12 Commits

49 changed files with 2717 additions and 241 deletions

View File

@@ -292,6 +292,7 @@ Text output is optimized for direct operator use. JSON output is optimized for a
- Usage errors and fatal setup errors exit non-zero and do not emit a JSON result document. - Usage errors and fatal setup errors exit non-zero and do not emit a JSON result document.
- `run --format json` emits a JSON result for partial destination failures, sets `ok` to `false`, includes result details and errors, and exits non-zero. - `run --format json` emits a JSON result for partial destination failures, sets `ok` to `false`, includes result details and errors, and exits non-zero.
- Warnings are included in JSON output and are printed in text output when relevant. - Warnings are included in JSON output and are printed in text output when relevant.
- `run` summaries include separate `replace_older`, `replace_conflict`, `replace_newer`, `replace_takeover`, and `force_replace` counters. Takeover destination actions include `takeover_mode` in JSON and text output.
## Diagnostics And Recovery ## Diagnostics And Recovery

View File

@@ -313,6 +313,7 @@ transform:
markdown_to_html: markdown_to_html:
enabled: true enabled: true
mode: sidecar mode: sidecar
css_href: /assets/report.css
``` ```
`publish.html` controls whether generated HTML outputs are published. When `publish.html` is `true`, `transform.markdown_to_html.enabled` must also be `true`. `publish.html` controls whether generated HTML outputs are published. When `publish.html` is `true`, `transform.markdown_to_html.enabled` must also be `true`.
@@ -322,10 +323,13 @@ Markdown transform fields:
- `transform.markdown_to_html.enabled`: enables Markdown-to-HTML generation for this destination. - `transform.markdown_to_html.enabled`: enables Markdown-to-HTML generation for this destination.
- `transform.markdown_to_html.mode`: optional. Accepted values are `sidecar` and `index`; default is `sidecar` when a Markdown transform block is present. - `transform.markdown_to_html.mode`: optional. Accepted values are `sidecar` and `index`; default is `sidecar` when a Markdown transform block is present.
- `transform.markdown_to_html.input`: optional source manifest path for `index` mode only. - `transform.markdown_to_html.input`: optional source manifest path for `index` mode only.
- `transform.markdown_to_html.css_href`: optional stylesheet href to link from generated HTML.
`sidecar` mode renders every manifest-listed `.md` file to a same-directory `.html` output. `index` mode renders one Markdown source to `index.html` at the destination bundle path. If `index` mode omits `input`, the selected source bundle must contain exactly one Markdown file. `sidecar` mode renders every manifest-listed `.md` file to a same-directory `.html` output. `index` mode renders one Markdown source to `index.html` at the destination bundle path. If `index` mode omits `input`, the selected source bundle must contain exactly one Markdown file.
At least one output type must be enabled. Enabled Markdown transforms are rejected when `publish.html` is `false`, and `input` is rejected unless `mode` is `index`. `css_href` may be an absolute `http` or `https` URL, a root-relative path such as `/assets/report.css`, or a relative URL path such as `assets/report.css`. Query strings are allowed. `distributor` injects the href as a `<link rel="stylesheet">` element but does not copy, publish, verify, or manage the CSS file solely because `css_href` is set.
At least one output type must be enabled. Enabled Markdown transforms are rejected when `publish.html` is `false`, `input` is rejected unless `mode` is `index`, and `css_href` is rejected when the Markdown transform is disabled.
## Destination Path Mapping ## Destination Path Mapping
@@ -412,7 +416,27 @@ pipelines:
mode: sidecar mode: sidecar
``` ```
Every output path in a shared root belongs to exactly one `pipeline_id` and `destination_id`. A different owner planning the same path fails as a conflict. Every output path in a shared root belongs to exactly one `pipeline_id` and `destination_id`. A different owner planning the same path fails as a conflict unless `takeover.mode` allows the managed output path to move to the current owner.
## Takeover Policy
```yaml
takeover:
mode: same_pipeline
```
- `takeover.mode`: optional. Accepted values are `same_pipeline`, `same_source`, `any_managed`, and `never`; default is `same_pipeline`.
Takeover controls when a destination may normally replace valid distributor-managed state whose pipeline, destination, source identity, or shared-root output owner differs from the current publication.
- `same_pipeline`: replace managed state owned by the same pipeline. The previous destination id and source id may differ.
- `same_source`: replace managed state only when the existing source manifest id matches the current source id.
- `any_managed`: replace any valid distributor-managed state at the selected destination bundle path.
- `never`: do not replace identity or source conflicts without the explicit forced replacement workflow.
For shared-root state, `same_pipeline` permits taking over output paths owned by another destination in the same pipeline, `same_source` permits taking over output paths whose owner records the same source manifest id, and `any_managed` permits taking over output paths owned by any valid shared-root owner. Unrelated owner records and non-conflicting outputs remain managed by their existing owners.
Takeover does not apply to unmanaged content, invalid destination state, same-created digest conflicts, or same-source destination-newer comparisons.
## Reconciliation Policy ## Reconciliation Policy
@@ -486,7 +510,7 @@ Transfer fields and accepted values:
- `transfer.on_destination_newer`: `skip`, `replace`, or `fail`. Default: `skip`. - `transfer.on_destination_newer`: `skip`, `replace`, or `fail`. Default: `skip`.
- `transfer.on_conflict`: `fail` or `replace`. Default: `fail`. - `transfer.on_conflict`: `fail` or `replace`. Default: `fail`.
`replace` for `on_destination_newer` and `on_conflict` is honored only when `run --force` is supplied. There is no config field that enables forced replacement by default. `replace` for `on_destination_newer` and `on_conflict` applies only to valid distributor-managed destination state. Unmanaged destination content and invalid destination state still require the explicit `run --force` workflow where supported.
## Size And Duration Values ## Size And Duration Values
@@ -525,6 +549,7 @@ Defaults are applied after YAML decoding and before validation:
- `links.primary: auto` when a `links` block is present and `primary` is omitted - `links.primary: auto` when a `links` block is present and `primary` is omitted
- `state.mode: single_owner` - `state.mode: single_owner`
- `reconciliation.mode: replace` - `reconciliation.mode: replace`
- `takeover.mode: same_pipeline`
- `retention.prune.enabled: false` - `retention.prune.enabled: false`
- `transfer.on_destination_same: skip` - `transfer.on_destination_same: skip`
- `transfer.on_destination_older: replace` - `transfer.on_destination_older: replace`

View File

@@ -96,9 +96,11 @@ Destination reconciliation applies when destination state is older than the sour
- `replace`: for single-owner state, delete managed output paths recorded in `outputs` plus `.distributor.json`, require the destination bundle path to be empty afterward, write the newly planned outputs, and write state whose `outputs` are exactly that new planned set. For shared-root state, delete only the current owner's omitted outputs and preserve unrelated owners. - `replace`: for single-owner state, delete managed output paths recorded in `outputs` plus `.distributor.json`, require the destination bundle path to be empty afterward, write the newly planned outputs, and write state whose `outputs` are exactly that new planned set. For shared-root state, delete only the current owner's omitted outputs and preserve unrelated owners.
- `merge`: retain managed output paths omitted from the new plan, overwrite planned paths only when they are already recorded in existing state, fail when a newly planned path exists in storage but is not recorded as managed, and write state whose `outputs` are the cumulative managed set. - `merge`: retain managed output paths omitted from the new plan, overwrite planned paths only when they are already recorded in existing state, fail when a newly planned path exists in storage but is not recorded as managed, and write state whose `outputs` are the cumulative managed set.
Takeover replacement applies when valid managed state has an identity, source, or shared-root output-owner mismatch and destination `takeover.mode` permits the current publication to take ownership. It uses bounded managed replacement behavior. For shared-root state, only taken-over output records and the current owner records are rewritten; unrelated owner records and non-conflicting outputs remain managed by their existing owners.
Top-level `links.primary_url` is selected from the newly planned outputs for the current publication. Retained outputs keep their existing per-output URL metadata. Top-level `links.primary_url` is selected from the newly planned outputs for the current publication. Retained outputs keep their existing per-output URL metadata.
If a merge publication fails after writing outputs, cleanup removes only newly created outputs from that failed attempt. Previously managed overwritten paths remain managed and are not removed by failed-attempt cleanup. If a same-source merge publication fails after writing outputs, cleanup removes only newly created outputs from that failed attempt. Previously managed overwritten paths remain managed and are not removed by failed-attempt cleanup. Takeover replacement does not retain omitted outputs through merge reconciliation.
## Comparison Semantics ## Comparison Semantics
@@ -106,15 +108,16 @@ If a merge publication fails after writing outputs, cleanup removes only newly c
- No state and no content: publish new outputs. - No state and no content: publish new outputs.
- No state and existing content: treat the destination as unmanaged. - No state and existing content: treat the destination as unmanaged.
- Shared-root state without the current owner: publish new outputs for that owner if planned paths do not collide with other owners or unmanaged content. - Shared-root state without the current owner: publish new outputs for that owner if planned paths do not collide with unmanaged content or with other owners that `takeover.mode` does not permit.
- Matching embedded source manifest: skip. - Matching embedded source manifest: skip.
- Same source id with older `created`: replace if policy allows. - Same source id with older `created`: replace if policy allows.
- Same source id with newer `created`: skip by default. - Same source id with newer `created`: skip by default, or replace when `transfer.on_destination_newer: replace` is configured.
- Same source id and same `created` with different digest: conflict. - Same source id and same `created` with different digest: conflict by default, or replace when `transfer.on_conflict: replace` is configured.
- Different source id, pipeline id, or destination id: conflict. - Different source id, pipeline id, or destination id in single-owner state: conflict unless `takeover.mode` permits managed ownership transfer or `transfer.on_conflict: replace` is configured.
- Shared-root output path owned by a different owner: conflict unless `takeover.mode` permits managed ownership transfer or `transfer.on_conflict: replace` is configured.
- Invalid state JSON or invalid state fields: conflict. - Invalid state JSON or invalid state fields: conflict.
Normal single-owner replacement deletes only managed output paths recorded in `outputs` plus `.distributor.json`. Shared-root replacement deletes only omitted outputs for the current owner. Merge publication retains omitted managed outputs. Forced replacement deletes the bounded destination bundle path. Normal single-owner replacement deletes only managed output paths recorded in `outputs` plus `.distributor.json`. Shared-root replacement deletes only omitted outputs for the current owner. Merge publication retains omitted managed outputs for same-source replacement. Forced replacement deletes the bounded destination bundle path.
## State Repair Semantics ## State Repair Semantics
@@ -238,7 +241,7 @@ For shared-root state:
If `state.mode: shared_root` is configured and existing state is a compatible single-owner `.distributor.json` for the same pipeline id and destination id, the next successful publish writes schema version `3` shared-root state for that owner. If `state.mode: shared_root` is configured and existing state is a compatible single-owner `.distributor.json` for the same pipeline id and destination id, the next successful publish writes schema version `3` shared-root state for that owner.
If existing single-owner state belongs to a different pipeline or destination, publish fails as a conflict. `distributor` does not implicitly take over unrelated state or unmanaged files. If `state.mode: shared_root` is configured and existing single-owner state belongs to a different pipeline or destination, publish fails as a conflict. `distributor` does not implicitly convert unrelated single-owner state or take over unmanaged files during shared-root migration.
## Boundaries ## Boundaries

View File

@@ -10,7 +10,7 @@ Rendering uses `github.com/yuin/goldmark`. The exact version is pinned in `go.mo
## Renderer Behavior ## Renderer Behavior
The transformer constructs `goldmark.New()` with no project-specific extensions, parser options, renderer options, templates, CSS, or metadata injection. The transformer constructs `goldmark.New()` with no project-specific extensions, parser options, renderer options, templates, or source manifest metadata injection.
Supported output modes: Supported output modes:
@@ -19,6 +19,8 @@ Supported output modes:
In `index` mode, `transform.markdown_to_html.input` may name the source manifest path to render. If `input` is omitted, the source manifest must list exactly one `.md` file. The selected input must be a clean relative source path, must be listed in the source manifest, and must end in `.md`. In `index` mode, `transform.markdown_to_html.input` may name the source manifest path to render. If `input` is omitted, the source manifest must list exactly one `.md` file. The selected input must be a clean relative source path, must be listed in the source manifest, and must end in `.md`.
When `transform.markdown_to_html.css_href` is set, generated HTML includes a stylesheet link in the document head. The href may be an absolute HTTP(S) URL, a root-relative path, or a relative URL path. Distributor treats this as a link reference only; it does not copy, publish, verify, or manage the CSS file solely because `css_href` is configured.
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.
## HTML Wrapper ## HTML Wrapper
@@ -28,10 +30,11 @@ Rendered Markdown body HTML is wrapped in a fixed document shell:
- `<!doctype html>` - `<!doctype html>`
- `<html lang="en">` - `<html lang="en">`
- UTF-8 `<meta charset>` - UTF-8 `<meta charset>`
- optional `<link rel="stylesheet" href="...">` when `css_href` is configured
- empty `<title>` - empty `<title>`
- `<body>` containing the rendered Markdown body - `<body>` containing the rendered Markdown body
The wrapper is deterministic and does not read configuration, templates, CSS, or source manifest metadata. The wrapper is deterministic. When `css_href` is omitted, the generated wrapper is unchanged from the unstyled output. When `css_href` is configured, its escaped link element is part of the generated output bytes.
## Output Metadata ## Output Metadata

View File

@@ -52,7 +52,7 @@ The adapter uses these S3 operations:
Writes buffer the input and set `ContentLength`. If no content type is supplied by the caller, the adapter infers a content type from the logical path. Writes buffer the input and set `ContentLength`. If no content type is supplied by the caller, the adapter infers a content type from the logical path.
Normal replacement and failed-write cleanup delete only managed output objects plus `.distributor.json`. Merge publication retains omitted managed objects and may overwrite existing managed objects. Forced replacement deletes objects under the bounded destination bundle prefix. The backend does not manage bucket versioning, lifecycle rules, object lock, or delete markers. Normal replacement and failed-write cleanup delete only managed output objects plus `.distributor.json`. Same-source merge publication retains omitted managed objects and may overwrite existing managed objects. Takeover replacement does not retain omitted outputs through merge reconciliation. Forced replacement deletes objects under the bounded destination bundle prefix. The backend does not manage bucket versioning, lifecycle rules, object lock, or delete markers.
## Error Mapping ## Error Mapping

View File

@@ -54,7 +54,7 @@ The configured `path` is the backend root. All source discovery, destination pat
The adapter rejects symlink ancestors for reads and writes. Reads require regular files. Writes create parent directories and prefer atomic temp-file-plus-rename writes when requested. Walk output is sorted through the shared storage walker. The adapter rejects symlink ancestors for reads and writes. Reads require regular files. Writes create parent directories and prefer atomic temp-file-plus-rename writes when requested. Walk output is sorted through the shared storage walker.
Managed cleanup and normal replacement delete only managed output paths plus `.distributor.json`. Merge publication retains omitted managed paths and may overwrite existing managed paths. Forced replacement deletes the bounded destination bundle path. Managed cleanup and normal replacement delete only managed output paths plus `.distributor.json`. Same-source merge publication retains omitted managed paths and may overwrite existing managed paths. Takeover replacement does not retain omitted outputs through merge reconciliation. Forced replacement deletes the bounded destination bundle path.
## Boundaries ## Boundaries

View File

@@ -20,7 +20,7 @@ User-facing command parsing stays in `internal/cli`, including `reconcile-state`
## Config Fields Used ## Config Fields Used
The package consumes the loaded `config.Config`: `server.http`, `secrets.directory`, pipeline ids, source and destination backend fields, validation policy, publish policy, transform policy, path mapping, links, state policy, reconciliation policy, retention policy, and transfer policy. The package consumes the loaded `config.Config`: `server.http`, `secrets.directory`, pipeline ids, source and destination backend fields, validation policy, publish policy, transform policy, path mapping, links, state policy, reconciliation policy, takeover policy, retention policy, and transfer policy.
Config fields are validated and defaulted by `internal/config` before app workflows use them. Config fields are validated and defaulted by `internal/config` before app workflows use them.
@@ -32,7 +32,7 @@ The app layer registers default transforms, including Markdown-to-HTML, and supp
## State And Manifest Behavior ## State And Manifest Behavior
Run workflows discover and validate source bundles through `internal/bundle`. Destination state actions are prepared and written through `internal/publish` and `internal/state`; the app layer records report projections of those actions and results. Run workflows discover and validate source bundles through `internal/bundle`. Destination state actions are prepared and written through `internal/publish` and `internal/state`; the app layer records report projections of those actions and results. Run summaries count older-state, conflict, newer-state, takeover, and explicit forced replacements separately.
Reconcile-state workflows load one configured pipeline/destination selector, open that destination root, parse the root `.distributor.json`, and report missing managed output records plus unmanaged storage entries. Managed output existence checks use storage `Stat`; unmanaged reporting uses bounded storage `Walk` and excludes `.distributor.json` plus all paths already recorded as managed. Apply mode removes missing managed output records from state and rewrites valid state only; dry-run reports the same repair without writing. Text output reports `changed`, `would_change`, or `unchanged`; JSON output uses the shared app envelope. It does not validate output digests, delete destination files, adopt unmanaged files, or rewrite invalid or mismatched state. Reconcile-state workflows load one configured pipeline/destination selector, open that destination root, parse the root `.distributor.json`, and report missing managed output records plus unmanaged storage entries. Managed output existence checks use storage `Stat`; unmanaged reporting uses bounded storage `Walk` and excludes `.distributor.json` plus all paths already recorded as managed. Apply mode removes missing managed output records from state and rewrites valid state only; dry-run reports the same repair without writing. Text output reports `changed`, `would_change`, or `unchanged`; JSON output uses the shared app envelope. It does not validate output digests, delete destination files, adopt unmanaged files, or rewrite invalid or mismatched state.

View File

@@ -18,7 +18,7 @@ The canonical user-facing config reference is `docs/config.md`.
## Config Fields Used ## Config Fields Used
The package defines all user-visible config fields: `server.http`, `secrets`, `pipelines`, source and destination backend fields, validation policy, publish policy, transform policy, path mapping, links, state policy, reconciliation policy, retention policy, and transfer policy. The package defines all user-visible config fields: `server.http`, `secrets`, `pipelines`, source and destination backend fields, validation policy, publish policy, transform policy, path mapping, links, state policy, reconciliation policy, takeover policy, retention policy, and transfer policy.
## Adapters Used ## Adapters Used
@@ -26,7 +26,7 @@ No external storage adapters are used directly. The package exposes normalized c
## State And Manifest Behavior ## State And Manifest Behavior
The package does not parse source manifests or destination state. It validates config values that later affect manifest validation and destination state, such as publish/transform combinations, links, state policy, reconciliation policy, retention policy, transfer policy, backend roots, S3 prefix shape, and HTTP upload source settings. The package does not parse source manifests or destination state. It validates config values that later affect manifest validation and destination state, such as publish/transform combinations, links, state policy, reconciliation policy, takeover policy, retention policy, transfer policy, backend roots, S3 prefix shape, and HTTP upload source settings.
## Skip And Resume Behavior ## Skip And Resume Behavior

View File

@@ -8,9 +8,9 @@ Audience: developers and LLM coding agents changing `internal/publish`.
## Inputs And Outputs ## Inputs And Outputs
Inputs are a source bundle, source backend, destination backend, pipeline id, destination id, destination bundle path, path mapping mode, publish policy, transform policy, optional link policy, state policy, reconciliation policy, transformer resolver, transfer policy, distributor version, and force flag. Inputs are a source bundle, source backend, destination backend, pipeline id, destination id, destination bundle path, path mapping mode, publish policy, transform policy, optional link policy, state policy, reconciliation policy, takeover policy, transformer resolver, transfer policy, distributor version, and force flag.
Output from planning is a `Plan` with action, reason, destination identity, selected outputs, state mode, owner scope, reconciliation mode, optional existing single-owner or shared-root state, optional primary URL, and force metadata. Shared-root plans also expose other-owner outputs to preserve, current-owner outputs retained by merge, current-owner outputs deleted by replace, and current-owner outputs to write. Execution writes selected source outputs, generated outputs, and `.distributor.json` for executable publish or replacement actions. Output from planning is a `Plan` with action, reason, destination identity, selected outputs, state mode, owner scope, reconciliation mode, takeover mode, optional existing single-owner or shared-root state, optional primary URL, and force metadata. Shared-root plans also expose other-owner outputs to preserve, taken-over outputs, current-owner outputs retained by merge, current-owner outputs deleted by replace or takeover, and current-owner outputs to write. Execution writes selected source outputs, generated outputs, and `.distributor.json` for executable publish or replacement actions.
## Boundaries ## Boundaries
@@ -20,7 +20,7 @@ External destination state semantics are documented in `docs/integrations/destin
## Config Fields Used ## Config Fields Used
The package consumes already-defaulted config values for destination `publish`, `transform`, `links`, `state`, `reconciliation`, `transfer`, and path mapping mode. It uses `config.ValidatePublishTransformPolicy` for publish/transform consistency. The package consumes already-defaulted config values for destination `publish`, `transform`, `links`, `state`, `reconciliation`, `takeover`, `transfer`, and path mapping mode. It uses `config.ValidatePublishTransformPolicy` for publish/transform consistency.
## Adapters Used ## Adapters Used
@@ -28,25 +28,25 @@ The package depends on `internal/storage.Backend` for source and destination IO,
## State And Manifest Behavior ## State And Manifest Behavior
Planning inspects destination state through `internal/state`, compares it with the source manifest, and maps comparison outcomes plus transfer policy into actions: `publish_new`, `replace_older`, `force_replace`, `skip_same`, `skip_destination_newer`, `fail_conflict`, or `fail_unmanaged`. Planning inspects destination state through `internal/state`, compares it with the source manifest, and maps comparison outcomes plus transfer and takeover policy into actions: `publish_new`, `replace_older`, `replace_conflict`, `replace_newer`, `replace_takeover`, `force_replace`, `skip_same`, `skip_destination_newer`, `fail_conflict`, or `fail_unmanaged`.
Single-owner destinations compare the whole destination state against the configured pipeline and destination ids. Shared-root destinations compare only the current owner scope, keyed by pipeline id and destination id. An absent shared-root owner is publishable for that owner unless a planned output collides with unmanaged storage content. Planned writes to a path owned by another shared-root owner fail as conflicts. Single-owner destinations compare the whole destination state against the configured pipeline and destination ids. Valid managed identity and source conflicts can become `replace_takeover` when `takeover.mode` allows them. Shared-root destinations compare only the current owner scope, keyed by pipeline id and destination id. An absent shared-root owner is publishable for that owner unless a planned output collides with unmanaged storage content. Planned writes to a path owned by another shared-root owner become `replace_takeover` when `takeover.mode` allows that managed output path to move to the current owner.
Execution writes destination state after selected outputs are written. Destination state includes copied source output metadata, generated output metadata, output timestamps, embedded source manifest, reconciliation metadata, link metadata when configured, pipeline id, destination id, and publication timestamps. Execution writes destination state after selected outputs are written. Destination state includes copied source output metadata, generated output metadata, output timestamps, embedded source manifest, reconciliation metadata, link metadata when configured, pipeline id, destination id, and publication timestamps.
## Skip And Resume Behavior ## Skip And Resume Behavior
`skip_same` and `skip_destination_newer` execute as no-ops. Replacement-mode single-owner updates remove managed output paths from existing state plus `.distributor.json`, verify the destination is empty, and write state whose outputs are exactly the new plan. Replacement-mode shared-root updates remove only current-owner omitted outputs and preserve unrelated owners. Merge-mode updates retain omitted managed outputs, overwrite only paths already recorded as managed, reject unmanaged destination path collisions, and write cumulative output state. Failed writes trigger cleanup where practical; merge cleanup removes only newly created outputs from the failed attempt. `skip_same` and `skip_destination_newer` execute as no-ops. Replacement-mode single-owner updates remove managed output paths from existing state plus `.distributor.json`, verify the destination is empty, and write state whose outputs are exactly the new plan. `replace_conflict` uses managed replacement mechanics and does not retain omitted outputs through merge reconciliation. `replace_newer` follows the same managed replacement and merge-retention rules as `replace_older`. `replace_takeover` uses managed replacement mechanics and does not retain omitted outputs through merge reconciliation. Replacement-mode shared-root updates remove only current-owner omitted outputs and preserve unrelated owners. Shared-root takeover rewrites only the taken-over output records and current owner records. Merge-mode same-source updates retain omitted managed outputs, overwrite only paths already recorded as managed, reject unmanaged destination path collisions, and write cumulative output state. Failed writes trigger cleanup where practical; same-source merge cleanup removes only newly created outputs from the failed attempt.
Shared-root execution writes schema version `3` state. It preserves unrelated owner records and outputs, updates only the publishing owner metadata, preserves root `created_at`, and updates root `updated_at` after successful state writes. Compatible single-owner state for the same pipeline and destination is converted to shared-root state on successful publish. Shared-root execution writes schema version `3` state. It preserves unrelated owner records and outputs, updates only the publishing owner metadata, preserves root `created_at`, and updates root `updated_at` after successful state writes. Compatible single-owner state for the same pipeline and destination is converted to shared-root state on successful publish.
Forced replacement is explicit per request and deletes the bounded destination bundle path before writing new outputs and state. Forced replacement is explicit per request and deletes the bounded destination bundle path before writing new outputs and state. Valid managed conflict and newer-state replacements are normal managed replacement actions when transfer policy allows them; they are not forced replacement actions.
Retention pruning is not part of publish execution and does not run automatically after a successful publish. The app-level prune workflow uses destination state after publication to select managed outputs for deletion. Retention pruning is not part of publish execution and does not run automatically after a successful publish. The app-level prune workflow uses destination state after publication to select managed outputs for deletion.
## Failure Behavior ## Failure Behavior
Planning fails for incomplete requests, invalid publish/transform policy, invalid state mode, invalid reconciliation mode, output path collisions, invalid destination state, unmanaged destination content without force, shared-root owner path conflicts, conflict outcomes not allowed by transfer policy, unresolved transforms, invalid Markdown output selection, and invalid link URL planning. Planning fails for incomplete requests, invalid publish/transform policy, invalid state mode, invalid reconciliation mode, output path collisions, invalid destination state, unmanaged destination content without force, shared-root owner path conflicts not allowed by `takeover.mode`, conflict outcomes not allowed by transfer policy, unresolved transforms, invalid Markdown output selection, and invalid link URL planning.
Execution fails on delete, read, transform output, unmanaged merge path collision, shared-root ownership conflict, write, state validation, state serialization, or context errors. Execution refuses actions that are not executable publish or replacement actions. Execution fails on delete, read, transform output, unmanaged merge path collision, shared-root ownership conflict, write, state validation, state serialization, or context errors. Execution refuses actions that are not executable publish or replacement actions.
@@ -65,7 +65,7 @@ Execution fails on delete, read, transform output, unmanaged merge path collisio
- Replacement reconciliation deletes only managed paths recorded in existing state plus `.distributor.json` for single-owner state, and only current-owner omitted outputs for shared-root state. - Replacement reconciliation deletes only managed paths recorded in existing state plus `.distributor.json` for single-owner state, and only current-owner omitted outputs for shared-root state.
- Merge reconciliation never adopts unmanaged content. - Merge reconciliation never adopts unmanaged content.
- Merge state output records are cumulative for the single owner. - Merge state output records are cumulative for the single owner.
- Shared-root planning is owner-scoped and preserves unrelated owner outputs. - Shared-root planning is owner-scoped, preserves unrelated owner outputs, and records taken-over managed output paths separately from unrelated owners.
- Shared-root execution writes owner-scoped changes without deleting unrelated owners. - Shared-root execution writes owner-scoped changes without deleting unrelated owners.
- Forced replacement deletes only within the supplied destination bundle path. - Forced replacement deletes only within the supplied destination bundle path.
- Destination state is written after selected outputs are written. - Destination state is written after selected outputs are written.

View File

@@ -44,7 +44,7 @@ Shared-root helper projections preserve output `created_at` for existing managed
## Skip And Resume Behavior ## Skip And Resume Behavior
Comparison is pure. It returns outcomes for absent state, unmanaged content, invalid state, pipeline/destination mismatch, same source manifest, older destination, newer destination, same-created digest conflict, and different source id conflict. It does not decide whether to skip, replace, force, or fail; publish planning maps outcomes to actions. Comparison is pure. It returns outcomes for absent state, unmanaged content, invalid state, pipeline/destination mismatch, same source manifest, older destination, newer destination, same-created digest conflict, and different source id conflict. Shared-root helpers expose structured output ownership conflicts. State code does not decide whether to skip, replace, take over, force, or fail; publish planning maps outcomes and conflicts to actions.
Shared-root comparison is owner-scoped. It compares only the owner keyed by the current pipeline id and destination id, treats an absent owner as absent destination state for that owner, and can compare compatible single-owner state for the current owner without converting unrelated single-owner state. Shared-root comparison is owner-scoped. It compares only the owner keyed by the current pipeline id and destination id, treats an absent owner as absent destination state for that owner, and can compare compatible single-owner state for the current owner without converting unrelated single-owner state.
@@ -74,7 +74,7 @@ Parsing rejects invalid JSON, trailing data, missing required fields, invalid ti
- Newly written single-owner state uses schema version `2`. - Newly written single-owner state uses schema version `2`.
- Schema version `1` state remains readable as replacement-mode single-owner state. - Schema version `1` state remains readable as replacement-mode single-owner state.
- Schema version `3` shared-root state is parsed and validated without converting unrelated single-owner state. - Schema version `3` shared-root state is parsed and validated without converting unrelated single-owner state.
- Shared-root owner updates preserve unrelated owners and reject planned path collisions with other owners. - Shared-root owner updates preserve unrelated owners. Publish planning removes taken-over output records before owner replacement when takeover policy allows a managed path to move owners.
- Missing-output repair helpers preserve unrelated owner records and outputs. - Missing-output repair helpers preserve unrelated owner records and outputs.
- Prune planning uses output `updated_at` and preserves unrelated shared-root owners. - Prune planning uses output `updated_at` and preserves unrelated shared-root owners.
- Generated outputs always record a transform id. - Generated outputs always record a transform id.

View File

@@ -67,11 +67,16 @@ Published destination bundle paths contain `.distributor.json`. See [Destination
- No destination state and no destination content: publish new outputs. - No destination state and no destination content: publish new outputs.
- Matching destination state: skip as already published. - Matching destination state: skip as already published.
- Older destination state for the same source id: replace if transfer policy allows it. - Older destination state for the same source id: replace if transfer policy allows it.
- Newer destination state: skip by default. - Newer destination state for the same source id: skip by default, or replace when `transfer.on_destination_newer: replace` is configured.
- Invalid destination state, identity mismatch, different source id, or same-created digest mismatch: fail by default. - Valid managed state with an identity, source, same-created digest, or shared-root output-owner mismatch: replace when destination `takeover.mode` allows it or, for remaining valid managed conflicts, when `transfer.on_conflict: replace` is configured.
- Invalid destination state, identity, source, same-created digest, or shared-root output-owner mismatches not allowed by `takeover.mode` or `transfer.on_conflict: replace`: fail by default.
- Content without `.distributor.json`: fail as unmanaged content by default. - Content without `.distributor.json`: fail as unmanaged content by default.
When destination state is older than the source, `transfer.on_destination_older` controls whether publication may proceed and `reconciliation.mode` controls how managed outputs are updated. When destination state is older or newer than the source, `transfer.on_destination_older` and `transfer.on_destination_newer` control whether publication may proceed and `reconciliation.mode` controls how managed outputs are updated.
When `transfer.on_conflict: replace` permits `replace_conflict`, the destination is valid managed state but does not match the current source, pipeline, destination, or same-created digest. `replace_conflict` rewrites the affected managed destination state and does not retain omitted outputs through merge reconciliation.
For takeover replacement, `reconciliation.mode: merge` does not retain omitted outputs from the previous source identity. The destination is rewritten as a managed replacement for the current source or shared-root owner.
`reconciliation.mode: replace` is the default. It deletes only managed output paths recorded in `.distributor.json` plus the state file, verifies the destination bundle path is empty, then writes the newly planned outputs and state. The new state `outputs` array is exactly the newly planned output set. `reconciliation.mode: replace` is the default. It deletes only managed output paths recorded in `.distributor.json` plus the state file, verifies the destination bundle path is empty, then writes the newly planned outputs and state. The new state `outputs` array is exactly the newly planned output set.
@@ -79,11 +84,11 @@ When destination state is older than the source, `transfer.on_destination_older`
For both modes, retained or overwritten paths are identified only from `.distributor.json`; unmanaged files are not adopted. For both modes, retained or overwritten paths are identified only from `.distributor.json`; unmanaged files are not adopted.
For `state.mode: shared_root`, one destination root may contain outputs from multiple pipeline/destination owners. Comparisons, replacement, and merge retention are scoped to the current owner. Outputs owned by other owners are preserved. A planned output path owned by another owner fails as a conflict, and a planned path that exists in storage but is not recorded in state fails as unmanaged content by default. For `state.mode: shared_root`, one destination root may contain outputs from multiple pipeline/destination owners. Comparisons, replacement, and merge retention are scoped to the current owner. Outputs owned by other owners are preserved unless a planned output path is owned by another valid owner and `takeover.mode` allows moving that path to the current owner. A planned path that exists in storage but is not recorded in state fails as unmanaged content by default.
If `state.mode: shared_root` is configured on a destination whose existing single-owner state belongs to the same pipeline and destination, the next successful publish converts that state file to shared-root schema. Existing single-owner state for a different pipeline or destination remains a conflict. If `state.mode: shared_root` is configured on a destination whose existing single-owner state belongs to the same pipeline and destination, the next successful publish converts that state file to shared-root schema. Existing single-owner state for a different pipeline or destination remains a conflict.
If a write fails after some outputs were written, `distributor` attempts cleanup before returning the error. In `replace` mode, cleanup removes outputs written during that failed attempt. In `merge` mode, cleanup removes only newly created outputs from that failed attempt; overwritten managed outputs are left in place because they previously belonged to the managed set. Operators should still inspect the destination after a failed write before retrying. If a write fails after some outputs were written, `distributor` attempts cleanup before returning the error. In `replace` mode and takeover replacement, cleanup removes outputs written during that failed attempt. In same-source `merge` mode, cleanup removes only newly created outputs from that failed attempt; overwritten managed outputs are left in place because they previously belonged to the managed set. Operators should still inspect the destination after a failed write before retrying.
Fan-out destinations are independent. If one destination fails after planning or execution begins, later destinations are still attempted. The command exits non-zero if any destination failed. Fan-out destinations are independent. If one destination fails after planning or execution begins, later destinations are still attempted. The command exits non-zero if any destination failed.
@@ -150,12 +155,15 @@ For single-owner state, the state owner must match the selected pipeline and des
`run --dry-run` loads config, resolves credentials, discovers source bundles, opens destinations, inspects destination state, builds publish plans, and prints actions. It does not write outputs, `.distributor.json`, or SSH `known_hosts` entries. For reconciliation, dry runs report the same high-level action labels as execution; inspect the configured destination's `reconciliation.mode` to determine whether `replace_older` will replace the managed set or merge into it. `run --dry-run` loads config, resolves credentials, discovers source bundles, opens destinations, inspects destination state, builds publish plans, and prints actions. It does not write outputs, `.distributor.json`, or SSH `known_hosts` entries. For reconciliation, dry runs report the same high-level action labels as execution; inspect the configured destination's `reconciliation.mode` to determine whether `replace_older` will replace the managed set or merge into it.
For shared-root destinations, dry runs are owner-scoped. A `replace_older` action replaces or merges only the current owner according to `reconciliation.mode`; unrelated owners remain managed by the shared-root state. For shared-root destinations, dry runs are owner-scoped. A `replace_older` action replaces or merges only the current owner according to `reconciliation.mode`; unrelated owners remain managed by the shared-root state. Paths owned by another owner fail as conflicts unless `takeover.mode` allows ownership transfer.
Review these action labels before publishing: Review these action labels before publishing:
- `publish_new`: destination state is absent, or a shared-root owner is absent and planned paths are publishable. - `publish_new`: destination state is absent, or a shared-root owner is absent and planned paths are publishable.
- `replace_older`: destination state is older than the source. - `replace_older`: destination state is older than the source.
- `replace_newer`: destination state is newer than the source and `transfer.on_destination_newer: replace` allows managed replacement.
- `replace_conflict`: destination state is valid managed state with a conflict and `transfer.on_conflict: replace` allows managed replacement.
- `replace_takeover`: destination state is valid managed state and `takeover.mode` allows replacement across an identity, source, or shared-root output-owner mismatch.
- `skip_same`: destination state already matches the source. - `skip_same`: destination state already matches the source.
- `skip_destination_newer`: destination state is newer than the source and is skipped. - `skip_destination_newer`: destination state is newer than the source and is skipped.
- `force_replace`: destructive replacement selected because `--force` is present and policy permits it. - `force_replace`: destructive replacement selected because `--force` is present and policy permits it.
@@ -163,7 +171,7 @@ Review these action labels before publishing:
Fixed destinations add fixed-path warnings during dry runs, including the selected source bundle and replacement warnings when the destination root would be replaced. Fixed destinations add fixed-path warnings during dry runs, including the selected source bundle and replacement warnings when the destination root would be replaced.
JSON output includes warnings, pipeline summaries, destination action records, output records, URLs when configured, final counters, and partial failure details. Fatal setup failures such as unreadable config or invalid secrets do not produce a JSON result document. Text and JSON summaries count `publish_new`, `replace_older`, `replace_conflict`, `replace_newer`, `replace_takeover`, `force_replace`, skipped, and failed destinations separately. Takeover action records include the configured takeover mode and the conflict reason. JSON output includes warnings, pipeline summaries, destination action records, output records, URLs when configured, final counters, and partial failure details. Fatal setup failures such as unreadable config or invalid secrets do not produce a JSON result document.
## Forced Replacement Workflow ## Forced Replacement Workflow
@@ -174,10 +182,7 @@ go run ./cmd/distributor run --config <config-path> --dry-run --force
go run ./cmd/distributor run --config <config-path> --force go run ./cmd/distributor run --config <config-path> --force
``` ```
Forced replacement can claim unmanaged non-empty destination paths. State conflicts require both `--force` and transfer policy that permits replacement: Forced replacement can claim unmanaged non-empty destination paths and is reserved for exceptional destructive replacement. Valid managed newer state and valid managed conflict state use `replace_newer` and `replace_conflict` when the corresponding transfer policy allows replacement; they do not require `--force`.
- newer destination state requires `transfer.on_destination_newer: replace`;
- conflict outcomes require `transfer.on_conflict: replace`.
Forced replacement deletes the current destination bundle path before writing outputs and state. It does not delete parent paths, sibling paths, or storage outside the destination bundle path. For fixed destinations, the destination bundle path is the backend root, so a forced replacement can clear that configured root. Forced replacement deletes the current destination bundle path before writing outputs and state. It does not delete parent paths, sibling paths, or storage outside the destination bundle path. For fixed destinations, the destination bundle path is the backend root, so a forced replacement can clear that configured root.
@@ -267,7 +272,7 @@ S3 execution uses the AWS SDK for Go v2. See [S3-Compatible Storage Integration]
When explicit S3 credential variable names are configured, both must resolve to non-empty values through the process environment or `secrets.directory`. When omitted, the AWS SDK default credential chain is used as-is. When explicit S3 credential variable names are configured, both must resolve to non-empty values through the process environment or `secrets.directory`. When omitted, the AWS SDK default credential chain is used as-is.
Normal single-owner replacement and failed-write cleanup delete only managed output objects recorded in `.distributor.json` plus the state object. Shared-root replacement deletes only current-owner omitted output objects and rewrites the shared state object. Merge publication retains omitted managed objects and may overwrite existing managed objects. Forced replacement deletes objects under the bounded destination bundle prefix. Distributor does not manage bucket versioning or delete markers. Normal single-owner replacement and failed-write cleanup delete only managed output objects recorded in `.distributor.json` plus the state object. Shared-root replacement deletes only current-owner omitted output objects and rewrites the shared state object. Same-source merge publication retains omitted managed objects and may overwrite existing managed objects. Takeover replacement does not retain omitted outputs through merge reconciliation. Forced replacement deletes objects under the bounded destination bundle prefix. Distributor does not manage bucket versioning or delete markers.
## Secrets Operation ## Secrets Operation
@@ -282,7 +287,7 @@ Use these recovery boundaries:
- For source validation failures, regenerate the source bundle and manifest together. - For source validation failures, regenerate the source bundle and manifest together.
- For an empty or missing destination, rerun after fixing config or storage access. - For an empty or missing destination, rerun after fixing config or storage access.
- For unmanaged destination content, move unrelated files aside or use a different destination path before publishing. - For unmanaged destination content, move unrelated files aside or use a different destination path before publishing.
- For shared-root ownership conflicts, change one owner so it writes a different destination path, or use a separate destination root. - For shared-root ownership conflicts, change one owner so it writes a different destination path, use a separate destination root, or configure `takeover.mode` when the current owner should take over valid managed output paths.
- For missing managed output files recorded in state, run `reconcile-state --dry-run`, then apply `reconcile-state` if the missing files should no longer be considered managed. - For missing managed output files recorded in state, run `reconcile-state --dry-run`, then apply `reconcile-state` if the missing files should no longer be considered managed.
- For configured retention cleanup, run `prune --dry-run`, then apply `prune --apply` after reviewing the managed output list. - For configured retention cleanup, run `prune --dry-run`, then apply `prune --apply` after reviewing the managed output list.
- For failed writes, inspect the destination bundle path, remove only confirmed partial outputs if needed, then rerun `--dry-run`. In merge mode, retained outputs may be intentional managed outputs from the prior state. - For failed writes, inspect the destination bundle path, remove only confirmed partial outputs if needed, then rerun `--dry-run`. In merge mode, retained outputs may be intentional managed outputs from the prior state.

View File

@@ -169,9 +169,9 @@ Destination comparison rules are based on `.distributor.json`:
- No `.distributor.json`: publish normally only if the destination bundle path is empty. - No `.distributor.json`: publish normally only if the destination bundle path is empty.
- Existing state embeds the same normalized source manifest: skip as already published. - Existing state embeds the same normalized source manifest: skip as already published.
- Existing state has the same source id and an older source `created`: replace, subject to destructive-operation safety rules. - Existing state has the same source id and an older source `created`: replace, subject to destructive-operation safety rules.
- Existing state has the same source id and a newer source `created`: skip because the destination is newer than the source. - Existing state has the same source id and a newer source `created`: skip by default, or replace when `transfer.on_destination_newer: replace` is configured.
- Existing state has the same source id and same `created` but different digest: fail as a conflict. - Existing state has the same source id and same `created` but different digest: fail by default, or replace as valid managed conflict state when `transfer.on_conflict: replace` is configured.
- Existing state has a different source id: fail as a conflict. - Existing valid managed state has a different source id, pipeline id, destination id, or shared-root output owner: replace when destination `takeover.mode` permits that ownership transfer, or replace as valid managed conflict state when `transfer.on_conflict: replace` is configured; otherwise fail as a conflict.
For older destination state, destination `reconciliation.mode` controls output updates. `replace` rewrites the managed output set to match the new plan. `merge` retains omitted managed outputs, overwrites only existing managed paths, and rejects planned paths that collide with unmanaged storage content. For older destination state, destination `reconciliation.mode` controls output updates. `replace` rewrites the managed output set to match the new plan. `merge` retains omitted managed outputs, overwrites only existing managed paths, and rejects planned paths that collide with unmanaged storage content.
@@ -264,6 +264,7 @@ Pipeline configuration should express:
- per-destination transform policy; - per-destination transform policy;
- per-destination public link policy; - per-destination public link policy;
- validation behavior; - validation behavior;
- per-destination takeover behavior;
- destination conflict/replacement behavior. - destination conflict/replacement behavior.
## Modules and Registries ## Modules and Registries

View File

@@ -18,7 +18,7 @@ Use it with `docs/policy/architecture.md` and `docs/policy/documentation.md`.
- `internal/adapters/ssh`: SSH/SFTP backend. - `internal/adapters/ssh`: SSH/SFTP backend.
- `internal/adapters/s3`: S3-compatible object storage backend. - `internal/adapters/s3`: S3-compatible object storage backend.
- `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, takeover 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 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.

View File

@@ -43,6 +43,7 @@ Canonical homes:
- project purpose and quickstart: `README.md` - project purpose and quickstart: `README.md`
- development principles: `docs/policy/architecture.md` - development principles: `docs/policy/architecture.md`
- public HTTP API reference: `docs/api.md`
- configuration reference: `docs/config.md` - configuration reference: `docs/config.md`
- CLI reference: `docs/cli.md` - CLI reference: `docs/cli.md`
- operations and recovery: `docs/operations.md` - operations and recovery: `docs/operations.md`
@@ -122,6 +123,22 @@ Recommended:
- `docs/troubleshooting.md` - `docs/troubleshooting.md`
- validated examples under `examples/` - validated examples under `examples/`
### Public HTTP API service
Required:
- `docs/api.md`
- `docs/cli.md`, if CLI-based
- `docs/config.md`, if config-driven
- `docs/operations.md`
- `docs/internal/`
- `docs/policy/development.md`
Recommended:
- `docs/troubleshooting.md`
- `docs/consumers/`, for task-oriented client integration guides
- `docs/integrations/`, for upstream/downstream service contracts
- validated examples under `examples/`
### Project with public packages or consumer APIs ### Project with public packages or consumer APIs
Required: Required:
@@ -173,6 +190,32 @@ It should include:
For small projects, this file may be brief. It may simply state that the project is intentionally narrow, monolithic, and dependency-light. For small projects, this file may be brief. It may simply state that the project is intentionally narrow, monolithic, and dependency-light.
### docs/api.md
**Audience:** external HTTP API consumers, developers, LLM coding agents integrating by HTTP
Required for projects whose primary public interface is HTTP.
`docs/api.md` is the canonical public HTTP API contract. It should be normative for external consumers and should not be duplicated by README, operations docs, consumer guides, or integration docs.
It should include:
1. base URL conventions;
2. authentication and authorization behavior, if implemented;
3. response envelope;
4. supported media types and content negotiation behavior;
5. shared query parameters;
6. endpoint reference grouped by route family;
7. request parameters and validation rules;
8. response fields, units, nullability, and optionality;
9. error response shape and status codes;
10. pagination, caching, rate-limit, idempotency, and retry behavior, if implemented;
11. compact request and response examples.
It must document only implemented endpoints and behavior. Planned endpoints, proposed fields, future filters, and experimental response shapes belong only under `docs/roadmap/`.
For HTTP API projects, `docs/consumers/` may provide task-oriented client integration guides, but those guides should link to `docs/api.md` for the authoritative endpoint contract.
### docs/policy/development.md ### docs/policy/development.md
**Audience:** developers, LLM coding agents **Audience:** developers, LLM coding agents
@@ -264,6 +307,8 @@ Required for projects with public packages, SDKs, client APIs, plugin APIs, or o
This directory describes how an external codebase should consume the project's public API. It should be task-oriented and copyable where useful. It is not the place for internal implementation details or operator procedures. This directory describes how an external codebase should consume the project's public API. It should be task-oriented and copyable where useful. It is not the place for internal implementation details or operator procedures.
For projects whose public API is HTTP, `docs/consumers/` is not required, and it should not duplicate the endpoint reference in `docs/api.md`. If present, it may provide practical integration workflows, client-specific examples, or migration notes that link back to `docs/api.md`.
`docs/consumers/api.md` should provide the consumer-facing overview and primary implementation workflow. It should include: `docs/consumers/api.md` should provide the consumer-facing overview and primary implementation workflow. It should include:
1. intended consumer audience and use cases; 1. intended consumer audience and use cases;
@@ -330,6 +375,8 @@ Required for projects that depend on external CLIs, APIs, services, protocols, o
This directory contains concise, versioned reference notes for external integration contracts. It should document only the parts of the external system that this project actually uses or exposes. This directory contains concise, versioned reference notes for external integration contracts. It should document only the parts of the external system that this project actually uses or exposes.
For public HTTP API services, `docs/integrations/` should document upstream, downstream, storage, protocol, or runtime contracts that the service depends on or bridges. It should not become a second copy of the public HTTP endpoint reference; that belongs in `docs/api.md`.
Use one file per integration where useful. Use one file per integration where useful.
## Examples Directory ## Examples Directory
@@ -385,9 +432,10 @@ Before merging documentation changes, verify:
- README is concise and orientation-focused. - README is concise and orientation-focused.
- `docs/policy/architecture.md` describes development principles. - `docs/policy/architecture.md` describes development principles.
- `docs/api.md` is the canonical HTTP contract for HTTP API services.
- Future work appears only under `docs/roadmap/`. - Future work appears only under `docs/roadmap/`.
- User-facing docs avoid unnecessary internals. - User-facing docs avoid unnecessary internals.
- Consumer-facing docs explain public APIs without duplicating integration contracts. - Consumer-facing docs explain public APIs without duplicating HTTP endpoint or integration contracts.
- Developer-facing docs preserve boundaries and invariants. - Developer-facing docs preserve boundaries and invariants.
- Config examples match the schema. - Config examples match the schema.
- CLI examples match real commands and flags. - CLI examples match real commands and flags.

283
docs/roadmap/catalog.md Normal file
View File

@@ -0,0 +1,283 @@
# Catalog State And Destination Workflow Roadmap
This roadmap records the intended first-class state model and destination
workflow configuration for replacement and additive publication workflows.
Current `single_owner` and `shared_root` state are oriented around comparing a
destination owner to one latest source manifest. That works well for replacement
workflows, where a producer maintains a curated source of truth and
`distributor` makes a destination match it. It is a poor fit for additive
workflows, where each run contributes new or updated output paths while
preserving unrelated managed outputs from previous runs and other pipelines.
The target model is a current-state catalog: `.distributor.json` records the
currently managed output paths at a destination root, and each output record
stores its current owner, compact source identity, content digest, and update
metadata. It is not intended to be an audit log.
Both replacement and additive workflows should use the same catalog state shape.
The workflow choice is runtime policy from destination config, not persisted
state.
## Locked Decisions
- Add one destination state mode named `catalog` for both replacement and
additive workflows.
- Catalog state writes `.distributor.json` schema version `4`.
- Add a destination-level `workflow` setting with accepted values
`replacement` and `additive`.
- Default `workflow` to `additive` because it is the least destructive workflow.
- `workflow` replaces the normal user-facing need to combine `state.mode`,
`reconciliation.mode`, `takeover.mode`, and transfer conflict settings for the
two primary workflows.
- `workflow: replacement` treats the current planned outputs as the authoritative
managed output set for the destination scope and removes previously managed
outputs in that scope when they are no longer planned.
- `workflow: additive` writes or overwrites the planned output paths and retains
unrelated managed outputs.
- If a planned path already exists as a managed output, the new publication may
overwrite it and becomes that path's current owner.
- If a planned path exists in storage but is not recorded in valid catalog state,
it remains unmanaged content and must not be adopted implicitly.
- If an output path changes owner, preserve the output record's existing
`created_at` and update only `updated_at`.
- Catalog state records current ownership only. It does not retain historical
owners, historical sources, or old versions of overwritten output records.
- `pipeline_id` and `destination_id` are stored separately on each output
record. They are not concatenated into one owner string.
- Catalog state does not include top-level `owners`; owners are derivable from
the output records.
- Catalog state does not include top-level `sources`; compact source identity is
stored directly on each output record.
- Catalog state does not record whether the last run used `replacement` or
`additive`. Workflow is execution policy, and persisting it would create
drift risk if config changes later.
- Legacy destination policy fields should be rejected outright in the new
workflow config model. Do not retain aliases for `state`, `reconciliation`,
`takeover`, or `transfer`.
## Destination Workflow Semantics
The user-facing destination config should express intent directly:
```yaml
destinations:
- id: weather-latest
backend: local
path: /srv/reports/weather/latest
workflow: additive
```
```yaml
destinations:
- id: weather-archive
backend: local
path: /srv/reports/weather/archive
workflow: replacement
```
`workflow` is orthogonal to backend config, path mapping, publish source/HTML
selection, transforms, links, and retention.
### Replacement Workflow
A replacement destination is for producers that maintain a curated source of
truth and expect `distributor` to make the destination's managed scope match the
current publication.
For a destination configured with `workflow: replacement`:
- planned outputs are written to their resolved destination paths;
- planned outputs may overwrite existing managed outputs at the same path;
- each written output record is replaced in-place with the current
publication's owner, source identity, hash, size, and timestamps;
- managed outputs in the destination scope that are not present in the current
plan are deleted and removed from catalog state;
- unmanaged destination content remains unmanaged and blocks planned path
collisions unless an explicit force workflow later chooses otherwise;
- the catalog state shape remains the same as additive workflow state.
### Additive Workflow
An additive destination is for producers that routinely contribute outputs to a
shared destination root.
For a destination configured with `workflow: additive`:
- planned outputs are written to their resolved destination paths;
- planned outputs may overwrite existing managed outputs at the same path;
- each overwritten output record is replaced in-place with the current
publication's owner, source identity, hash, size, and timestamps;
- managed outputs not present in the current plan are retained;
- unrelated managed outputs from other pipelines or destinations are retained;
- unmanaged destination content remains unmanaged and blocks planned path
collisions unless an explicit force workflow later chooses otherwise;
- pruning can select retained managed outputs by `updated_at` and, when useful,
by `pipeline_id` and/or `destination_id`.
Replacement workflow treats the current publication as the desired managed
output set for a destination scope. Additive workflow treats the current
publication as a patch to the catalog of currently managed outputs.
## Destination State Schema Version 4
Catalog state should use this top-level shape:
```json
{
"schema_version": 4,
"distributor_version": "dev",
"created_at": "2026-06-19T12:00:00Z",
"updated_at": "2026-06-19T12:05:00Z",
"state": {
"mode": "catalog"
},
"outputs": []
}
```
Top-level fields:
- `schema_version`: required. Value `4` for catalog state.
- `distributor_version`: optional diagnostic version string.
- `created_at`: required RFC3339 timestamp for when the catalog state file was
first created.
- `updated_at`: required RFC3339 timestamp for the latest catalog state update.
- `state.mode`: required. Value `catalog`.
- `outputs`: required array of currently managed output records.
Catalog state should not include top-level `pipeline_id`, `destination_id`,
`published_at`, `workflow`, `owners`, `sources`, or a full source manifest.
Those concepts belong on output records or in configuration.
## Output Record Schema
Each output record should be self-contained enough to support current
ownership, pruning, repair, bitrot checks, and basic provenance without a
separate owner or source catalog.
```json
{
"path": "tomorrow/index.html",
"pipeline_id": "weatherreporter.daily",
"destination_id": "latest-html",
"source": {
"id": "weatherreporter.tomorrow",
"digest": "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
"created": "2026-06-19T12:00:00Z"
},
"kind": "generated",
"source_path": "report.md",
"transform": "markdown_to_html",
"sha256": "sha256:abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789",
"size": 12345,
"created_at": "2026-06-19T12:00:00Z",
"updated_at": "2026-06-19T12:05:00Z",
"url": "https://reports.example.com/weather/tomorrow/"
}
```
Required output fields:
- `path`: destination-relative managed output path.
- `pipeline_id`: pipeline that most recently wrote this output path.
- `destination_id`: destination that most recently wrote this output path.
- `source`: compact identity of the source bundle that produced this output.
- `source.id`: source manifest id.
- `source.digest`: source manifest digest.
- `source.created`: source manifest creation timestamp, RFC3339.
- `kind`: `source` or `generated`.
- `sha256`: digest of the output bytes.
- `size`: output byte size.
- `created_at`: RFC3339 timestamp for when this output path first became
managed in catalog state.
- `updated_at`: RFC3339 timestamp for when this output path was most recently
written or updated.
Optional output fields:
- `source_path`: present only for generated outputs; source manifest path used
to produce the generated output.
- `transform`: present only for generated outputs; transform name used to
produce the generated output.
- `url`: present only when destination link configuration produces a public URL
for this output.
For copied source outputs, `source_path` and `transform` should be omitted. The
output `path` is already the copied source artifact path.
## Useful Properties
The catalog shape supports both primary workflows without unnecessary
normalization:
- current owner of each path is explicit;
- current source identity for each path is explicit;
- bitrot checks can compare storage bytes to `sha256`;
- pruning can use `updated_at`, optionally scoped by `pipeline_id` and
`destination_id`;
- repair can remove missing managed output records without consulting an owner
or source table;
- overwriting an output path updates one output record in place;
- no orphaned top-level owner/source records need to be maintained.
The schema intentionally avoids storing a full source manifest for every output.
The source manifest remains the producer-to-distributor validation contract, but
catalog state only needs compact source identity for currently managed outputs.
## Relationship To Existing State And Config Modes
Existing state modes remain current behavior until catalog mode is implemented:
- `single_owner` schema version `2` supports one owner for a destination bundle
path.
- `shared_root` schema version `3` supports multiple owners in one destination
root but still keeps owner records with latest source manifests.
- `catalog` schema version `4` should support replacement and additive
current-state ownership without top-level owner or source catalogs.
The intended user-facing config should move toward `workflow: replacement` and
`workflow: additive` instead of requiring ordinary users to combine
`state.mode`, `reconciliation.mode`, `takeover.mode`, and transfer conflict
settings.
Because the project is still alpha pre-release, catalog implementation should be
a clean break:
- remove legacy write paths for current `single_owner` and `shared_root` state;
- do not implement migration from schema versions `1`, `2`, or `3`;
- do not preserve backwards compatibility for legacy destination state;
- when a configured destination writes successfully, write schema version `4`
catalog state;
- if an existing `.distributor.json` has schema version lower than `4`, treat it
as superseded legacy state for planning purposes and overwrite it according to
the configured workflow, without attempting conversion.
For the first catalog run against superseded legacy state:
- `workflow: replacement` may clear the bounded destination root before writing
the planned outputs and schema version `4` catalog state.
- `workflow: additive` may overwrite only the planned output paths, then write
schema version `4` catalog state containing those planned outputs.
- unplanned files left behind by an additive run against superseded legacy state
are not recorded in catalog state and are treated as unmanaged content by
later catalog runs.
The target direction is that both primary workflows use catalog state.
## Prune And Reconcile-State Scope
Catalog maintenance commands should initially keep the existing ownership
selector model:
- `prune --pipeline <id> --destination <id>` operates only on outputs currently
owned by that pipeline/destination.
- `reconcile-state --pipeline <id> --destination <id>` repairs only outputs
currently owned by that pipeline/destination.
- `reconcile-state --all-owners` repairs all output records in the catalog.
- `prune` remains scoped to the selected pipeline/destination owner only in the
initial catalog implementation.
Do not add catalog-specific selectors in the initial implementation, such as
`--source-id`, `--path-prefix`, or `--kind`. Those may be useful later, but they
are not required to make additive workflow first-class.

View File

@@ -0,0 +1,345 @@
# Catalog State And Workflow Implementation Roadmap
This is the active staged implementation plan for
`docs/roadmap/catalog.md`. The feature roadmap defines the target state model
and policy decisions; this document defines the implementation sequence for an
LLM coding agent to follow stage by stage.
Future behavior must remain under `docs/roadmap/` until implemented. Update
current-behavior docs only in the stage that implements the corresponding
behavior.
## Current Baseline
`distributor` currently writes destination `.distributor.json` using
single-owner schema version `2` or shared-root schema version `3`. Destination
behavior is selected through several low-level knobs: `state.mode`,
`reconciliation.mode`, `takeover.mode`, and `transfer`.
The target behavior is a clean alpha break:
- all newly written destination state uses schema version `4`;
- all destinations use `state.mode: catalog` internally;
- user-facing destination behavior is selected by `workflow: additive` or
`workflow: replacement`;
- `workflow` defaults to `additive`;
- legacy destination policy fields are rejected, not aliased;
- legacy state schema versions `1`, `2`, and `3` are not migrated.
## Implementation Principles
- Keep the source manifest contract unchanged.
- Keep backend adapters unaware of catalog and workflow policy.
- Treat `workflow` as runtime config, not persisted state.
- Keep unmanaged content protected after catalog state exists.
- Preserve output `created_at` when a path changes owner; update only
`updated_at`.
- Prefer removing legacy state/config paths over compatibility shims.
- Preserve current public APIs outside destination state/config unless the
catalog roadmap explicitly changes them.
## Active Implementation Stages
## Stage 1: Destination Workflow Config Clean Break
Goal: replace low-level destination policy config with the user-facing workflow
switch.
Implementation scope:
- Add destination `workflow` config with accepted values `additive` and
`replacement`.
- Default omitted `workflow` to `additive`.
- Remove or make unsupported the destination-level config fields `state`,
`reconciliation`, `takeover`, and `transfer`.
- Ensure configs containing those legacy fields fail clearly. Prefer strict YAML
unknown-field failure by removing struct fields; add explicit validation only
if clearer errors are needed without weakening strict decoding.
- Preserve backend, publish, transform, path mapping, links, retention, and
other non-policy destination fields.
- Update example configs only when the implementation stage also updates
current docs; otherwise keep this stage focused on config code and tests.
Tests:
- `go test ./internal/config`
- Omitted workflow defaults to `additive`.
- `workflow: additive` and `workflow: replacement` validate.
- Unknown workflow values fail.
- Legacy `state`, `reconciliation`, `takeover`, and `transfer` fields fail.
- Existing valid examples are updated or tests are adjusted in the same change if
examples currently use legacy fields.
Completion criteria:
- New configs express destination replacement/additive intent with one field.
- No normal config path accepts legacy destination policy knobs.
## Stage 2: Catalog State Schema Version 4
Goal: implement the schema version `4` catalog state model in `internal/state`.
Implementation scope:
- Add catalog state types for top-level schema version `4`, `state.mode:
catalog`, and `outputs`.
- Add compact per-output source identity with `id`, `digest`, and `created`.
- Add catalog output records with required `path`, `pipeline_id`,
`destination_id`, `source`, `kind`, `sha256`, `size`, `created_at`, and
`updated_at`.
- Add optional `source_path`, `transform`, and `url`, present only where allowed
by the catalog roadmap.
- Validate duplicate paths, invalid owner ids, invalid source identities,
invalid output paths, invalid digests, negative sizes, invalid timestamps,
invalid kind/transform combinations, and invalid URLs.
- Marshal catalog state deterministically with the existing JSON formatting
conventions.
- Update `ParseDocument` so schema version `4` returns catalog state.
- Treat schema versions lower than `4` as superseded legacy state for publish
planning, not as readable/migrated active state. Keep enough detection to
identify legacy state and avoid treating it as arbitrary invalid JSON.
- Reject unsupported future schema versions.
Tests:
- `go test ./internal/state`
- Parse/validate/marshal valid catalog state.
- Reject malformed catalog state and invalid output records.
- Detect schema versions `1`, `2`, and `3` as superseded legacy state.
- Reject future schema versions.
- Prove no top-level `owners`, `sources`, workflow, source manifest, pipeline id,
destination id, or published timestamp is accepted for catalog state.
Completion criteria:
- State package has one canonical schema version `4` catalog contract for new
writes.
- Legacy state is detected but not migrated.
## Stage 3: Catalog Publish Planning
Goal: plan publish actions against catalog state and destination workflow.
Implementation scope:
- Replace publish request inputs that consume state/reconciliation/takeover and
transfer policy with destination workflow.
- Map workflow to catalog actions:
- `workflow: additive`: upsert planned outputs and retain all other managed
catalog outputs.
- `workflow: replacement`: upsert planned outputs and delete catalog outputs
owned by the current pipeline/destination that are omitted from the plan.
- Planned paths that already exist as catalog-managed outputs may be overwritten
and become owned by the current pipeline/destination.
- Planned path collisions with storage content not recorded in catalog state
fail as unmanaged content.
- Matching planned outputs may skip writes when source identity and output digest
already match, if that optimization can be implemented without changing
externally visible results; otherwise writing idempotently is acceptable.
- Existing schema `< 4` state is superseded:
- replacement workflow may plan a bounded destination-root clear before
writing planned outputs;
- additive workflow may plan overwrites for planned paths only and leave
unplanned files unmanaged.
- Invalid JSON or future schema state remains a conflict, not a superseded
legacy state.
- Preserve path mapping, publish policy, transforms, links, fixed-path
selection, and output collision checks.
Tests:
- `go test ./internal/publish`
- Additive workflow publishes new catalog state.
- Additive workflow overwrites an existing managed output and retains unrelated
outputs.
- Replacement workflow removes omitted outputs owned by the current
pipeline/destination.
- Replacement workflow preserves unrelated catalog outputs owned by other
pipeline/destination pairs.
- Managed output ownership moves to the current pipeline/destination when a
planned path is overwritten.
- `created_at` is preserved when an existing path changes owner; `updated_at`
changes.
- Unmanaged path collisions fail.
- Legacy schema `< 4` state follows the superseded-state rules above.
- Invalid/future state fails.
Completion criteria:
- Publish planning no longer depends on single-owner/shared-root comparison
semantics.
- Workflow behavior is fully driven by `workflow`.
## Stage 4: Catalog Publish Execution
Goal: execute catalog publish plans and write schema version `4` state.
Implementation scope:
- Write only schema version `4` catalog `.distributor.json`.
- Implement additive execution as managed upsert of planned outputs plus catalog
state update.
- Implement replacement execution as managed upsert plus deletion of omitted
current-owner catalog outputs.
- For replacement over superseded legacy state, clear the bounded destination
root before writing planned outputs and catalog state.
- For additive over superseded legacy state, overwrite planned paths and write a
catalog containing only planned outputs; leave unplanned files unmanaged.
- Preserve cleanup behavior on failed writes:
- additive cleanup removes outputs newly created by the failed attempt where
practical;
- replacement cleanup follows existing managed-replacement safety where
practical;
- state is written only after selected outputs are written.
- Preserve link metadata, generated output digests, source output digests,
content type behavior, and backend-safe writes.
Tests:
- `go test ./internal/publish ./internal/app`
- Additive execution writes planned outputs, overwrites managed planned paths,
retains unrelated managed outputs, and writes catalog state.
- Replacement execution deletes omitted current-owner outputs and preserves
unrelated owner outputs.
- Superseded legacy replacement clears bounded destination root only.
- Superseded legacy additive leaves unplanned files on disk but out of catalog
state.
- Failed writes do not leave misleading catalog state.
- Local, fake-backed SSH, and fake-backed S3 app paths exercise the same publish
behavior.
Completion criteria:
- Successful `run` writes only v4 catalog state.
- Destination outputs match additive/replacement workflow semantics.
## Stage 5: Run Reporting, Notifications, And CLI Surface
Goal: update user-visible run behavior to describe workflow/catalog actions
instead of legacy replacement/takeover actions.
Implementation scope:
- Replace legacy action labels tied to state/reconciliation/takeover/transfer
with these stable workflow-oriented labels:
- `publish_new`
- `upsert_additive`
- `replace_catalog`
- `skip_same`
- `force_replace`
- `fail_unmanaged`
- `fail_conflict`
- Ensure text and JSON run summaries include workflow-relevant counters.
- Include `workflow` in run action records where useful.
- Update fixed-path dry-run warnings to describe additive upsert or replacement
clearly.
- Ensure notifications use the new action labels.
- Remove reporting assumptions that depend on `replace_older`,
`replace_newer`, `replace_conflict`, or `replace_takeover`.
Tests:
- `go test ./internal/app ./internal/cli`
- Text dry-run output distinguishes additive from replacement workflow.
- JSON output includes workflow and stable action labels.
- Summary counters are deterministic.
- Notifications fire for additive and replacement writes.
- Existing CLI commands still parse and execute with the new config shape.
Completion criteria:
- Operators can understand from dry-run output whether a destination will upsert
or replace managed catalog outputs.
## Stage 6: Catalog Prune And Reconcile-State
Goal: update maintenance commands to operate on catalog state with the agreed
selector model.
Implementation scope:
- Prune:
- selected `--pipeline` and `--destination` prune only outputs currently owned
by that pipeline/destination;
- no `--all-owners` prune mode in the initial catalog implementation;
- do not add `--source-id`, `--path-prefix`, or `--kind` selectors.
- Reconcile-state:
- selected `--pipeline` and `--destination` repair only outputs currently
owned by that pipeline/destination;
- `--all-owners` repairs all catalog outputs;
- unmanaged reporting compares storage entries to all catalog output paths,
not just selected owner paths.
- Rewrite repaired/pruned state as schema version `4`.
- Remove legacy single-owner/shared-root maintenance branches.
Tests:
- `go test ./internal/state ./internal/app ./internal/cli`
- Prune selects only current-owner catalog outputs.
- Prune deletes selected outputs and removes their catalog records.
- Reconcile-state selected owner removes only missing outputs for that owner.
- `reconcile-state --all-owners` removes missing outputs for all owners.
- Unmanaged reporting excludes all catalog-managed paths and reports unrecorded
storage entries.
- JSON/text output remains stable and clear.
Completion criteria:
- Maintenance commands operate only on catalog state and respect the locked
selector rules.
## Stage 7: Clean Break Removal And Documentation
Goal: remove legacy state/config behavior and document the implemented catalog
workflow model.
Implementation scope:
- Remove dead code for writing schema version `2` single-owner and schema
version `3` shared-root state.
- Remove legacy config structs/constants/defaults/validation for destination
`state`, `reconciliation`, `takeover`, and `transfer` where no longer used.
- Remove or rewrite tests that only assert legacy state/config behavior.
- Update current-behavior docs:
- `docs/config.md`
- `docs/cli.md`
- `docs/operations.md`
- `docs/troubleshooting.md`
- `docs/integrations/destination-state.md`
- relevant `docs/internal/` docs
- `docs/policy/architecture.md`
- `docs/policy/development.md`
- Update examples to use `workflow` and remove legacy fields.
- Keep roadmap-only material out of current docs.
- Once implemented and documented, remove or rewrite
`docs/roadmap/catalog.md` so completed behavior is not described only as
future work.
Tests and checks:
- `go test ./...`
- `rg -n "state:|reconciliation:|takeover:|transfer:" examples docs --glob '!docs/roadmap/**'`
- `rg -n 'single_owner|shared_root|schema version `2`|schema version `3`' docs internal`
- `rg -n "workflow: additive|workflow: replacement|schema_version.*4" docs examples`
Completion criteria:
- Current docs and examples describe the catalog workflow model.
- Legacy destination policy fields and legacy write paths are gone.
- Full test suite passes.
## Refactors To Avoid
- Do not add top-level `owners` or `sources` catalogs.
- Do not persist workflow in `.distributor.json`.
- Do not keep deprecated config aliases for legacy destination policy fields.
- Do not implement state migration from schema versions `1`, `2`, or `3`.
- Do not add catalog-specific prune/reconcile selectors beyond the agreed
initial ownership scope.
- Do not move catalog policy into storage adapters.
## Open Questions
No open questions are known. The catalog roadmap locks the state shape, workflow
values, default workflow, clean-break policy, legacy-state behavior, output
field selection, `created_at` preservation, and maintenance command scope.

View File

@@ -205,7 +205,7 @@ Reference: [Operations](operations.md#forced-replacement-workflow).
Symptom: `fail_conflict`, `destination source id differs`, `same id and created time but different digest`, `pipeline id ... does not match`, or `destination id ... does not match`. Symptom: `fail_conflict`, `destination source id differs`, `same id and created time but different digest`, `pipeline id ... does not match`, or `destination id ... does not match`.
Likely cause: `.distributor.json` belongs to a different pipeline, destination, source id, or same-created source with different content. Likely cause: `.distributor.json` belongs to a different pipeline, destination, source id, shared-root output owner, or same-created source with different content. Valid managed identity, source, and shared-root output-owner mismatches can publish as `replace_takeover` when destination `takeover.mode` allows them, or as `replace_conflict` when `transfer.on_conflict: replace` allows managed conflict replacement.
Diagnostic: Diagnostic:
@@ -214,7 +214,7 @@ cat <destination-path>/.distributor.json
go run ./cmd/distributor inspect <source-root> go run ./cmd/distributor inspect <source-root>
``` ```
Safe fix: verify the source and destination are intended to match. Use a separate destination path for unrelated content. To replace the existing state, configure `transfer.on_conflict: replace`, preview with `--dry-run --force`, then publish with `--force`. Safe fix: verify the source and destination are intended to match. Use a separate destination path for unrelated content. For normal managed replacement, configure destination `takeover.mode` to match the intended ownership boundary or configure `transfer.on_conflict: replace`, then preview with `--dry-run`. Use `--force` only for exceptional replacement of unmanaged content or other force-only cases reported as `force_replace`.
Reference: [Operations](operations.md#destination-state-and-retry-behavior). Reference: [Operations](operations.md#destination-state-and-retry-behavior).
@@ -262,7 +262,7 @@ Reference: [Operations](operations.md#managed-output-pruning).
## Destination Is Newer Than Source ## Destination Is Newer Than Source
Symptom: `skip_destination_newer` or `destination is newer and replacement requires --force`. Symptom: `skip_destination_newer`.
Likely cause: the destination state records a source manifest with a later `created` timestamp than the current source. Likely cause: the destination state records a source manifest with a later `created` timestamp than the current source.
@@ -272,7 +272,7 @@ Diagnostic:
go run ./cmd/distributor run --config <config-path> --dry-run --format json go run ./cmd/distributor run --config <config-path> --dry-run --format json
``` ```
Safe fix: keep the default skip behavior unless replacement is intentional. To replace newer state, configure `transfer.on_destination_newer: replace`, preview with `--dry-run --force`, then publish with `--force`. Safe fix: keep the default skip behavior unless replacement is intentional. To replace newer valid managed state, configure `transfer.on_destination_newer: replace`, preview with `--dry-run`, then publish without `--force`.
Reference: [Operations](operations.md#forced-replacement-workflow). Reference: [Operations](operations.md#forced-replacement-workflow).
@@ -312,7 +312,7 @@ Reference: [Configuration](config.md#publish-and-transform-policy).
Symptom: `fail_conflict` with a reason like `destination output path ... is owned by <pipeline>/<destination>`. Symptom: `fail_conflict` with a reason like `destination output path ... is owned by <pipeline>/<destination>`.
Likely cause: a `state.mode: shared_root` destination planned an output path already recorded in `.distributor.json` for another pipeline/destination owner. Likely cause: a `state.mode: shared_root` destination planned an output path already recorded in `.distributor.json` for another pipeline/destination owner, and `takeover.mode` does not allow that managed path to move to the current owner.
Diagnostic: Diagnostic:
@@ -354,7 +354,7 @@ Diagnostic:
find <destination-path> -maxdepth 2 -print find <destination-path> -maxdepth 2 -print
``` ```
Safe fix: inspect the destination bundle path printed in the error. `distributor` attempts to remove outputs from the failed attempt, but operators should verify the destination before retrying. In merge mode, previously managed retained or overwritten outputs may remain intentionally. Rerun `--dry-run` before publishing again. Safe fix: inspect the destination bundle path printed in the error. `distributor` attempts to remove outputs from the failed attempt, but operators should verify the destination before retrying. In same-source merge mode, previously managed retained or overwritten outputs may remain intentionally. Rerun `--dry-run` before publishing again.
Reference: [Operations](operations.md#destination-state-and-retry-behavior). Reference: [Operations](operations.md#destination-state-and-retry-behavior).

View File

@@ -170,7 +170,7 @@ func (b *Backend) WriteFrom(ctx context.Context, logicalPath string, r io.Reader
return storage.Entry{}, storage.NewError(storage.OpWriteFrom, BackendName, logicalPath, storage.ErrConflict, fmt.Errorf("stream size %d does not match expected size %d", written, opts.Size)) return storage.Entry{}, storage.NewError(storage.OpWriteFrom, BackendName, logicalPath, storage.ErrConflict, fmt.Errorf("stream size %d does not match expected size %d", written, opts.Size))
} }
if opts.PreferAtomic { if opts.PreferAtomic {
if err := b.client.Rename(writePath, nativePath); err != nil { if err := renamePromotedFile(b.client, writePath, nativePath, opts.Overwrite); err != nil {
return storage.Entry{}, b.translateError(storage.OpWriteFrom, logicalPath, err) return storage.Entry{}, b.translateError(storage.OpWriteFrom, logicalPath, err)
} }
cleanup = false cleanup = false
@@ -178,6 +178,27 @@ func (b *Backend) WriteFrom(ctx context.Context, logicalPath string, r io.Reader
return b.Stat(ctx, logicalPath) return b.Stat(ctx, logicalPath)
} }
type sftpRenamer interface {
PosixRename(oldname, newname string) error
Rename(oldname, newname string) error
Remove(path string) error
}
func renamePromotedFile(client sftpRenamer, oldname, newname string, overwrite bool) error {
if !overwrite {
return client.Rename(oldname, newname)
}
if err := client.PosixRename(oldname, newname); err == nil {
return nil
} else if !isReplaceRenameFallbackError(err) {
return err
}
if err := client.Remove(newname); err != nil && !isNotExist(err) {
return err
}
return client.Rename(oldname, newname)
}
func (b *Backend) Stat(ctx context.Context, logicalPath string) (storage.Entry, error) { func (b *Backend) Stat(ctx context.Context, logicalPath string) (storage.Entry, error) {
if err := ctx.Err(); err != nil { if err := ctx.Err(); err != nil {
return storage.Entry{}, err return storage.Entry{}, err
@@ -464,6 +485,14 @@ func isNotExist(err error) bool {
return errors.Is(err, fs.ErrNotExist) || errors.Is(err, os.ErrNotExist) || errors.Is(err, sftp.ErrSSHFxNoSuchFile) return errors.Is(err, fs.ErrNotExist) || errors.Is(err, os.ErrNotExist) || errors.Is(err, sftp.ErrSSHFxNoSuchFile)
} }
func isReplaceRenameFallbackError(err error) bool {
if errors.Is(err, sftp.ErrSSHFxFailure) || errors.Is(err, sftp.ErrSSHFxOpUnsupported) {
return true
}
var statusErr *sftp.StatusError
return errors.As(err, &statusErr) && (statusErr.FxCode() == sftp.ErrSSHFxFailure || statusErr.FxCode() == sftp.ErrSSHFxOpUnsupported)
}
func (b *Backend) translateError(op, logicalPath string, err error) error { func (b *Backend) translateError(op, logicalPath string, err error) error {
kind := storage.ErrUnknown kind := storage.ErrUnknown
switch { switch {

View File

@@ -0,0 +1,125 @@
package ssh
import (
"errors"
"os"
"testing"
"github.com/pkg/sftp"
)
func TestRenamePromotedFileUsesPlainRenameWithoutOverwrite(t *testing.T) {
client := &recordingRenamer{}
if err := renamePromotedFile(client, "temp", "index.html", false); err != nil {
t.Fatalf("renamePromotedFile() error = %v", err)
}
if got, want := client.calls, []string{"rename temp index.html"}; !equalStrings(got, want) {
t.Fatalf("calls = %q, want %q", got, want)
}
}
func TestRenamePromotedFileUsesPosixRenameForOverwrite(t *testing.T) {
client := &recordingRenamer{}
if err := renamePromotedFile(client, "temp", "index.html", true); err != nil {
t.Fatalf("renamePromotedFile() error = %v", err)
}
if got, want := client.calls, []string{"posix temp index.html"}; !equalStrings(got, want) {
t.Fatalf("calls = %q, want %q", got, want)
}
}
func TestRenamePromotedFileFallsBackWhenReplaceRenameUnsupported(t *testing.T) {
for _, err := range []error{
sftp.ErrSSHFxOpUnsupported,
sftp.ErrSSHFxFailure,
&sftp.StatusError{Code: uint32(sftp.ErrSSHFxOpUnsupported)},
&sftp.StatusError{Code: uint32(sftp.ErrSSHFxFailure)},
} {
t.Run(err.Error(), func(t *testing.T) {
client := &recordingRenamer{posixErr: err}
if err := renamePromotedFile(client, "temp", "index.html", true); err != nil {
t.Fatalf("renamePromotedFile() error = %v", err)
}
want := []string{"posix temp index.html", "remove index.html", "rename temp index.html"}
if got := client.calls; !equalStrings(got, want) {
t.Fatalf("calls = %q, want %q", got, want)
}
})
}
}
func TestRenamePromotedFileIgnoresMissingTargetDuringFallback(t *testing.T) {
client := &recordingRenamer{
posixErr: sftp.ErrSSHFxOpUnsupported,
removeErr: &os.PathError{
Op: "remove",
Path: "index.html",
Err: os.ErrNotExist,
},
}
if err := renamePromotedFile(client, "temp", "index.html", true); err != nil {
t.Fatalf("renamePromotedFile() error = %v", err)
}
want := []string{"posix temp index.html", "remove index.html", "rename temp index.html"}
if got := client.calls; !equalStrings(got, want) {
t.Fatalf("calls = %q, want %q", got, want)
}
}
func TestRenamePromotedFileDoesNotFallbackForPermissionError(t *testing.T) {
client := &recordingRenamer{posixErr: sftp.ErrSSHFxPermissionDenied}
if err := renamePromotedFile(client, "temp", "index.html", true); !errors.Is(err, sftp.ErrSSHFxPermissionDenied) {
t.Fatalf("renamePromotedFile() error = %v, want permission denied", err)
}
if got, want := client.calls, []string{"posix temp index.html"}; !equalStrings(got, want) {
t.Fatalf("calls = %q, want %q", got, want)
}
}
func TestRenamePromotedFileReturnsRemoveFallbackError(t *testing.T) {
client := &recordingRenamer{
posixErr: sftp.ErrSSHFxOpUnsupported,
removeErr: sftp.ErrSSHFxPermissionDenied,
}
if err := renamePromotedFile(client, "temp", "index.html", true); !errors.Is(err, sftp.ErrSSHFxPermissionDenied) {
t.Fatalf("renamePromotedFile() error = %v, want permission denied", err)
}
want := []string{"posix temp index.html", "remove index.html"}
if got := client.calls; !equalStrings(got, want) {
t.Fatalf("calls = %q, want %q", got, want)
}
}
type recordingRenamer struct {
calls []string
posixErr error
renameErr error
removeErr error
}
func (r *recordingRenamer) PosixRename(oldname, newname string) error {
r.calls = append(r.calls, "posix "+oldname+" "+newname)
return r.posixErr
}
func (r *recordingRenamer) Rename(oldname, newname string) error {
r.calls = append(r.calls, "rename "+oldname+" "+newname)
return r.renameErr
}
func (r *recordingRenamer) Remove(path string) error {
r.calls = append(r.calls, "remove "+path)
return r.removeErr
}
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
}

View File

@@ -71,6 +71,7 @@ func processDestinationSelection(ctx context.Context, request runDestinationRequ
Links: request.destination.Links, Links: request.destination.Links,
State: request.destination.State, State: request.destination.State,
Reconciliation: request.destination.Reconciliation, Reconciliation: request.destination.Reconciliation,
Takeover: request.destination.Takeover,
Transformers: request.transforms, Transformers: request.transforms,
Transfer: request.destination.Transfer, Transfer: request.destination.Transfer,
DistributorVersion: Version, DistributorVersion: Version,

View File

@@ -6,7 +6,7 @@ import (
) )
func shouldNotify(action publish.Action) bool { func shouldNotify(action publish.Action) bool {
return action == publish.ActionPublishNew || action == publish.ActionReplaceOlder || action == publish.ActionForceReplace return action == publish.ActionPublishNew || action == publish.ActionReplaceOlder || action == publish.ActionReplaceConflict || action == publish.ActionReplaceNewer || action == publish.ActionReplaceTakeover || action == publish.ActionForceReplace
} }
func notifyEvent(plan publish.Plan) notify.Event { func notifyEvent(plan publish.Plan) notify.Event {

View File

@@ -60,7 +60,7 @@ func writeRunActionLine(w io.Writer, action RunActionRecord) {
fmt.Fprintf(w, " - bundle=%s destination=%s backend=%s%s action=error reason=%q\n", action.BundlePath, destinationID, action.Backend, pathMappingRecordSummary(action), action.Reason) 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 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) fmt.Fprintf(w, " - bundle=%s destination=%s backend=%s%s action=%s%s outputs=%s reason=%q\n", action.BundlePath, action.DestinationID, action.Backend, pathMappingRecordSummary(action), action.Action, takeoverModeRecordSummary(action), outputRecordSummary(action.Outputs), action.Reason)
} }
func pathMappingRecordSummary(action RunActionRecord) string { func pathMappingRecordSummary(action RunActionRecord) string {
@@ -70,6 +70,13 @@ func pathMappingRecordSummary(action RunActionRecord) string {
return fmt.Sprintf(" path_mapping=fixed target=%s", action.DestinationPath) return fmt.Sprintf(" path_mapping=fixed target=%s", action.DestinationPath)
} }
func takeoverModeRecordSummary(action RunActionRecord) string {
if action.TakeoverMode == "" {
return ""
}
return fmt.Sprintf(" takeover_mode=%s", action.TakeoverMode)
}
func outputRecordSummary(outputs []RunOutputRecord) string { func outputRecordSummary(outputs []RunOutputRecord) string {
if len(outputs) == 0 { if len(outputs) == 0 {
return "none" return "none"
@@ -137,6 +144,7 @@ type RunActionRecord struct {
DestinationPath string `json:"destination_path"` DestinationPath string `json:"destination_path"`
PathMapping string `json:"path_mapping,omitempty"` PathMapping string `json:"path_mapping,omitempty"`
Action string `json:"action"` Action string `json:"action"`
TakeoverMode string `json:"takeover_mode,omitempty"`
PrimaryURL string `json:"primary_url,omitempty"` PrimaryURL string `json:"primary_url,omitempty"`
Reason string `json:"reason,omitempty"` Reason string `json:"reason,omitempty"`
Outputs []RunOutputRecord `json:"outputs"` Outputs []RunOutputRecord `json:"outputs"`
@@ -181,12 +189,20 @@ func runActionFromPlan(backend string, plan publish.Plan, planErr error) RunActi
DestinationPath: storage.DisplayPath(plan.DestinationBundlePath), DestinationPath: storage.DisplayPath(plan.DestinationBundlePath),
PathMapping: plan.PathMapping, PathMapping: plan.PathMapping,
Action: string(plan.Action), Action: string(plan.Action),
TakeoverMode: takeoverModeForAction(plan),
PrimaryURL: plan.PrimaryURL, PrimaryURL: plan.PrimaryURL,
Reason: plan.Reason, Reason: plan.Reason,
Outputs: runOutputsFromPlan(plan.Outputs), Outputs: runOutputsFromPlan(plan.Outputs),
} }
} }
func takeoverModeForAction(plan publish.Plan) string {
if plan.Action != publish.ActionReplaceTakeover {
return ""
}
return plan.TakeoverMode
}
func errorAction(pipelineID, destinationID, backend, bundlePath string, err error) RunActionRecord { func errorAction(pipelineID, destinationID, backend, bundlePath string, err error) RunActionRecord {
return RunActionRecord{ return RunActionRecord{
PipelineID: pipelineID, PipelineID: pipelineID,

View File

@@ -63,10 +63,13 @@ func fixedPathSelectionWarning(pipelineID, destinationID string, selections []de
} }
func isDestructiveFixedPathAction(action publish.Action) bool { func isDestructiveFixedPathAction(action publish.Action) bool {
return action == publish.ActionReplaceOlder || action == publish.ActionForceReplace return action == publish.ActionReplaceOlder || action == publish.ActionReplaceConflict || action == publish.ActionReplaceNewer || action == publish.ActionReplaceTakeover || action == publish.ActionForceReplace
} }
func fixedPathReplacementWarning(plan publish.Plan) OutputWarning { func fixedPathReplacementWarning(plan publish.Plan) OutputWarning {
if plan.Action == publish.ActionReplaceTakeover {
return OutputWarning{Message: fmt.Sprintf("pipeline=%s destination=%s path_mapping=fixed action=%s takeover_mode=%s replaces destination root for selected_bundle=%s reason=%q", plan.PipelineID, plan.DestinationID, plan.Action, plan.TakeoverMode, storage.DisplayPath(plan.BundlePath), plan.Reason)}
}
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))} 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))}
} }

View File

@@ -11,6 +11,9 @@ type runSummary struct {
planned int planned int
publishNew int publishNew int
replaceOlder int replaceOlder int
replaceConflict int
replaceNewer int
replaceTakeover int
forceReplace int forceReplace int
skipped int skipped int
failures int failures int
@@ -24,6 +27,12 @@ func (s *runSummary) recordPlan(action publish.Action) {
s.publishNew++ s.publishNew++
case publish.ActionReplaceOlder: case publish.ActionReplaceOlder:
s.replaceOlder++ s.replaceOlder++
case publish.ActionReplaceConflict:
s.replaceConflict++
case publish.ActionReplaceNewer:
s.replaceNewer++
case publish.ActionReplaceTakeover:
s.replaceTakeover++
case publish.ActionForceReplace: case publish.ActionForceReplace:
s.forceReplace++ s.forceReplace++
case publish.ActionSkipSame, publish.ActionSkipDestinationNewer: case publish.ActionSkipSame, publish.ActionSkipDestinationNewer:
@@ -44,6 +53,9 @@ type RunSummaryCounters struct {
Planned int `json:"planned"` Planned int `json:"planned"`
PublishNew int `json:"publish_new"` PublishNew int `json:"publish_new"`
ReplaceOlder int `json:"replace_older"` ReplaceOlder int `json:"replace_older"`
ReplaceConflict int `json:"replace_conflict"`
ReplaceNewer int `json:"replace_newer"`
ReplaceTakeover int `json:"replace_takeover"`
ForceReplace int `json:"force_replace"` ForceReplace int `json:"force_replace"`
Skipped int `json:"skipped"` Skipped int `json:"skipped"`
Failed int `json:"failed"` Failed int `json:"failed"`
@@ -52,7 +64,7 @@ type RunSummaryCounters struct {
} }
func (s RunSummaryCounters) Line() string { 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) return fmt.Sprintf("Final status: %s planned=%d publish_new=%d replace_older=%d replace_conflict=%d replace_newer=%d replace_takeover=%d force_replace=%d skipped=%d failed=%d dry_run=%t fixed_path=%d", s.Status, s.Planned, s.PublishNew, s.ReplaceOlder, s.ReplaceConflict, s.ReplaceNewer, s.ReplaceTakeover, s.ForceReplace, s.Skipped, s.Failed, s.DryRun, s.FixedPath)
} }
func (s runSummary) Result() RunSummaryCounters { func (s runSummary) Result() RunSummaryCounters {
@@ -65,6 +77,9 @@ func (s runSummary) Result() RunSummaryCounters {
Planned: s.planned, Planned: s.planned,
PublishNew: s.publishNew, PublishNew: s.publishNew,
ReplaceOlder: s.replaceOlder, ReplaceOlder: s.replaceOlder,
ReplaceConflict: s.replaceConflict,
ReplaceNewer: s.replaceNewer,
ReplaceTakeover: s.replaceTakeover,
ForceReplace: s.forceReplace, ForceReplace: s.forceReplace,
Skipped: s.skipped, Skipped: s.skipped,
Failed: s.failures, Failed: s.failures,

View File

@@ -43,7 +43,7 @@ func TestRunDryRunPrintsConfigSummary(t *testing.T) {
"Configured pipelines: 1", "Configured pipelines: 1",
"- pipeline=reports source=local bundles=1 destinations=archive", "- pipeline=reports source=local bundles=1 destinations=archive",
"bundle=. destination=archive backend=local action=publish_new outputs=report.md,summary.txt", "bundle=. destination=archive backend=local action=publish_new outputs=report.md,summary.txt",
"Final status: ok planned=1 publish_new=1 replace_older=0 force_replace=0 skipped=0 failed=0 dry_run=true", "Final status: ok planned=1 publish_new=1 replace_older=0 replace_conflict=0 replace_newer=0 replace_takeover=0 force_replace=0 skipped=0 failed=0 dry_run=true",
} { } {
if !strings.Contains(output, want) { if !strings.Contains(output, want) {
t.Fatalf("Run() output = %q, want substring %q", output, want) t.Fatalf("Run() output = %q, want substring %q", output, want)
@@ -592,8 +592,9 @@ func TestRunFixedPathDryRunWarnsForReplacement(t *testing.T) {
} }
output := stdout.String() output := stdout.String()
for _, want := range []string{ for _, want := range []string{
"Warning: pipeline=reports destination=archive path_mapping=fixed action=replace_older replaces destination root for selected_bundle=new", "Warning: pipeline=reports destination=archive path_mapping=fixed action=replace_takeover takeover_mode=same_pipeline replaces destination root for selected_bundle=new reason=\"destination source id differs from source\"",
"bundle=new destination=archive backend=local path_mapping=fixed target=. action=replace_older", "bundle=new destination=archive backend=local path_mapping=fixed target=. action=replace_takeover takeover_mode=same_pipeline outputs=report.md,summary.txt reason=\"destination source id differs from source\"",
"replace_takeover=1",
} { } {
if !strings.Contains(output, want) { if !strings.Contains(output, want) {
t.Fatalf("stdout = %q, want substring %q", output, want) t.Fatalf("stdout = %q, want substring %q", output, want)
@@ -602,6 +603,61 @@ func TestRunFixedPathDryRunWarnsForReplacement(t *testing.T) {
testutil.AssertFile(t, filepath.Join(destinationRoot, "report.md"), "# Report\nOld.\n") testutil.AssertFile(t, filepath.Join(destinationRoot, "report.md"), "# Report\nOld.\n")
} }
func TestRunJSONIncludesTakeoverActionAndSummary(t *testing.T) {
sourceRoot := t.TempDir()
destinationRoot := t.TempDir()
writeSourceBundle(t, sourceRoot, "old", testBundleOptions{
ID: "reports.old",
Created: testutil.DefaultCreated,
Files: []testFile{
{Path: "report.md", Data: "# Report\nOld.\n"},
{Path: "summary.txt", Data: "Old summary\n"},
},
})
configPath := testutil.WriteLocalConfigWithPathMapping(t, sourceRoot, destinationRoot, config.PathMappingFixed)
if err := Run(context.Background(), RunOptions{ConfigPath: configPath}); err != nil {
t.Fatalf("first Run() error = %v", err)
}
writeSourceBundle(t, sourceRoot, "new", testBundleOptions{
ID: "reports.new",
Created: testutil.DefaultCreated.Add(time.Hour),
Files: []testFile{
{Path: "report.md", Data: "# Report\nNew.\n"},
{Path: "summary.txt", Data: "New summary\n"},
},
})
var stdout bytes.Buffer
err := Run(context.Background(), RunOptions{
ConfigPath: configPath,
DryRun: true,
Stdout: &stdout,
OutputFormat: OutputFormatJSON,
})
if err != nil {
t.Fatalf("Run() error = %v", err)
}
result := decodeAppResult(t, stdout.String())
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 {
t.Fatalf("action = %#v, want object", actions[0])
}
if action["action"] != "replace_takeover" || action["takeover_mode"] != "same_pipeline" || action["reason"] != "destination source id differs from source" {
t.Fatalf("action = %#v, want takeover action metadata", action)
}
summary, ok := result["summary"].(map[string]any)
if !ok {
t.Fatalf("summary = %#v, want object", result["summary"])
}
if summary["replace_takeover"] != float64(1) || summary["replace_older"] != float64(0) || summary["force_replace"] != float64(0) {
t.Fatalf("summary = %#v, want takeover counter only", summary)
}
}
func TestRunFixedPathReplacesOlderManagedState(t *testing.T) { func TestRunFixedPathReplacesOlderManagedState(t *testing.T) {
sourceRoot := t.TempDir() sourceRoot := t.TempDir()
destinationRoot := t.TempDir() destinationRoot := t.TempDir()
@@ -628,9 +684,13 @@ func TestRunFixedPathReplacesOlderManagedState(t *testing.T) {
}, },
}) })
if err := Run(context.Background(), RunOptions{ConfigPath: configPath}); err != nil { var stdout bytes.Buffer
if err := Run(context.Background(), RunOptions{ConfigPath: configPath, Stdout: &stdout}); err != nil {
t.Fatalf("second Run() error = %v", err) t.Fatalf("second Run() error = %v", err)
} }
if !strings.Contains(stdout.String(), "action=replace_takeover takeover_mode=same_pipeline") {
t.Fatalf("stdout = %q, want same-pipeline takeover", stdout.String())
}
testutil.AssertFile(t, filepath.Join(destinationRoot, "report.md"), "# Report\nNew.\n") testutil.AssertFile(t, filepath.Join(destinationRoot, "report.md"), "# Report\nNew.\n")
destinationState := readStateFile(t, filepath.Join(destinationRoot, storage.StateFileName)) destinationState := readStateFile(t, filepath.Join(destinationRoot, storage.StateFileName))
if destinationState.Source.Manifest.ID != "reports.new" { if destinationState.Source.Manifest.ID != "reports.new" {
@@ -638,11 +698,72 @@ func TestRunFixedPathReplacesOlderManagedState(t *testing.T) {
} }
} }
func TestRunPreserveRelativeSameSourceTakeoverAllowsOwnerMismatch(t *testing.T) {
sourceRoot := t.TempDir()
destinationRoot := t.TempDir()
sourceManifest := writeSourceBundle(t, sourceRoot, "daily/report", testBundleOptions{
ID: "reports.same",
Files: []testFile{{Path: "report.md", Data: "# Report\nNew.\n"}},
})
testutil.WriteDestinationState(t, destinationRoot, "daily/report", sourceManifest, testutil.DestinationStateOptions{
PipelineID: "other",
})
if err := os.WriteFile(filepath.Join(destinationRoot, "daily", "report", "report.md"), []byte("# Report\nOld.\n"), 0o600); err != nil {
t.Fatalf("write old report: %v", err)
}
var stdout bytes.Buffer
err := Run(context.Background(), RunOptions{
ConfigPath: writeSameSourcePreserveRelativeConfig(t, sourceRoot, destinationRoot),
Stdout: &stdout,
})
if err != nil {
t.Fatalf("Run() error = %v", err)
}
if !strings.Contains(stdout.String(), "action=replace_takeover takeover_mode=same_source") {
t.Fatalf("stdout = %q, want same-source takeover", stdout.String())
}
testutil.AssertFile(t, filepath.Join(destinationRoot, "daily", "report", "report.md"), "# Report\nNew.\n")
destinationState := readStateFile(t, filepath.Join(destinationRoot, "daily", "report", storage.StateFileName))
if destinationState.PipelineID != "reports" || destinationState.Source.Manifest.ID != "reports.same" {
t.Fatalf("state owner/source = %s/%s source=%s, want reports/archive reports.same", destinationState.PipelineID, destinationState.DestinationID, destinationState.Source.Manifest.ID)
}
}
func TestRunPreserveRelativeSameSourceRefusesDifferentSource(t *testing.T) {
sourceRoot := t.TempDir()
destinationRoot := t.TempDir()
sourceManifest := writeSourceBundle(t, sourceRoot, "daily/report", testBundleOptions{
ID: "reports.same",
Files: []testFile{{Path: "report.md", Data: "# Report\nNew.\n"}},
})
destinationManifest := sourceManifest
destinationManifest.ID = "reports.other"
testutil.WriteDestinationState(t, destinationRoot, "daily/report", destinationManifest, testutil.DestinationStateOptions{
PipelineID: "other",
})
if err := os.WriteFile(filepath.Join(destinationRoot, "daily", "report", "report.md"), []byte("# Report\nOld.\n"), 0o600); err != nil {
t.Fatalf("write old report: %v", err)
}
err := Run(context.Background(), RunOptions{
ConfigPath: writeSameSourcePreserveRelativeConfig(t, sourceRoot, destinationRoot),
})
if err == nil || !strings.Contains(err.Error(), "fail_conflict") {
t.Fatalf("Run() error = %v, want fail_conflict", err)
}
testutil.AssertFile(t, filepath.Join(destinationRoot, "daily", "report", "report.md"), "# Report\nOld.\n")
destinationState := readStateFile(t, filepath.Join(destinationRoot, "daily", "report", storage.StateFileName))
if destinationState.PipelineID != "other" || destinationState.Source.Manifest.ID != "reports.other" {
t.Fatalf("state owner/source = %s/%s source=%s, want unchanged other/archive reports.other", destinationState.PipelineID, destinationState.DestinationID, destinationState.Source.Manifest.ID)
}
}
func TestRunFixedPathSkipsWhenDestinationStateIsNewer(t *testing.T) { func TestRunFixedPathSkipsWhenDestinationStateIsNewer(t *testing.T) {
sourceRoot := t.TempDir() sourceRoot := t.TempDir()
destinationRoot := t.TempDir() destinationRoot := t.TempDir()
newer := testutil.ValidManifest(testutil.BundleOptions{ newer := testutil.ValidManifest(testutil.BundleOptions{
ID: "reports.newer", ID: "reports.same",
Created: testutil.DefaultCreated.Add(time.Hour), Created: testutil.DefaultCreated.Add(time.Hour),
}) })
writeDestinationState(t, destinationRoot, "", newer) writeDestinationState(t, destinationRoot, "", newer)
@@ -650,7 +771,7 @@ func TestRunFixedPathSkipsWhenDestinationStateIsNewer(t *testing.T) {
t.Fatalf("write existing report: %v", err) t.Fatalf("write existing report: %v", err)
} }
writeSourceBundle(t, sourceRoot, "older", testBundleOptions{ writeSourceBundle(t, sourceRoot, "older", testBundleOptions{
ID: "reports.older", ID: "reports.same",
Created: testutil.DefaultCreated, Created: testutil.DefaultCreated,
}) })
@@ -721,14 +842,6 @@ func TestRunFixedPathRemoteBackendsUseBackendRoots(t *testing.T) {
{Path: "summary.txt", Data: "Old summary\n"}, {Path: "summary.txt", Data: "Old summary\n"},
}, },
}) })
writeSourceBundle(t, localSourceRoot, "new", testBundleOptions{
ID: "reports.new",
Created: testutil.DefaultCreated.Add(time.Hour),
Files: []testFile{
{Path: "report.md", Data: "# Report\nNew.\n"},
{Path: "summary.txt", Data: "New summary\n"},
},
})
s3Destination := fake.New() s3Destination := fake.New()
sshDestination := fake.New() sshDestination := fake.New()
cfg := config.Config{Pipelines: []config.Pipeline{{ cfg := config.Config{Pipelines: []config.Pipeline{{
@@ -760,6 +873,30 @@ func TestRunFixedPathRemoteBackendsUseBackendRoots(t *testing.T) {
if err := runConfigWithBackendFactory(context.Background(), cfg, RunOptions{}, provider); err != nil { if err := runConfigWithBackendFactory(context.Background(), cfg, RunOptions{}, provider); err != nil {
t.Fatalf("Run() error = %v", err) t.Fatalf("Run() error = %v", err)
} }
testutil.AssertFakeFile(t, s3Destination, "report.md", "# Report\nOld.\n")
testutil.AssertFakeFile(t, sshDestination, "summary.txt", "Old summary\n")
writeSourceBundle(t, localSourceRoot, "new", testBundleOptions{
ID: "reports.new",
Created: testutil.DefaultCreated.Add(time.Hour),
Files: []testFile{
{Path: "report.md", Data: "# Report\nNew.\n"},
{Path: "summary.txt", Data: "New summary\n"},
},
})
var stdout bytes.Buffer
if err := runConfigWithBackendFactory(context.Background(), cfg, RunOptions{Stdout: &stdout}, provider); err != nil {
t.Fatalf("second Run() error = %v", err)
}
for _, want := range []string{
"destination=object-latest backend=s3 path_mapping=fixed target=. action=replace_takeover takeover_mode=same_pipeline",
"destination=ssh-latest backend=ssh path_mapping=fixed target=. action=replace_takeover takeover_mode=same_pipeline",
"replace_takeover=2",
} {
if !strings.Contains(stdout.String(), want) {
t.Fatalf("stdout = %q, want substring %q", stdout.String(), want)
}
}
testutil.AssertFakeFile(t, s3Destination, "report.md", "# Report\nNew.\n") testutil.AssertFakeFile(t, s3Destination, "report.md", "# Report\nNew.\n")
testutil.AssertFakeFile(t, s3Destination, "summary.txt", "New summary\n") testutil.AssertFakeFile(t, s3Destination, "summary.txt", "New summary\n")
testutil.AssertFakeMissing(t, s3Destination, "new/report.md") testutil.AssertFakeMissing(t, s3Destination, "new/report.md")
@@ -1221,7 +1358,7 @@ func TestRunContinuesAfterDestinationFailure(t *testing.T) {
for _, want := range []string{ for _, want := range []string{
"destination=archive-one backend=local action=error", "destination=archive-one backend=local action=error",
"destination=archive-two backend=local action=publish_new", "destination=archive-two backend=local action=publish_new",
"Final status: failed planned=1 publish_new=1 replace_older=0 force_replace=0 skipped=0 failed=1 dry_run=false", "Final status: failed planned=1 publish_new=1 replace_older=0 replace_conflict=0 replace_newer=0 replace_takeover=0 force_replace=0 skipped=0 failed=1 dry_run=false",
} { } {
if !strings.Contains(output, want) { if !strings.Contains(output, want) {
t.Fatalf("stdout = %q, want substring %q", output, want) t.Fatalf("stdout = %q, want substring %q", output, want)
@@ -1526,14 +1663,130 @@ func TestRunSkipsNewerDestination(t *testing.T) {
testutil.AssertFile(t, filepath.Join(destinationRoot, "report.md"), "newer\n") testutil.AssertFile(t, filepath.Join(destinationRoot, "report.md"), "newer\n")
} }
func TestRunFailsOnConflict(t *testing.T) { func TestRunReplacesConflictWhenTransferPolicyAllows(t *testing.T) {
sourceRoot := t.TempDir()
destinationRoot := t.TempDir()
manifest := writeSourceBundle(t, sourceRoot, "", testBundleOptions{})
conflict := manifest
conflict.ID = "other.source"
writeDestinationState(t, destinationRoot, "", conflict)
if err := os.WriteFile(filepath.Join(destinationRoot, "report.md"), []byte("old\n"), 0o600); err != nil {
t.Fatalf("write old output: %v", err)
}
configPath := writeConfigFile(t, `
pipelines:
- id: reports
source:
backend: local
path: `+sourceRoot+`
destinations:
- id: archive
backend: local
path: `+destinationRoot+`
takeover:
mode: never
transfer:
on_conflict: replace
`)
var stdout bytes.Buffer
err := Run(context.Background(), RunOptions{ConfigPath: configPath, DryRun: true, Stdout: &stdout})
if err != nil {
t.Fatalf("Run() error = %v", err)
}
output := stdout.String()
for _, want := range []string{
"action=replace_conflict",
"replace_conflict=1",
"force_replace=0",
} {
if !strings.Contains(output, want) {
t.Fatalf("stdout = %q, want substring %q", output, want)
}
}
var jsonOut bytes.Buffer
err = Run(context.Background(), RunOptions{ConfigPath: configPath, DryRun: true, Stdout: &jsonOut, OutputFormat: OutputFormatJSON})
if err != nil {
t.Fatalf("Run() JSON error = %v", err)
}
result := decodeAppResult(t, jsonOut.String())
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"] != "replace_conflict" {
t.Fatalf("action = %#v, want replace_conflict", actions[0])
}
summary, ok := result["summary"].(map[string]any)
if !ok || summary["replace_conflict"] != float64(1) || summary["force_replace"] != float64(0) {
t.Fatalf("summary = %#v, want replace_conflict without force", result["summary"])
}
}
func TestRunReplacesNewerWhenTransferPolicyAllows(t *testing.T) {
sourceRoot := t.TempDir()
destinationRoot := t.TempDir()
manifest := writeSourceBundle(t, sourceRoot, "", testBundleOptions{})
newer := manifest
newer.Created = newer.Created.Add(time.Hour)
writeDestinationState(t, destinationRoot, "", newer)
if err := os.WriteFile(filepath.Join(destinationRoot, "report.md"), []byte("newer\n"), 0o600); err != nil {
t.Fatalf("write newer output: %v", err)
}
configPath := writeConfigFile(t, `
pipelines:
- id: reports
source:
backend: local
path: `+sourceRoot+`
destinations:
- id: archive
backend: local
path: `+destinationRoot+`
transfer:
on_destination_newer: replace
`)
var stdout bytes.Buffer
err := Run(context.Background(), RunOptions{ConfigPath: configPath, DryRun: true, Stdout: &stdout})
if err != nil {
t.Fatalf("Run() error = %v", err)
}
output := stdout.String()
for _, want := range []string{
"action=replace_newer",
"replace_newer=1",
"force_replace=0",
} {
if !strings.Contains(output, want) {
t.Fatalf("stdout = %q, want substring %q", output, want)
}
}
}
func TestRunTakeoverNeverFailsOnConflict(t *testing.T) {
sourceRoot := t.TempDir() sourceRoot := t.TempDir()
destinationRoot := t.TempDir() destinationRoot := t.TempDir()
manifest := writeSourceBundle(t, sourceRoot, "", testBundleOptions{}) manifest := writeSourceBundle(t, sourceRoot, "", testBundleOptions{})
manifest.ID = "other.source" manifest.ID = "other.source"
writeDestinationState(t, destinationRoot, "", manifest) writeDestinationState(t, destinationRoot, "", manifest)
configPath := writeConfigFile(t, `
pipelines:
- id: reports
source:
backend: local
path: `+sourceRoot+`
destinations:
- id: archive
backend: local
path: `+destinationRoot+`
takeover:
mode: never
`)
err := Run(context.Background(), RunOptions{ConfigPath: writeLocalConfig(t, sourceRoot, destinationRoot)}) err := Run(context.Background(), RunOptions{ConfigPath: configPath})
if err == nil || !strings.Contains(err.Error(), "fail_conflict") { if err == nil || !strings.Contains(err.Error(), "fail_conflict") {
t.Fatalf("Run() error = %v, want fail_conflict", err) t.Fatalf("Run() error = %v, want fail_conflict", err)
} }
@@ -1649,7 +1902,7 @@ func TestRunExercisesRemoteBackendShapesThroughCommonPath(t *testing.T) {
"pipeline=local-to-ssh source=local", "pipeline=local-to-ssh source=local",
"destination=ssh-archive backend=ssh action=publish_new", "destination=ssh-archive backend=ssh action=publish_new",
"pipeline=ssh-to-local source=ssh", "pipeline=ssh-to-local source=ssh",
"Final status: ok planned=4 publish_new=4 replace_older=0 force_replace=0 skipped=0 failed=0 dry_run=true", "Final status: ok planned=4 publish_new=4 replace_older=0 replace_conflict=0 replace_newer=0 replace_takeover=0 force_replace=0 skipped=0 failed=0 dry_run=true",
} { } {
if !strings.Contains(dryRunOutput.String(), want) { if !strings.Contains(dryRunOutput.String(), want) {
t.Fatalf("dry-run output = %q, want substring %q", dryRunOutput.String(), want) t.Fatalf("dry-run output = %q, want substring %q", dryRunOutput.String(), want)
@@ -1823,6 +2076,25 @@ pipelines:
`) `)
} }
func writeSameSourcePreserveRelativeConfig(t *testing.T, sourceRoot, destinationRoot 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: preserve_relative
takeover:
mode: same_source
`)
}
func writeFanoutConfig(t *testing.T, sourceRoot, firstDestination, secondDestination string) string { func writeFanoutConfig(t *testing.T, sourceRoot, firstDestination, secondDestination string) string {
t.Helper() t.Helper()
return testutil.WriteFanoutLocalConfig(t, sourceRoot, firstDestination, secondDestination) return testutil.WriteFanoutLocalConfig(t, sourceRoot, firstDestination, secondDestination)

View File

@@ -635,7 +635,7 @@ func TestExecuteRunDryRun(t *testing.T) {
wantStdout := "Configured pipelines: 1\n" + wantStdout := "Configured pipelines: 1\n" +
"- pipeline=reports source=local bundles=1 destinations=archive\n" + "- 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" + " - 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" "Final status: ok planned=1 publish_new=1 replace_older=0 replace_conflict=0 replace_newer=0 replace_takeover=0 force_replace=0 skipped=0 failed=0 dry_run=true fixed_path=0\n"
if got := stdout.String(); got != wantStdout { if got := stdout.String(); got != wantStdout {
t.Fatalf("stdout = %q, want %q", got, wantStdout) t.Fatalf("stdout = %q, want %q", got, wantStdout)
} }

View File

@@ -57,6 +57,7 @@ type Destination struct {
Links *Links `yaml:"links"` Links *Links `yaml:"links"`
State StatePolicy `yaml:"state"` State StatePolicy `yaml:"state"`
Reconciliation ReconciliationPolicy `yaml:"reconciliation"` Reconciliation ReconciliationPolicy `yaml:"reconciliation"`
Takeover TakeoverPolicy `yaml:"takeover"`
Retention RetentionPolicy `yaml:"retention"` Retention RetentionPolicy `yaml:"retention"`
Transfer TransferPolicy `yaml:"transfer"` Transfer TransferPolicy `yaml:"transfer"`
} }
@@ -110,6 +111,7 @@ type MarkdownToHTML struct {
Enabled bool `yaml:"enabled"` Enabled bool `yaml:"enabled"`
Mode string `yaml:"mode"` Mode string `yaml:"mode"`
Input string `yaml:"input"` Input string `yaml:"input"`
CssHref string `yaml:"css_href"`
} }
type PathMapping struct { type PathMapping struct {
@@ -125,6 +127,10 @@ type ReconciliationPolicy struct {
Mode string `yaml:"mode"` Mode string `yaml:"mode"`
} }
type TakeoverPolicy struct {
Mode string `yaml:"mode"`
}
type StatePolicy struct { type StatePolicy struct {
Mode string `yaml:"mode"` Mode string `yaml:"mode"`
} }

View File

@@ -47,6 +47,13 @@ const (
ReconciliationModeMerge = "merge" ReconciliationModeMerge = "merge"
) )
const (
TakeoverModeSamePipeline = "same_pipeline"
TakeoverModeSameSource = "same_source"
TakeoverModeAnyManaged = "any_managed"
TakeoverModeNever = "never"
)
const ( const (
StateModeSingleOwner = "single_owner" StateModeSingleOwner = "single_owner"
StateModeSharedRoot = "shared_root" StateModeSharedRoot = "shared_root"
@@ -95,6 +102,9 @@ func ApplyDefaults(cfg *Config) {
if destination.Reconciliation.Mode == "" { if destination.Reconciliation.Mode == "" {
destination.Reconciliation.Mode = ReconciliationModeReplace destination.Reconciliation.Mode = ReconciliationModeReplace
} }
if destination.Takeover.Mode == "" {
destination.Takeover.Mode = TakeoverModeSamePipeline
}
if destination.Transfer.OnDestinationSame == "" { if destination.Transfer.OnDestinationSame == "" {
destination.Transfer.OnDestinationSame = TransferActionSkip destination.Transfer.OnDestinationSame = TransferActionSkip
} }

View File

@@ -39,6 +39,9 @@ pipelines:
if got, want := destination.State.Mode, StateModeSingleOwner; got != want { if got, want := destination.State.Mode, StateModeSingleOwner; got != want {
t.Fatalf("state mode default = %q, want %q", got, want) t.Fatalf("state mode default = %q, want %q", got, want)
} }
if got, want := destination.Takeover.Mode, TakeoverModeSamePipeline; got != want {
t.Fatalf("takeover mode default = %q, want %q", got, want)
}
if destination.Retention.Prune.Enabled { if destination.Retention.Prune.Enabled {
t.Fatal("retention.prune.enabled default = true, want false") t.Fatal("retention.prune.enabled default = true, want false")
} }
@@ -231,6 +234,50 @@ pipelines:
} }
} }
func TestLoadFileAcceptsExplicitTakeoverModes(t *testing.T) {
cfg := loadConfig(t, `
pipelines:
- id: reports
source:
backend: local
path: /source
destinations:
- id: same-pipeline
backend: local
path: /same-pipeline
takeover:
mode: same_pipeline
- id: same-source
backend: local
path: /same-source
takeover:
mode: same_source
- id: any-managed
backend: local
path: /any-managed
takeover:
mode: any_managed
- id: never
backend: local
path: /never
takeover:
mode: never
`)
destinations := cfg.Pipelines[0].Destinations
wants := []string{
TakeoverModeSamePipeline,
TakeoverModeSameSource,
TakeoverModeAnyManaged,
TakeoverModeNever,
}
for index, want := range wants {
if got := destinations[index].Takeover.Mode; got != want {
t.Fatalf("destinations[%d].takeover.mode = %q, want %q", index, got, want)
}
}
}
func TestLoadFileAcceptsRetentionPruneConfig(t *testing.T) { func TestLoadFileAcceptsRetentionPruneConfig(t *testing.T) {
cfg := loadConfig(t, ` cfg := loadConfig(t, `
pipelines: pipelines:
@@ -868,6 +915,38 @@ pipelines:
`, "on_destination_older must be replace or fail") `, "on_destination_older must be replace or fail")
} }
func TestLoadFileRejectsInvalidTakeoverMode(t *testing.T) {
assertLoadError(t, `
pipelines:
- id: reports
source:
backend: local
path: /source
destinations:
- id: archive
backend: local
path: /archive
takeover:
mode: unmanaged
`, "takeover.mode must be same_pipeline, same_source, any_managed, or never")
}
func TestLoadFileRejectsUnknownTakeoverFields(t *testing.T) {
assertLoadError(t, `
pipelines:
- id: reports
source:
backend: local
path: /source
destinations:
- id: archive
backend: local
path: /archive
takeover:
surprise: true
`, "field surprise not found")
}
func TestLoadFileRejectsInvalidValidationAction(t *testing.T) { func TestLoadFileRejectsInvalidValidationAction(t *testing.T) {
assertLoadError(t, ` assertLoadError(t, `
pipelines: pipelines:

View File

@@ -2,8 +2,10 @@ package config
import ( import (
"fmt" "fmt"
"net/url"
"regexp" "regexp"
"strings" "strings"
"unicode"
"gitea.maximumdirect.net/eric/distributor/internal/link" "gitea.maximumdirect.net/eric/distributor/internal/link"
) )
@@ -74,6 +76,7 @@ func Validate(cfg Config) error {
errs = validateLinks(errs, destinationContext+".links", destination.Links) errs = validateLinks(errs, destinationContext+".links", destination.Links)
errs = validateStatePolicy(errs, destinationContext+".state", destination.State) errs = validateStatePolicy(errs, destinationContext+".state", destination.State)
errs = validateReconciliationPolicy(errs, destinationContext+".reconciliation", destination.Reconciliation) errs = validateReconciliationPolicy(errs, destinationContext+".reconciliation", destination.Reconciliation)
errs = validateTakeoverPolicy(errs, destinationContext+".takeover", destination.Takeover)
errs = validateRetentionPolicy(errs, destinationContext+".retention", destination.Retention) errs = validateRetentionPolicy(errs, destinationContext+".retention", destination.Retention)
errs = validateTransferPolicy(errs, destinationContext+".transfer", destination.Transfer) errs = validateTransferPolicy(errs, destinationContext+".transfer", destination.Transfer)
} }
@@ -281,9 +284,15 @@ func ValidatePublishTransformPolicy(publish PublishPolicy, transform Transform)
if transform.MarkdownToHTML.Input != "" && !transform.MarkdownToHTML.Enabled { if transform.MarkdownToHTML.Input != "" && !transform.MarkdownToHTML.Enabled {
return fmt.Errorf("transform.markdown_to_html.input requires transform.markdown_to_html.enabled to be true") return fmt.Errorf("transform.markdown_to_html.input requires transform.markdown_to_html.enabled to be true")
} }
if transform.MarkdownToHTML.CssHref != "" && !transform.MarkdownToHTML.Enabled {
return fmt.Errorf("transform.markdown_to_html.css_href requires transform.markdown_to_html.enabled to be true")
}
if transform.MarkdownToHTML.Input != "" && mode != TransformModeIndex { if transform.MarkdownToHTML.Input != "" && mode != TransformModeIndex {
return fmt.Errorf("transform.markdown_to_html.input is only valid when mode is %s", TransformModeIndex) return fmt.Errorf("transform.markdown_to_html.input is only valid when mode is %s", TransformModeIndex)
} }
if err := validateCSSHref(transform.MarkdownToHTML.CssHref); err != nil {
return fmt.Errorf("transform.markdown_to_html.css_href %w", err)
}
if transform.MarkdownToHTML.Enabled && !publish.HTML { if transform.MarkdownToHTML.Enabled && !publish.HTML {
return fmt.Errorf("transform.markdown_to_html.enabled requires publish.html to be true") return fmt.Errorf("transform.markdown_to_html.enabled requires publish.html to be true")
} }
@@ -293,6 +302,49 @@ func ValidatePublishTransformPolicy(publish PublishPolicy, transform Transform)
return nil return nil
} }
func validateCSSHref(value string) error {
if value == "" {
return nil
}
for _, character := range value {
if unicode.IsControl(character) || unicode.IsSpace(character) {
return fmt.Errorf("must not contain whitespace or control characters")
}
}
if strings.ContainsAny(value, "\\<>\"'") {
return fmt.Errorf("must not contain backslashes or HTML-sensitive characters")
}
if strings.HasPrefix(value, "//") {
return fmt.Errorf("must not be scheme-relative")
}
parsed, err := url.Parse(value)
if err != nil {
return fmt.Errorf("must be a valid URL reference: %w", err)
}
if parsed.Fragment != "" {
return fmt.Errorf("must not include a fragment")
}
if parsed.Scheme != "" {
if parsed.Scheme != "http" && parsed.Scheme != "https" {
return fmt.Errorf("scheme must be http or https")
}
if parsed.Host == "" {
return fmt.Errorf("host is required for absolute URLs")
}
if parsed.User != nil {
return fmt.Errorf("must not include userinfo")
}
return nil
}
if parsed.Host != "" {
return fmt.Errorf("must not be scheme-relative")
}
if parsed.Path == "" {
return fmt.Errorf("relative URL path is required")
}
return nil
}
func validatePathMapping(errs ValidationErrors, context string, mapping PathMapping) ValidationErrors { func validatePathMapping(errs ValidationErrors, context string, mapping PathMapping) ValidationErrors {
if mapping.Mode != PathMappingPreserveRelative && mapping.Mode != PathMappingFixed { if mapping.Mode != PathMappingPreserveRelative && mapping.Mode != PathMappingFixed {
errs = append(errs, context+".mode must be "+PathMappingPreserveRelative+" or "+PathMappingFixed) errs = append(errs, context+".mode must be "+PathMappingPreserveRelative+" or "+PathMappingFixed)
@@ -324,6 +376,15 @@ func validateReconciliationPolicy(errs ValidationErrors, context string, policy
return errs return errs
} }
func validateTakeoverPolicy(errs ValidationErrors, context string, policy TakeoverPolicy) ValidationErrors {
switch policy.Mode {
case TakeoverModeSamePipeline, TakeoverModeSameSource, TakeoverModeAnyManaged, TakeoverModeNever:
default:
errs = append(errs, context+".mode must be "+TakeoverModeSamePipeline+", "+TakeoverModeSameSource+", "+TakeoverModeAnyManaged+", or "+TakeoverModeNever)
}
return errs
}
func validateRetentionPolicy(errs ValidationErrors, context string, policy RetentionPolicy) ValidationErrors { func validateRetentionPolicy(errs ValidationErrors, context string, policy RetentionPolicy) ValidationErrors {
prune := policy.Prune prune := policy.Prune
if !prune.Enabled { if !prune.Enabled {

View File

@@ -142,6 +142,64 @@ func TestValidateReconciliationPolicy(t *testing.T) {
} }
} }
func TestValidateTakeoverPolicy(t *testing.T) {
tests := []struct {
name string
mode string
wantErr bool
}{
{name: "same pipeline", mode: TakeoverModeSamePipeline},
{name: "same source", mode: TakeoverModeSameSource},
{name: "any managed", mode: TakeoverModeAnyManaged},
{name: "never", mode: TakeoverModeNever},
{name: "invalid", mode: "unmanaged", 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",
Takeover: TakeoverPolicy{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 TestValidateTakeoverPolicyReportsFieldContext(t *testing.T) {
cfg := Config{Pipelines: []Pipeline{{
ID: "reports",
Source: Backend{Backend: BackendLocal, Path: "/source"},
Destinations: []Destination{{
ID: "archive",
Backend: BackendLocal,
Path: "/destination",
Takeover: TakeoverPolicy{Mode: "unmanaged"},
}},
}}}
ApplyDefaults(&cfg)
err := Validate(cfg)
if err == nil {
t.Fatal("Validate() error = nil, want error")
}
want := "pipelines[0].destinations[0].takeover.mode must be same_pipeline, same_source, any_managed, or never"
if !strings.Contains(err.Error(), want) {
t.Fatalf("Validate() error = %q, want %q", err, want)
}
}
func TestValidateStatePolicy(t *testing.T) { func TestValidateStatePolicy(t *testing.T) {
tests := []struct { tests := []struct {
name string name string
@@ -328,6 +386,24 @@ func publishTransformPolicyCases() []publishTransformPolicyCase {
Input: "report.md", Input: "report.md",
}}, }},
}, },
{
name: "html only sidecar css href allowed",
publish: PublishPolicy{HTML: true},
transform: Transform{MarkdownToHTML: &MarkdownToHTML{
Enabled: true,
Mode: TransformModeSidecar,
CssHref: "/assets/report.css",
}},
},
{
name: "html only index css href allowed",
publish: PublishPolicy{HTML: true},
transform: Transform{MarkdownToHTML: &MarkdownToHTML{
Enabled: true,
Mode: TransformModeIndex,
CssHref: "assets/report.css?v=20260614",
}},
},
{ {
name: "source and html sidecar allowed", name: "source and html sidecar allowed",
publish: PublishPolicy{Source: true, HTML: true}, publish: PublishPolicy{Source: true, HTML: true},
@@ -425,6 +501,16 @@ func publishTransformPolicyCases() []publishTransformPolicyCase {
}}, }},
wantErr: true, wantErr: true,
}, },
{
name: "disabled markdown css href rejected",
publish: PublishPolicy{Source: true},
transform: Transform{MarkdownToHTML: &MarkdownToHTML{
Enabled: false,
Mode: TransformModeSidecar,
CssHref: "/assets/report.css",
}},
wantErr: true,
},
{ {
name: "disabled markdown wrong mode rejected", name: "disabled markdown wrong mode rejected",
publish: PublishPolicy{Source: true}, publish: PublishPolicy{Source: true},
@@ -436,3 +522,44 @@ func publishTransformPolicyCases() []publishTransformPolicyCase {
}, },
} }
} }
func TestValidateCSSHref(t *testing.T) {
tests := []struct {
name string
value string
wantErr bool
}{
{name: "empty"},
{name: "root relative", value: "/assets/report.css"},
{name: "relative", value: "assets/report.css"},
{name: "parent relative", value: "../assets/report.css"},
{name: "query", value: "/assets/report.css?v=20260614"},
{name: "http", value: "http://example.com/report.css"},
{name: "https", value: "https://example.com/assets/report.css?v=1"},
{name: "javascript", value: "javascript:alert(1)", wantErr: true},
{name: "data", value: "data:text/css,body{}", wantErr: true},
{name: "file", value: "file:///tmp/report.css", wantErr: true},
{name: "scheme relative", value: "//example.com/report.css", wantErr: true},
{name: "userinfo", value: "https://user@example.com/report.css", wantErr: true},
{name: "fragment", value: "/assets/report.css#main", wantErr: true},
{name: "space", value: "/assets/report css", wantErr: true},
{name: "tab", value: "/assets/report\tcss", wantErr: true},
{name: "newline", value: "/assets/report\ncss", wantErr: true},
{name: "backslash", value: `assets\report.css`, wantErr: true},
{name: "less than", value: "/assets/<report>.css", wantErr: true},
{name: "double quote", value: `/assets/"report".css`, wantErr: true},
{name: "single quote", value: "/assets/'report'.css", wantErr: true},
{name: "query only", value: "?v=1", wantErr: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := validateCSSHref(tt.value)
if tt.wantErr && err == nil {
t.Fatal("validateCSSHref() error = nil, want error")
}
if !tt.wantErr && err != nil {
t.Fatalf("validateCSSHref() error = %v", err)
}
})
}
}

View File

@@ -16,7 +16,7 @@ func Execute(ctx context.Context, req Request, plan Plan) error {
switch plan.Action { switch plan.Action {
case ActionSkipSame, ActionSkipDestinationNewer: case ActionSkipSame, ActionSkipDestinationNewer:
return nil return nil
case ActionPublishNew, ActionReplaceOlder, ActionForceReplace: case ActionPublishNew, ActionReplaceOlder, ActionReplaceConflict, ActionReplaceNewer, ActionReplaceTakeover, ActionForceReplace:
if usesSharedRootState(req, plan) { if usesSharedRootState(req, plan) {
return executeSharedRoot(ctx, req, plan) return executeSharedRoot(ctx, req, plan)
} }
@@ -24,11 +24,11 @@ func Execute(ctx context.Context, req Request, plan Plan) error {
return fmt.Errorf("cannot execute action %s: %s", plan.Action, plan.Reason) return fmt.Errorf("cannot execute action %s: %s", plan.Action, plan.Reason)
} }
if plan.Action == ActionReplaceOlder { if plan.Action == ActionReplaceOlder || plan.Action == ActionReplaceConflict || plan.Action == ActionReplaceNewer || plan.Action == ActionReplaceTakeover {
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 plan.Reconciliation.Mode == config.ReconciliationModeReplace { if plan.Reconciliation.Mode == config.ReconciliationModeReplace || plan.Action == ActionReplaceConflict || plan.Action == ActionReplaceTakeover {
if err := req.DestinationBackend.DeleteManagedBundle(ctx, req.DestinationBundlePath, state.ManagedOutputPaths(*plan.ExistingState), storage.DeleteOptions{IgnoreMissing: true, PruneEmptyDirs: true}); err != nil { if err := req.DestinationBackend.DeleteManagedBundle(ctx, req.DestinationBundlePath, state.ManagedOutputPaths(*plan.ExistingState), storage.DeleteOptions{IgnoreMissing: true, PruneEmptyDirs: true}); err != nil {
return err return err
} }
@@ -148,7 +148,7 @@ func executeSharedRoot(ctx context.Context, req Request, plan Plan) error {
return err return err
} }
} }
if plan.Action == ActionReplaceOlder && plan.Reconciliation.Mode == config.ReconciliationModeReplace { if plan.Action == ActionReplaceTakeover || plan.Action == ActionReplaceConflict || (isReconciliationReplacementAction(plan.Action) && plan.Reconciliation.Mode == config.ReconciliationModeReplace) {
if err := req.DestinationBackend.DeleteManagedOutputs(ctx, req.DestinationBundlePath, sharedRootOutputPaths(plan.OwnerOutputsToDelete), storage.DeleteOptions{IgnoreMissing: true, PruneEmptyDirs: true}); err != nil { if err := req.DestinationBackend.DeleteManagedOutputs(ctx, req.DestinationBundlePath, sharedRootOutputPaths(plan.OwnerOutputsToDelete), storage.DeleteOptions{IgnoreMissing: true, PruneEmptyDirs: true}); err != nil {
return err return err
} }
@@ -158,7 +158,7 @@ func executeSharedRoot(ctx context.Context, req Request, plan Plan) error {
newOutputs := make([]Output, 0, len(plan.Outputs)) newOutputs := make([]Output, 0, len(plan.Outputs))
cleanup := func() { cleanup := func() {
outputs := writtenOutputs outputs := writtenOutputs
if plan.Reconciliation.Mode == config.ReconciliationModeMerge { if isReconciliationReplacementAction(plan.Action) && plan.Reconciliation.Mode == config.ReconciliationModeMerge {
outputs = newOutputs outputs = newOutputs
} }
_ = req.DestinationBackend.DeleteManagedOutputs(ctx, req.DestinationBundlePath, ManagedOutputPaths(outputs), storage.DeleteOptions{IgnoreMissing: true, PruneEmptyDirs: true}) _ = req.DestinationBackend.DeleteManagedOutputs(ctx, req.DestinationBundlePath, ManagedOutputPaths(outputs), storage.DeleteOptions{IgnoreMissing: true, PruneEmptyDirs: true})
@@ -257,6 +257,11 @@ func outputManagedBySharedRootPlan(output Output, plan Plan) bool {
return true return true
} }
} }
for _, existing := range plan.TakenOverOwnerOutputs {
if existing.Path == output.DestinationPath {
return true
}
}
return false return false
} }
@@ -273,7 +278,7 @@ func stateOutputsForPlan(plan Plan, now time.Time) ([]state.OutputFile, error) {
} }
func usesMergeRetention(plan Plan) bool { func usesMergeRetention(plan Plan) bool {
return plan.Reconciliation.Mode == config.ReconciliationModeMerge && plan.Action == ActionReplaceOlder return plan.Reconciliation.Mode == config.ReconciliationModeMerge && isReconciliationReplacementAction(plan.Action)
} }
func sharedRootStateForPlan(req Request, plan Plan, now time.Time) (state.SharedRootState, error) { func sharedRootStateForPlan(req Request, plan Plan, now time.Time) (state.SharedRootState, error) {
@@ -283,6 +288,7 @@ func sharedRootStateForPlan(req Request, plan Plan, now time.Time) (state.Shared
scope = state.CurrentOwnerScope(req.PipelineID, req.DestinationID) scope = state.CurrentOwnerScope(req.PipelineID, req.DestinationID)
} }
base := sharedRootBaseState(req, plan, now) base := sharedRootBaseState(req, plan, now)
base = removeTakenOverSharedRootOutputs(base, plan.TakenOverOwnerOutputs)
owner := state.OwnerRecord{ owner := state.OwnerRecord{
Scope: scope, Scope: scope,
Reconciliation: state.ReconciliationPolicy{Mode: plan.Reconciliation.Mode}, Reconciliation: state.ReconciliationPolicy{Mode: plan.Reconciliation.Mode},
@@ -292,7 +298,7 @@ func sharedRootStateForPlan(req Request, plan Plan, now time.Time) (state.Shared
owner.Links = &state.LinkState{PrimaryURL: plan.PrimaryURL} owner.Links = &state.LinkState{PrimaryURL: plan.PrimaryURL}
} }
planned := state.ProjectSharedRootOutputs(StateOutputProjections(plan.Outputs), currentOwnerSharedRootOutputs(plan), scope, req.SourceBundle.Manifest, now) planned := state.ProjectSharedRootOutputs(StateOutputProjections(plan.Outputs), currentOwnerSharedRootOutputs(plan), scope, req.SourceBundle.Manifest, now)
if plan.Action == ActionReplaceOlder && plan.Reconciliation.Mode == config.ReconciliationModeMerge { if isReconciliationReplacementAction(plan.Action) && plan.Reconciliation.Mode == config.ReconciliationModeMerge {
return state.MergeOwnerOutputs(base, scope, owner, planned) return state.MergeOwnerOutputs(base, scope, owner, planned)
} }
return state.ReplaceOwnerOutputs(base, scope, owner, planned) return state.ReplaceOwnerOutputs(base, scope, owner, planned)
@@ -319,6 +325,22 @@ func sharedRootBaseState(req Request, plan Plan, now time.Time) state.SharedRoot
return newSharedRootState(req, now) return newSharedRootState(req, now)
} }
func removeTakenOverSharedRootOutputs(sharedRoot state.SharedRootState, takenOver []state.SharedRootOutputFile) state.SharedRootState {
if len(takenOver) == 0 {
return sharedRoot
}
paths := sharedRootOutputPathSet(takenOver)
next := sharedRoot
next.Outputs = make([]state.SharedRootOutputFile, 0, len(sharedRoot.Outputs))
for _, output := range sharedRoot.Outputs {
if _, remove := paths[output.Path]; remove {
continue
}
next.Outputs = append(next.Outputs, output)
}
return next
}
func newSharedRootState(req Request, now time.Time) state.SharedRootState { func newSharedRootState(req Request, now time.Time) state.SharedRootState {
return state.SharedRootState{ return state.SharedRootState{
SchemaVersion: state.SharedRootSchemaVersion, SchemaVersion: state.SharedRootSchemaVersion,

View File

@@ -120,6 +120,71 @@ func TestExecuteMergeRetainsOmittedAndOverwritesManagedOutputs(t *testing.T) {
} }
} }
func TestExecuteReplaceConflictDeletesOmittedManagedOutputs(t *testing.T) {
sourceBackend := fake.New()
sourceBundle := testutil.WriteFakeSourceBundle(t, sourceBackend, "", testutil.BundleOptions{
Files: []testutil.SourceFile{{Path: "report.md", Data: "# Report\nNew.\n"}},
})
destinationBackend := fake.New()
conflict := sourceBundle.Manifest
conflict.ID = "other.source"
conflict.Files = append([]bundle.ManifestFile(nil), testutil.ValidManifest(testutil.BundleOptions{}).Files...)
conflict.Digest = bundle.BundleDigest(conflict.Files)
testutil.WriteFakeDestinationState(t, destinationBackend, "", conflict, testutil.DestinationStateOptions{})
req := testRequest(sourceBackend, destinationBackend, sourceBundle, config.ReconciliationModeMerge)
req.Takeover = config.TakeoverPolicy{Mode: config.TakeoverModeNever}
req.Transfer.OnConflict = config.TransferActionReplace
plan, err := Build(context.Background(), req)
if err != nil {
t.Fatalf("Build() error = %v", err)
}
if plan.Action != ActionReplaceConflict {
t.Fatalf("plan action = %s, want replace_conflict", plan.Action)
}
if err := Execute(context.Background(), req, plan); err != nil {
t.Fatalf("Execute() error = %v", err)
}
testutil.AssertFakeFile(t, destinationBackend, "report.md", "# Report\nNew.\n")
testutil.AssertFakeMissing(t, destinationBackend, "summary.txt")
destinationState := readFakeState(t, destinationBackend, "")
outputs := outputsByPath(destinationState.Outputs)
if got, want := len(outputs), 1; got != want {
t.Fatalf("state output count = %d, want %d", got, want)
}
if _, ok := outputs["summary.txt"]; ok {
t.Fatalf("state retained summary.txt after replace_conflict: %#v", destinationState.Outputs)
}
}
func TestExecuteReplaceNewerUsesManagedReplacement(t *testing.T) {
sourceBackend := fake.New()
sourceBundle := testutil.WriteFakeSourceBundle(t, sourceBackend, "", testutil.BundleOptions{
Files: []testutil.SourceFile{{Path: "report.md", Data: "# Report\nNew.\n"}},
})
destinationBackend := fake.New()
newer := sourceBundle.Manifest
newer.Created = newer.Created.Add(time.Hour)
newer.Files = append([]bundle.ManifestFile(nil), testutil.ValidManifest(testutil.BundleOptions{}).Files...)
newer.Digest = bundle.BundleDigest(newer.Files)
testutil.WriteFakeDestinationState(t, destinationBackend, "", newer, testutil.DestinationStateOptions{})
req := testRequest(sourceBackend, destinationBackend, sourceBundle, config.ReconciliationModeReplace)
req.Transfer.OnDestinationNewer = config.TransferActionReplace
plan, err := Build(context.Background(), req)
if err != nil {
t.Fatalf("Build() error = %v", err)
}
if plan.Action != ActionReplaceNewer {
t.Fatalf("plan action = %s, want replace_newer", plan.Action)
}
if err := Execute(context.Background(), req, plan); err != nil {
t.Fatalf("Execute() error = %v", err)
}
testutil.AssertFakeFile(t, destinationBackend, "report.md", "# Report\nNew.\n")
testutil.AssertFakeMissing(t, destinationBackend, "summary.txt")
}
func TestExecuteMergeFailsOnUnmanagedDestinationPathCollision(t *testing.T) { func TestExecuteMergeFailsOnUnmanagedDestinationPathCollision(t *testing.T) {
sourceBackend := fake.New() sourceBackend := fake.New()
sourceBundle := testutil.WriteFakeSourceBundle(t, sourceBackend, "", testutil.BundleOptions{ sourceBundle := testutil.WriteFakeSourceBundle(t, sourceBackend, "", testutil.BundleOptions{
@@ -189,7 +254,6 @@ func TestExecuteFixedPathSupportsReconciliationModes(t *testing.T) {
}) })
destinationBackend := fake.New() destinationBackend := fake.New()
older := sourceBundle.Manifest older := sourceBundle.Manifest
older.ID = "older.source"
older.Created = older.Created.Add(-time.Hour) older.Created = older.Created.Add(-time.Hour)
testutil.WriteFakeDestinationState(t, destinationBackend, "", older, testutil.DestinationStateOptions{}) testutil.WriteFakeDestinationState(t, destinationBackend, "", older, testutil.DestinationStateOptions{})

View File

@@ -29,61 +29,6 @@ func TestBuildPlansForcedReplacementOnlyWhenExplicit(t *testing.T) {
wantReason: "fail_unmanaged", wantReason: "fail_unmanaged",
forceAction: true, forceAction: true,
}, },
{
name: "different source id",
prepare: func(t *testing.T, backend *fake.Backend, source bundle.Manifest) {
t.Helper()
conflict := source
conflict.ID = "other.source"
testutil.WriteFakeDestinationState(t, backend, "bundle", conflict, testutil.DestinationStateOptions{})
},
transfer: conflictReplaceTransfer(),
wantReason: "requires --force",
forceAction: true,
},
{
name: "same created digest conflict",
prepare: func(t *testing.T, backend *fake.Backend, source bundle.Manifest) {
t.Helper()
conflict := testutil.ValidManifest(testutil.BundleOptions{Files: []testutil.SourceFile{{Path: "report.md", Data: "# Different\n"}}})
testutil.WriteFakeDestinationState(t, backend, "bundle", conflict, testutil.DestinationStateOptions{})
},
transfer: conflictReplaceTransfer(),
wantReason: "requires --force",
forceAction: true,
},
{
name: "pipeline mismatch",
prepare: func(t *testing.T, backend *fake.Backend, source bundle.Manifest) {
t.Helper()
testutil.WriteFakeDestinationState(t, backend, "bundle", source, testutil.DestinationStateOptions{PipelineID: "other-pipeline"})
},
transfer: conflictReplaceTransfer(),
wantReason: "requires --force",
forceAction: true,
},
{
name: "destination mismatch",
prepare: func(t *testing.T, backend *fake.Backend, source bundle.Manifest) {
t.Helper()
testutil.WriteFakeDestinationState(t, backend, "bundle", source, testutil.DestinationStateOptions{DestinationID: "other-destination"})
},
transfer: conflictReplaceTransfer(),
wantReason: "requires --force",
forceAction: true,
},
{
name: "newer destination",
prepare: func(t *testing.T, backend *fake.Backend, source bundle.Manifest) {
t.Helper()
newer := source
newer.Created = newer.Created.AddDate(0, 0, 1)
testutil.WriteFakeDestinationState(t, backend, "bundle", newer, testutil.DestinationStateOptions{})
},
transfer: newerReplaceTransfer(),
wantReason: "requires --force",
forceAction: true,
},
} }
for _, tt := range tests { for _, tt := range tests {
@@ -113,6 +58,89 @@ func TestBuildPlansForcedReplacementOnlyWhenExplicit(t *testing.T) {
} }
} }
func TestBuildPlansConflictReplacementWithoutForce(t *testing.T) {
tests := []struct {
name string
prepare func(t *testing.T, backend *fake.Backend, source bundle.Manifest)
wantReason string
}{
{
name: "different source id",
prepare: func(t *testing.T, backend *fake.Backend, source bundle.Manifest) {
t.Helper()
conflict := source
conflict.ID = "other.source"
testutil.WriteFakeDestinationState(t, backend, "bundle", conflict, testutil.DestinationStateOptions{})
},
wantReason: "destination source id differs",
},
{
name: "same created digest conflict",
prepare: func(t *testing.T, backend *fake.Backend, source bundle.Manifest) {
t.Helper()
conflict := testutil.ValidManifest(testutil.BundleOptions{Files: []testutil.SourceFile{{Path: "report.md", Data: "# Different\n"}}})
testutil.WriteFakeDestinationState(t, backend, "bundle", conflict, testutil.DestinationStateOptions{})
},
wantReason: "same id and created time but different digest",
},
{
name: "pipeline mismatch",
prepare: func(t *testing.T, backend *fake.Backend, source bundle.Manifest) {
t.Helper()
testutil.WriteFakeDestinationState(t, backend, "bundle", source, testutil.DestinationStateOptions{PipelineID: "other-pipeline"})
},
wantReason: "pipeline id",
},
{
name: "destination mismatch",
prepare: func(t *testing.T, backend *fake.Backend, source bundle.Manifest) {
t.Helper()
testutil.WriteFakeDestinationState(t, backend, "bundle", source, testutil.DestinationStateOptions{DestinationID: "other-destination"})
},
wantReason: "destination id",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
sourceBackend := fake.New()
sourceBundle := testutil.WriteFakeSourceBundle(t, sourceBackend, "bundle", testutil.BundleOptions{})
destinationBackend := fake.New()
tt.prepare(t, destinationBackend, sourceBundle.Manifest)
req := forceRequest(sourceBackend, destinationBackend, sourceBundle, conflictReplaceTransfer())
plan, err := Build(context.Background(), req)
if err != nil {
t.Fatalf("Build() error = %v", err)
}
if plan.Action != ActionReplaceConflict || plan.Force {
t.Fatalf("plan action = %s force=%t, want replace_conflict without force", plan.Action, plan.Force)
}
if !strings.Contains(plan.Reason, tt.wantReason) {
t.Fatalf("plan reason = %q, want %q", plan.Reason, tt.wantReason)
}
})
}
}
func TestBuildPlansNewerReplacementWithoutForce(t *testing.T) {
sourceBackend := fake.New()
sourceBundle := testutil.WriteFakeSourceBundle(t, sourceBackend, "bundle", testutil.BundleOptions{})
destinationBackend := fake.New()
newer := sourceBundle.Manifest
newer.Created = newer.Created.AddDate(0, 0, 1)
testutil.WriteFakeDestinationState(t, destinationBackend, "bundle", newer, testutil.DestinationStateOptions{})
req := forceRequest(sourceBackend, destinationBackend, sourceBundle, newerReplaceTransfer())
plan, err := Build(context.Background(), req)
if err != nil {
t.Fatalf("Build() error = %v", err)
}
if plan.Action != ActionReplaceNewer || plan.Force {
t.Fatalf("plan action = %s force=%t, want replace_newer without force", plan.Action, plan.Force)
}
}
func TestBuildRequiresConflictPolicyForStateConflicts(t *testing.T) { func TestBuildRequiresConflictPolicyForStateConflicts(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{})
@@ -166,6 +194,7 @@ func forceRequest(sourceBackend, destinationBackend *fake.Backend, sourceBundle
DestinationBackend: destinationBackend, DestinationBackend: destinationBackend,
DestinationBundlePath: sourceBundle.RootRelativePath, DestinationBundlePath: sourceBundle.RootRelativePath,
Publish: config.PublishPolicy{Source: true}, Publish: config.PublishPolicy{Source: true},
Takeover: config.TakeoverPolicy{Mode: config.TakeoverModeNever},
Transfer: transfer, Transfer: transfer,
DistributorVersion: "test", DistributorVersion: "test",
} }

View File

@@ -29,6 +29,7 @@ func PlanOutputs(ctx context.Context, req Request) ([]Output, error) {
Markdown: transform.MarkdownOptions{ Markdown: transform.MarkdownOptions{
Mode: req.Transform.MarkdownToHTML.Mode, Mode: req.Transform.MarkdownToHTML.Mode,
Input: req.Transform.MarkdownToHTML.Input, Input: req.Transform.MarkdownToHTML.Input,
CssHref: req.Transform.MarkdownToHTML.CssHref,
}, },
}) })
if err != nil { if err != nil {

View File

@@ -167,6 +167,7 @@ func TestPlanOutputsPassesMarkdownOptions(t *testing.T) {
Enabled: true, Enabled: true,
Mode: config.TransformModeIndex, Mode: config.TransformModeIndex,
Input: "report.md", Input: "report.md",
CssHref: "/assets/report.css",
}}, }},
Transformers: testResolver{transform.MarkdownToHTML: transformer}, Transformers: testResolver{transform.MarkdownToHTML: transformer},
}) })
@@ -174,8 +175,8 @@ func TestPlanOutputsPassesMarkdownOptions(t *testing.T) {
if err != nil { if err != nil {
t.Fatalf("PlanOutputs() error = %v", err) t.Fatalf("PlanOutputs() error = %v", err)
} }
if transformer.request.Markdown.Mode != config.TransformModeIndex || transformer.request.Markdown.Input != "report.md" { if transformer.request.Markdown.Mode != config.TransformModeIndex || transformer.request.Markdown.Input != "report.md" || transformer.request.Markdown.CssHref != "/assets/report.css" {
t.Fatalf("markdown options = %#v, want index/report.md", transformer.request.Markdown) t.Fatalf("markdown options = %#v, want index/report.md with css href", transformer.request.Markdown)
} }
} }

View File

@@ -16,11 +16,14 @@ type Action string
const ( const (
ActionPublishNew Action = "publish_new" ActionPublishNew Action = "publish_new"
ActionReplaceOlder Action = "replace_older" ActionReplaceOlder Action = "replace_older"
ActionReplaceConflict Action = "replace_conflict"
ActionReplaceNewer Action = "replace_newer"
ActionSkipSame Action = "skip_same" ActionSkipSame Action = "skip_same"
ActionSkipDestinationNewer Action = "skip_destination_newer" ActionSkipDestinationNewer Action = "skip_destination_newer"
ActionFailConflict Action = "fail_conflict" ActionFailConflict Action = "fail_conflict"
ActionFailUnmanaged Action = "fail_unmanaged" ActionFailUnmanaged Action = "fail_unmanaged"
ActionForceReplace Action = "force_replace" ActionForceReplace Action = "force_replace"
ActionReplaceTakeover Action = "replace_takeover"
) )
type Request struct { type Request struct {
@@ -36,6 +39,7 @@ type Request struct {
Links *config.Links Links *config.Links
State config.StatePolicy State config.StatePolicy
Reconciliation config.ReconciliationPolicy Reconciliation config.ReconciliationPolicy
Takeover config.TakeoverPolicy
Transformers TransformerResolver Transformers TransformerResolver
Transfer config.TransferPolicy Transfer config.TransferPolicy
DistributorVersion string DistributorVersion string
@@ -60,10 +64,12 @@ type Plan struct {
StateMode string StateMode string
OwnerScope state.OwnerScope OwnerScope state.OwnerScope
Reconciliation config.ReconciliationPolicy Reconciliation config.ReconciliationPolicy
TakeoverMode string
Outputs []Output Outputs []Output
ExistingState *state.DistributorState ExistingState *state.DistributorState
ExistingSharedRoot *state.SharedRootState ExistingSharedRoot *state.SharedRootState
OtherOwnerOutputs []state.SharedRootOutputFile OtherOwnerOutputs []state.SharedRootOutputFile
TakenOverOwnerOutputs []state.SharedRootOutputFile
RetainedOwnerOutputs []state.SharedRootOutputFile RetainedOwnerOutputs []state.SharedRootOutputFile
OwnerOutputsToDelete []state.SharedRootOutputFile OwnerOutputsToDelete []state.SharedRootOutputFile
OwnerOutputsToWrite []Output OwnerOutputsToWrite []Output
@@ -96,10 +102,14 @@ func Build(ctx context.Context, req Request) (Plan, error) {
if err != nil { if err != nil {
return Plan{}, err return Plan{}, err
} }
comparison := compareDestination(req, status)
action, reason := actionForComparison(comparison, req.Transfer, req.Force)
reconciliation := normalizeReconciliation(req.Reconciliation) reconciliation := normalizeReconciliation(req.Reconciliation)
stateMode := normalizeState(req.State).Mode stateMode := normalizeState(req.State).Mode
comparison := compareDestination(req, status)
action, reason := actionForComparison(comparison, req.Transfer, req.Force)
if takeoverActionAllowed(req, status, comparison, stateMode, action) {
action = ActionReplaceTakeover
reason = comparison.Reason
}
plan := Plan{ plan := Plan{
PipelineID: req.PipelineID, PipelineID: req.PipelineID,
DestinationID: req.DestinationID, DestinationID: req.DestinationID,
@@ -114,24 +124,28 @@ func Build(ctx context.Context, req Request) (Plan, error) {
StateMode: stateMode, StateMode: stateMode,
OwnerScope: state.CurrentOwnerScope(req.PipelineID, req.DestinationID), OwnerScope: state.CurrentOwnerScope(req.PipelineID, req.DestinationID),
Reconciliation: reconciliation, Reconciliation: reconciliation,
TakeoverMode: normalizeTakeover(req.Takeover).Mode,
Outputs: outputs, Outputs: outputs,
ExistingState: status.State, ExistingState: status.State,
ExistingSharedRoot: status.SharedRoot, ExistingSharedRoot: status.SharedRoot,
} }
if stateMode == config.StateModeSharedRoot { if stateMode == config.StateModeSharedRoot {
sharedDetails, err := planSharedRootOwner(ctx, req, status, action, reconciliation, outputs) sharedDetails, err := planSharedRootOwner(ctx, req, status, action, reconciliation, outputs)
plan.Action = sharedDetails.Action
if sharedDetails.Reason != "" {
plan.Reason = sharedDetails.Reason
}
plan.OtherOwnerOutputs = sharedDetails.OtherOwnerOutputs plan.OtherOwnerOutputs = sharedDetails.OtherOwnerOutputs
plan.TakenOverOwnerOutputs = sharedDetails.TakenOverOwnerOutputs
plan.RetainedOwnerOutputs = sharedDetails.RetainedOwnerOutputs plan.RetainedOwnerOutputs = sharedDetails.RetainedOwnerOutputs
plan.OwnerOutputsToDelete = sharedDetails.OwnerOutputsToDelete plan.OwnerOutputsToDelete = sharedDetails.OwnerOutputsToDelete
plan.OwnerOutputsToWrite = sharedDetails.OwnerOutputsToWrite plan.OwnerOutputsToWrite = sharedDetails.OwnerOutputsToWrite
if err != nil { if err != nil {
plan.Action = sharedDetails.Action
plan.Reason = sharedDetails.Reason
return plan, err return plan, err
} }
} }
if action == ActionFailConflict || action == ActionFailUnmanaged { if plan.Action == ActionFailConflict || plan.Action == ActionFailUnmanaged {
return plan, fmt.Errorf("%s: %s", action, reason) return plan, fmt.Errorf("%s: %s", plan.Action, plan.Reason)
} }
return plan, nil return plan, nil
} }
@@ -162,6 +176,11 @@ func validateRequest(req Request) error {
default: default:
return fmt.Errorf("state.mode must be %s or %s", config.StateModeSingleOwner, config.StateModeSharedRoot) return fmt.Errorf("state.mode must be %s or %s", config.StateModeSingleOwner, config.StateModeSharedRoot)
} }
switch normalizeTakeover(req.Takeover).Mode {
case config.TakeoverModeSamePipeline, config.TakeoverModeSameSource, config.TakeoverModeAnyManaged, config.TakeoverModeNever:
default:
return fmt.Errorf("takeover.mode must be %s, %s, %s, or %s", config.TakeoverModeSamePipeline, config.TakeoverModeSameSource, config.TakeoverModeAnyManaged, config.TakeoverModeNever)
}
return nil return nil
} }
@@ -179,6 +198,13 @@ func normalizeState(policy config.StatePolicy) config.StatePolicy {
return policy return policy
} }
func normalizeTakeover(policy config.TakeoverPolicy) config.TakeoverPolicy {
if policy.Mode == "" {
policy.Mode = config.TakeoverModeSamePipeline
}
return policy
}
func compareDestination(req Request, status state.DestinationStatus) state.Comparison { func compareDestination(req Request, status state.DestinationStatus) state.Comparison {
if normalizeState(req.State).Mode == config.StateModeSharedRoot { if normalizeState(req.State).Mode == config.StateModeSharedRoot {
scope := state.CurrentOwnerScope(req.PipelineID, req.DestinationID) scope := state.CurrentOwnerScope(req.PipelineID, req.DestinationID)
@@ -194,21 +220,19 @@ func compareDestination(req Request, status state.DestinationStatus) state.Compa
return state.Comparison{Outcome: state.OutcomeDestinationOlder, Reason: "fixed destination source is older than selected source"} return state.Comparison{Outcome: state.OutcomeDestinationOlder, Reason: "fixed destination source is older than selected source"}
} }
if destinationManifest.Created.After(req.SourceBundle.Manifest.Created) { if destinationManifest.Created.After(req.SourceBundle.Manifest.Created) {
return state.Comparison{Outcome: state.OutcomeDestinationNewer, Reason: "fixed destination source is newer than selected source"} return state.Comparison{
Outcome: state.OutcomeDestinationNewer,
Reason: "fixed destination source is newer than selected source",
Detail: state.ComparisonDetail{
Kind: state.ComparisonDetailDestinationNewer,
CurrentSourceID: req.SourceBundle.Manifest.ID,
DestinationSourceID: destinationManifest.ID,
},
}
} }
return comparison return comparison
} }
comparison := state.Compare(req.SourceBundle.Manifest, req.PipelineID, req.DestinationID, status) 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 return comparison
} }
@@ -226,6 +250,7 @@ type sharedRootPlanDetails struct {
Action Action Action Action
Reason string Reason string
OtherOwnerOutputs []state.SharedRootOutputFile OtherOwnerOutputs []state.SharedRootOutputFile
TakenOverOwnerOutputs []state.SharedRootOutputFile
RetainedOwnerOutputs []state.SharedRootOutputFile RetainedOwnerOutputs []state.SharedRootOutputFile
OwnerOutputsToDelete []state.SharedRootOutputFile OwnerOutputsToDelete []state.SharedRootOutputFile
OwnerOutputsToWrite []Output OwnerOutputsToWrite []Output
@@ -244,19 +269,34 @@ func planSharedRootOwner(ctx context.Context, req Request, status state.Destinat
details.OwnerOutputsToWrite = append([]Output(nil), outputs...) details.OwnerOutputsToWrite = append([]Output(nil), outputs...)
return details, nil return details, nil
} }
if conflict, ok := sharedRootPathOwnershipConflict(status, scope, plannedPaths); ok { conflicts := sharedRootPathOwnershipConflicts(status, scope, plannedPaths)
reason := fmt.Sprintf("destination output path %s is owned by %s/%s", conflict.Path, conflict.Owner.PipelineID, conflict.Owner.DestinationID) if len(conflicts) > 0 {
conflictAction := ActionReplaceTakeover
for _, conflict := range conflicts {
if sharedRootTakeoverAllowed(req, status, conflict) {
continue
}
if req.Transfer.OnConflict == config.TransferActionReplace {
conflictAction = ActionReplaceConflict
continue
}
reason := sharedRootOwnershipConflictReason(conflict)
details.Action = ActionFailConflict details.Action = ActionFailConflict
details.Reason = reason details.Reason = reason
return details, fmt.Errorf("%s: %s", ActionFailConflict, reason) return details, fmt.Errorf("%s: %s", ActionFailConflict, reason)
} }
details.Action = conflictAction
details.Reason = sharedRootOwnershipConflictReason(conflicts[0])
details.TakenOverOwnerOutputs = sharedRootConflictOutputs(status.SharedRoot, conflicts)
}
if err := rejectSharedRootUnmanagedCollisions(ctx, req.DestinationBackend, req.DestinationBundlePath, status, scope, plannedPaths); err != nil { if err := rejectSharedRootUnmanagedCollisions(ctx, req.DestinationBackend, req.DestinationBundlePath, status, scope, plannedPaths); err != nil {
details.Action = ActionFailUnmanaged details.Action = ActionFailUnmanaged
details.Reason = err.Error() details.Reason = err.Error()
return details, fmt.Errorf("%s: %s", ActionFailUnmanaged, err) return details, fmt.Errorf("%s: %s", ActionFailUnmanaged, err)
} }
details.OtherOwnerOutputs = otherOwnerOutputs(status, scope) takenOverPaths := sharedRootOutputPathSet(details.TakenOverOwnerOutputs)
details.OtherOwnerOutputs = otherOwnerOutputsExcept(status, scope, takenOverPaths)
ownerOutputs := currentOwnerOutputs(status, scope) ownerOutputs := currentOwnerOutputs(status, scope)
planned := make(map[string]struct{}, len(plannedPaths)) planned := make(map[string]struct{}, len(plannedPaths))
for _, path := range plannedPaths { for _, path := range plannedPaths {
@@ -266,11 +306,11 @@ func planSharedRootOwner(ctx context.Context, req Request, status state.Destinat
if _, exists := planned[output.Path]; exists { if _, exists := planned[output.Path]; exists {
continue continue
} }
if action == ActionReplaceOlder && reconciliation.Mode == config.ReconciliationModeReplace { if details.Action == ActionReplaceTakeover || details.Action == ActionReplaceConflict || (isReconciliationReplacementAction(details.Action) && reconciliation.Mode == config.ReconciliationModeReplace) {
details.OwnerOutputsToDelete = append(details.OwnerOutputsToDelete, output) details.OwnerOutputsToDelete = append(details.OwnerOutputsToDelete, output)
continue continue
} }
if action == ActionReplaceOlder && reconciliation.Mode == config.ReconciliationModeMerge { if isReconciliationReplacementAction(details.Action) && reconciliation.Mode == config.ReconciliationModeMerge {
details.RetainedOwnerOutputs = append(details.RetainedOwnerOutputs, output) details.RetainedOwnerOutputs = append(details.RetainedOwnerOutputs, output)
} }
} }
@@ -280,7 +320,7 @@ func planSharedRootOwner(ctx context.Context, req Request, status state.Destinat
func isWriteAction(action Action) bool { func isWriteAction(action Action) bool {
switch action { switch action {
case ActionPublishNew, ActionReplaceOlder, ActionForceReplace: case ActionPublishNew, ActionReplaceOlder, ActionReplaceConflict, ActionReplaceNewer, ActionReplaceTakeover, ActionForceReplace:
return true return true
default: default:
return false return false
@@ -295,11 +335,76 @@ func outputPaths(outputs []Output) []string {
return paths return paths
} }
func sharedRootPathOwnershipConflict(status state.DestinationStatus, scope state.OwnerScope, paths []string) (state.PathOwnershipConflict, bool) { func sharedRootOwnershipConflictReason(conflict state.PathOwnershipConflict) string {
if status.SharedRoot != nil { return fmt.Sprintf("destination output path %s is owned by %s/%s", conflict.Path, conflict.Owner.PipelineID, conflict.Owner.DestinationID)
return status.SharedRoot.PathOwnershipConflict(scope, paths) }
func sharedRootPathOwnershipConflicts(status state.DestinationStatus, scope state.OwnerScope, paths []string) []state.PathOwnershipConflict {
if status.SharedRoot == nil {
return nil
}
conflicts := make([]state.PathOwnershipConflict, 0)
seen := make(map[string]struct{}, len(paths))
for _, path := range paths {
if _, exists := seen[path]; exists {
continue
}
seen[path] = struct{}{}
owner, exists := status.SharedRoot.OutputOwner(path)
if !exists || owner == scope {
continue
}
conflicts = append(conflicts, state.PathOwnershipConflict{
Path: path,
Owner: owner,
CurrentOwner: scope,
Detail: state.ComparisonDetail{
Kind: state.ComparisonDetailSharedRootOutputOwner,
Path: path,
CurrentOwner: scope,
ConflictingOwner: owner,
},
})
}
return conflicts
}
func sharedRootConflictOutputs(sharedRoot *state.SharedRootState, conflicts []state.PathOwnershipConflict) []state.SharedRootOutputFile {
if sharedRoot == nil || len(conflicts) == 0 {
return nil
}
paths := make(map[string]struct{}, len(conflicts))
for _, conflict := range conflicts {
paths[conflict.Path] = struct{}{}
}
outputs := make([]state.SharedRootOutputFile, 0, len(conflicts))
for _, output := range sharedRoot.Outputs {
if _, exists := paths[output.Path]; exists {
outputs = append(outputs, output)
}
}
return outputs
}
func sharedRootTakeoverAllowed(req Request, status state.DestinationStatus, conflict state.PathOwnershipConflict) bool {
if status.SharedRoot == nil {
return false
}
takeover := normalizeTakeover(req.Takeover)
switch takeover.Mode {
case config.TakeoverModeSamePipeline:
return conflict.Owner.PipelineID == req.PipelineID
case config.TakeoverModeSameSource:
owner, ok := status.SharedRoot.Owner(conflict.Owner)
return ok && owner.Source.Manifest.ID == req.SourceBundle.Manifest.ID
case config.TakeoverModeAnyManaged:
_, ok := status.SharedRoot.Owner(conflict.Owner)
return ok
case config.TakeoverModeNever:
return false
default:
return false
} }
return state.PathOwnershipConflict{}, false
} }
func rejectSharedRootUnmanagedCollisions(ctx context.Context, backend storage.Backend, bundlePath string, status state.DestinationStatus, scope state.OwnerScope, paths []string) error { func rejectSharedRootUnmanagedCollisions(ctx context.Context, backend storage.Backend, bundlePath string, status state.DestinationStatus, scope state.OwnerScope, paths []string) error {
@@ -333,18 +438,34 @@ func pathManagedBySharedRootStatus(status state.DestinationStatus, scope state.O
} }
func otherOwnerOutputs(status state.DestinationStatus, scope state.OwnerScope) []state.SharedRootOutputFile { func otherOwnerOutputs(status state.DestinationStatus, scope state.OwnerScope) []state.SharedRootOutputFile {
return otherOwnerOutputsExcept(status, scope, nil)
}
func otherOwnerOutputsExcept(status state.DestinationStatus, scope state.OwnerScope, exclude map[string]struct{}) []state.SharedRootOutputFile {
if status.SharedRoot == nil { if status.SharedRoot == nil {
return nil return nil
} }
outputs := make([]state.SharedRootOutputFile, 0, len(status.SharedRoot.Outputs)) outputs := make([]state.SharedRootOutputFile, 0, len(status.SharedRoot.Outputs))
for _, output := range status.SharedRoot.Outputs { for _, output := range status.SharedRoot.Outputs {
if output.Owner != scope { if output.Owner == scope {
continue
}
if _, skip := exclude[output.Path]; skip {
continue
}
outputs = append(outputs, output) outputs = append(outputs, output)
} }
}
return outputs return outputs
} }
func sharedRootOutputPathSet(outputs []state.SharedRootOutputFile) map[string]struct{} {
paths := make(map[string]struct{}, len(outputs))
for _, output := range outputs {
paths[output.Path] = struct{}{}
}
return paths
}
func currentOwnerOutputs(status state.DestinationStatus, scope state.OwnerScope) []state.SharedRootOutputFile { func currentOwnerOutputs(status state.DestinationStatus, scope state.OwnerScope) []state.SharedRootOutputFile {
if status.SharedRoot != nil { if status.SharedRoot != nil {
outputs := make([]state.SharedRootOutputFile, 0, len(status.SharedRoot.Outputs)) outputs := make([]state.SharedRootOutputFile, 0, len(status.SharedRoot.Outputs))
@@ -392,10 +513,7 @@ func actionForComparison(comparison state.Comparison, transfer config.TransferPo
return ActionFailConflict, comparison.Reason return ActionFailConflict, comparison.Reason
case state.OutcomeIdentityMismatch, state.OutcomeSameCreatedConflict, state.OutcomeDifferentSourceConflict: case state.OutcomeIdentityMismatch, state.OutcomeSameCreatedConflict, state.OutcomeDifferentSourceConflict:
if transfer.OnConflict == config.TransferActionReplace { if transfer.OnConflict == config.TransferActionReplace {
if force { return ActionReplaceConflict, comparison.Reason
return ActionForceReplace, "forced replacement of conflicting destination state: " + comparison.Reason
}
return ActionFailConflict, "destination conflict replacement requires --force"
} }
return ActionFailConflict, comparison.Reason return ActionFailConflict, comparison.Reason
case state.OutcomeSameSource: case state.OutcomeSameSource:
@@ -410,10 +528,7 @@ func actionForComparison(comparison state.Comparison, transfer config.TransferPo
return ActionReplaceOlder, comparison.Reason return ActionReplaceOlder, comparison.Reason
case state.OutcomeDestinationNewer: case state.OutcomeDestinationNewer:
if transfer.OnDestinationNewer == config.TransferActionReplace { if transfer.OnDestinationNewer == config.TransferActionReplace {
if force { return ActionReplaceNewer, comparison.Reason
return ActionForceReplace, "forced replacement of newer destination state"
}
return ActionFailConflict, "destination is newer and replacement requires --force"
} }
if transfer.OnDestinationNewer == config.TransferActionFail { if transfer.OnDestinationNewer == config.TransferActionFail {
return ActionFailConflict, "destination is newer and transfer policy requires failure" return ActionFailConflict, "destination is newer and transfer policy requires failure"
@@ -423,3 +538,36 @@ func actionForComparison(comparison state.Comparison, transfer config.TransferPo
return ActionFailConflict, "unsupported comparison outcome" return ActionFailConflict, "unsupported comparison outcome"
} }
} }
func isReconciliationReplacementAction(action Action) bool {
return action == ActionReplaceOlder || action == ActionReplaceNewer
}
func takeoverActionAllowed(req Request, status state.DestinationStatus, comparison state.Comparison, stateMode string, action Action) bool {
if stateMode != config.StateModeSingleOwner || status.State == nil {
return false
}
if action == ActionForceReplace {
return false
}
switch comparison.Detail.Kind {
case state.ComparisonDetailPipelineIDMismatch,
state.ComparisonDetailDestinationIDMismatch,
state.ComparisonDetailDifferentSourceID:
default:
return false
}
takeover := normalizeTakeover(req.Takeover)
switch takeover.Mode {
case config.TakeoverModeSamePipeline:
return status.State.PipelineID == req.PipelineID
case config.TakeoverModeSameSource:
return status.State.Source.Manifest.ID == req.SourceBundle.Manifest.ID
case config.TakeoverModeAnyManaged:
return true
case config.TakeoverModeNever:
return false
default:
return false
}
}

View File

@@ -0,0 +1,36 @@
package publish
import (
"testing"
"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/testutil"
)
func TestCompareDestinationFixedPathPreservesDifferentSourceConflict(t *testing.T) {
sourceBackend := fake.New()
sourceBundle := testutil.WriteFakeSourceBundle(t, sourceBackend, "bundle", testutil.BundleOptions{})
destinationState := testutil.DestinationState(sourceBundle.Manifest, testutil.DestinationStateOptions{})
destinationState.Source.Manifest.ID = "latest.previous"
comparison := compareDestination(Request{
PipelineID: "reports",
DestinationID: "archive",
SourceBundle: sourceBundle,
DestinationBundlePath: "",
PathMapping: config.PathMappingFixed,
State: config.StatePolicy{Mode: config.StateModeSingleOwner},
}, state.DestinationStatus{State: &destinationState, HasContents: true})
if comparison.Outcome != state.OutcomeDifferentSourceConflict {
t.Fatalf("comparison outcome = %s, want %s", comparison.Outcome, state.OutcomeDifferentSourceConflict)
}
if comparison.Detail.Kind != state.ComparisonDetailDifferentSourceID {
t.Fatalf("detail kind = %q, want %q", comparison.Detail.Kind, state.ComparisonDetailDifferentSourceID)
}
if comparison.Detail.CurrentSourceID != sourceBundle.Manifest.ID || comparison.Detail.DestinationSourceID != "latest.previous" {
t.Fatalf("detail = %#v, want source ids", comparison.Detail)
}
}

View File

@@ -113,6 +113,105 @@ func TestBuildSharedRootRejectsOtherOwnerPathConflict(t *testing.T) {
} }
} }
func TestBuildSharedRootPlansOutputTakeoverByPolicy(t *testing.T) {
tests := []struct {
name string
takeover config.TakeoverPolicy
transfer config.TransferPolicy
ownerScope state.OwnerScope
sameSource bool
wantAction Action
wantErr string
}{
{
name: "default same pipeline allows different destination",
takeover: config.TakeoverPolicy{},
ownerScope: state.CurrentOwnerScope("reports", "web"),
wantAction: ActionReplaceTakeover,
},
{
name: "same pipeline refuses different pipeline",
takeover: config.TakeoverPolicy{Mode: config.TakeoverModeSamePipeline},
ownerScope: state.CurrentOwnerScope("other", "archive"),
wantErr: "fail_conflict",
},
{
name: "same source allows different pipeline",
takeover: config.TakeoverPolicy{Mode: config.TakeoverModeSameSource},
ownerScope: state.CurrentOwnerScope("other", "archive"),
sameSource: true,
wantAction: ActionReplaceTakeover,
},
{
name: "same source refuses different source",
takeover: config.TakeoverPolicy{Mode: config.TakeoverModeSameSource},
ownerScope: state.CurrentOwnerScope("reports", "web"),
wantErr: "fail_conflict",
},
{
name: "any managed allows different pipeline",
takeover: config.TakeoverPolicy{Mode: config.TakeoverModeAnyManaged},
ownerScope: state.CurrentOwnerScope("other", "archive"),
wantAction: ActionReplaceTakeover,
},
{
name: "never refuses same pipeline",
takeover: config.TakeoverPolicy{Mode: config.TakeoverModeNever},
ownerScope: state.CurrentOwnerScope("reports", "web"),
wantErr: "fail_conflict",
},
{
name: "transfer conflict replacement allows managed owner conflict",
takeover: config.TakeoverPolicy{Mode: config.TakeoverModeNever},
transfer: config.TransferPolicy{OnConflict: config.TransferActionReplace},
ownerScope: state.CurrentOwnerScope("other", "archive"),
wantAction: ActionReplaceConflict,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
sourceBackend := fake.New()
sourceBundle := testutil.WriteFakeSourceBundle(t, sourceBackend, "bundle", testutil.BundleOptions{
Files: []testutil.SourceFile{{Path: "report.md", Data: "# Report\n"}},
})
destinationBackend := fake.New()
sharedRoot := sharedRootStateWithOwners(t, sourceBundle.Manifest, false)
ownerManifest := sharedRoot.Owners[0].Source.Manifest
if tt.sameSource {
ownerManifest = sourceBundle.Manifest
}
setSharedRootOwnerOutput(t, &sharedRoot, 0, tt.ownerScope, ownerManifest, "report.md")
writeFakeSharedRootState(t, destinationBackend, "bundle", sharedRoot)
req := sharedRootRequest(sourceBackend, destinationBackend, sourceBundle, config.ReconciliationModeReplace)
req.Takeover = tt.takeover
if tt.transfer.OnConflict != "" {
req.Transfer.OnConflict = tt.transfer.OnConflict
}
plan, err := Build(context.Background(), req)
if tt.wantErr != "" {
if err == nil || !strings.Contains(err.Error(), tt.wantErr) {
t.Fatalf("Build() error = %v, want %q", err, tt.wantErr)
}
if plan.Action != ActionFailConflict {
t.Fatalf("plan action = %s, want fail_conflict", plan.Action)
}
return
}
if err != nil {
t.Fatalf("Build() error = %v", err)
}
if plan.Action != tt.wantAction {
t.Fatalf("plan action = %s, want %s", plan.Action, tt.wantAction)
}
if got, want := sharedRootOutputPathList(plan.TakenOverOwnerOutputs), "report.md"; got != want {
t.Fatalf("taken over outputs = %q, want %q", got, want)
}
})
}
}
func TestBuildSharedRootRejectsUnmanagedPathCollision(t *testing.T) { func TestBuildSharedRootRejectsUnmanagedPathCollision(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{
@@ -203,6 +302,120 @@ func TestExecuteSharedRootReplaceDeletesOnlyCurrentOwnerOmittedOutputs(t *testin
} }
} }
func TestExecuteSharedRootTakeoverReassignsPathAndPreservesUnrelatedOutputs(t *testing.T) {
sourceBackend := fake.New()
sourceBundle := testutil.WriteFakeSourceBundle(t, sourceBackend, "bundle", testutil.BundleOptions{
Files: []testutil.SourceFile{{Path: "report.md", Data: "# Report\nNew.\n"}},
})
destinationBackend := fake.New()
sharedRoot := sharedRootStateWithOwners(t, sourceBundle.Manifest, false)
previousScope := state.CurrentOwnerScope("reports", "web")
setSharedRootOwnerOutput(t, &sharedRoot, 0, previousScope, sharedRoot.Owners[0].Source.Manifest, "report.md")
keepOutput := sharedRoot.Outputs[0]
keepOutput.Path = "web/keep.md"
keepOutput.SourcePath = "web/keep.md"
sharedRoot.Outputs = append(sharedRoot.Outputs, keepOutput)
writeFakeSharedRootState(t, destinationBackend, "bundle", sharedRoot)
req := sharedRootRequest(sourceBackend, destinationBackend, sourceBundle, config.ReconciliationModeReplace)
plan, err := Build(context.Background(), req)
if err != nil {
t.Fatalf("Build() error = %v", err)
}
if plan.Action != ActionReplaceTakeover {
t.Fatalf("plan action = %s, want %s", plan.Action, ActionReplaceTakeover)
}
if err := Execute(context.Background(), req, plan); err != nil {
t.Fatalf("Execute() error = %v", err)
}
testutil.AssertFakeFile(t, destinationBackend, "bundle/report.md", "# Report\nNew.\n")
testutil.AssertFakeFile(t, destinationBackend, "bundle/web/keep.md", "old")
destinationState := readFakeSharedRootState(t, destinationBackend, "bundle")
reportOutput, ok := findSharedRootOutputForTest(destinationState.Outputs, "report.md")
if !ok {
t.Fatal("report.md missing from shared-root outputs")
}
if reportOutput.Owner != state.CurrentOwnerScope("reports", "archive") {
t.Fatalf("report.md owner = %#v, want reports/archive", reportOutput.Owner)
}
keep, ok := findSharedRootOutputForTest(destinationState.Outputs, "web/keep.md")
if !ok {
t.Fatal("web/keep.md missing from shared-root outputs")
}
if keep.Owner != previousScope {
t.Fatalf("web/keep.md owner = %#v, want reports/web", keep.Owner)
}
}
func TestExecuteSharedRootTakeoverMergeDoesNotRetainOldSourceOutputs(t *testing.T) {
sourceBackend := fake.New()
sourceBundle := testutil.WriteFakeSourceBundle(t, sourceBackend, "bundle", testutil.BundleOptions{
Files: []testutil.SourceFile{{Path: "report.md", Data: "# Report\nNew.\n"}},
})
destinationBackend := fake.New()
sharedRoot := sharedRootStateWithOwners(t, sourceBundle.Manifest, false)
previousScope := state.CurrentOwnerScope("reports", "web")
setSharedRootOwnerOutput(t, &sharedRoot, 0, previousScope, sharedRoot.Owners[0].Source.Manifest, "report.md")
createdAt := sharedRoot.CreatedAt
oldManifest := sourceBundle.Manifest
oldManifest.ID = "old.source"
oldManifest.Created = oldManifest.Created.Add(-time.Hour)
oldManifest.Files = []bundle.ManifestFile{{
Path: "old.md",
SHA256: bundle.FileDigest([]byte("old\n")),
Size: int64(len("old\n")),
}}
oldManifest.Digest = bundle.BundleDigest(oldManifest.Files)
currentScope := state.CurrentOwnerScope("reports", "archive")
sharedRoot.Owners = append(sharedRoot.Owners, state.OwnerRecord{
Scope: currentScope,
Reconciliation: state.ReconciliationPolicy{Mode: config.ReconciliationModeMerge},
Source: state.SourceState{Manifest: oldManifest},
})
sharedRoot.Outputs = append(sharedRoot.Outputs, state.SharedRootOutputFile{
Path: "old.md",
Kind: state.OutputKindSource,
SourcePath: "old.md",
SHA256: oldManifest.Files[0].SHA256,
Size: oldManifest.Files[0].Size,
Owner: currentScope,
SourceID: oldManifest.ID,
SourceDigest: oldManifest.Digest,
SourceCreated: oldManifest.Created,
CreatedAt: createdAt,
UpdatedAt: createdAt,
})
writeFakeSharedRootState(t, destinationBackend, "bundle", sharedRoot)
req := sharedRootRequest(sourceBackend, destinationBackend, sourceBundle, config.ReconciliationModeMerge)
req.PathMapping = config.PathMappingFixed
plan, err := Build(context.Background(), req)
if err != nil {
t.Fatalf("Build() error = %v", err)
}
if plan.Action != ActionReplaceTakeover {
t.Fatalf("plan action = %s, want %s", plan.Action, ActionReplaceTakeover)
}
if got, want := sharedRootOutputPathList(plan.OwnerOutputsToDelete), "old.md"; got != want {
t.Fatalf("owner outputs to delete = %q, want %q", got, want)
}
if len(plan.RetainedOwnerOutputs) != 0 {
t.Fatalf("retained owner outputs = %#v, want none", plan.RetainedOwnerOutputs)
}
if err := Execute(context.Background(), req, plan); err != nil {
t.Fatalf("Execute() error = %v", err)
}
testutil.AssertFakeFile(t, destinationBackend, "bundle/report.md", "# Report\nNew.\n")
testutil.AssertFakeMissing(t, destinationBackend, "bundle/old.md")
destinationState := readFakeSharedRootState(t, destinationBackend, "bundle")
if got, want := strings.Join(destinationState.AllManagedOutputPaths(), ","), "report.md"; got != want {
t.Fatalf("managed paths = %q, want %q", got, want)
}
}
func TestExecuteSharedRootMergeRetainsCurrentOwnerOmittedOutputs(t *testing.T) { func TestExecuteSharedRootMergeRetainsCurrentOwnerOmittedOutputs(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{
@@ -322,6 +535,26 @@ func findSharedRootOutputForTest(outputs []state.SharedRootOutputFile, path stri
return state.SharedRootOutputFile{}, false return state.SharedRootOutputFile{}, false
} }
func setSharedRootOwnerOutput(t *testing.T, sharedRoot *state.SharedRootState, index int, scope state.OwnerScope, manifest bundle.Manifest, path string) {
t.Helper()
sharedRoot.Owners[index].Scope = scope
sharedRoot.Owners[index].Source = state.SourceState{Manifest: manifest}
sourcePath := path
if len(manifest.Files) > 0 {
sourcePath = manifest.Files[0].Path
}
sharedRoot.Outputs[index].Path = path
sharedRoot.Outputs[index].SourcePath = sourcePath
sharedRoot.Outputs[index].Owner = scope
sharedRoot.Outputs[index].SourceID = manifest.ID
sharedRoot.Outputs[index].SourceDigest = manifest.Digest
sharedRoot.Outputs[index].SourceCreated = manifest.Created
if len(manifest.Files) > 0 {
sharedRoot.Outputs[index].SHA256 = manifest.Files[0].SHA256
sharedRoot.Outputs[index].Size = manifest.Files[0].Size
}
}
func sharedRootStateWithOwners(t *testing.T, current bundle.Manifest, includeCurrent bool) state.SharedRootState { func sharedRootStateWithOwners(t *testing.T, current bundle.Manifest, includeCurrent bool) state.SharedRootState {
t.Helper() t.Helper()
createdAt := time.Date(2026, 5, 30, 11, 12, 0, 0, time.UTC) createdAt := time.Date(2026, 5, 30, 11, 12, 0, 0, time.UTC)

View File

@@ -0,0 +1,215 @@
package publish
import (
"context"
"strings"
"testing"
"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/fake"
"gitea.maximumdirect.net/eric/distributor/internal/testutil"
)
func TestBuildPlansSingleOwnerTakeoverByPolicy(t *testing.T) {
tests := []struct {
name string
takeover config.TakeoverPolicy
mutateState func(*bundle.Manifest, *testutil.DestinationStateOptions)
wantAction Action
wantErr string
}{
{
name: "default same pipeline different source",
takeover: config.TakeoverPolicy{},
mutateState: func(manifest *bundle.Manifest, opts *testutil.DestinationStateOptions) {
manifest.ID = "other.source"
},
wantAction: ActionReplaceTakeover,
},
{
name: "same pipeline different newer source",
takeover: config.TakeoverPolicy{Mode: config.TakeoverModeSamePipeline},
mutateState: func(manifest *bundle.Manifest, opts *testutil.DestinationStateOptions) {
manifest.ID = "other.source"
manifest.Created = manifest.Created.AddDate(0, 0, 1)
},
wantAction: ActionReplaceTakeover,
},
{
name: "default same pipeline different destination",
takeover: config.TakeoverPolicy{},
mutateState: func(manifest *bundle.Manifest, opts *testutil.DestinationStateOptions) {
opts.DestinationID = "web"
},
wantAction: ActionReplaceTakeover,
},
{
name: "same pipeline refuses different pipeline",
takeover: config.TakeoverPolicy{Mode: config.TakeoverModeSamePipeline},
mutateState: func(manifest *bundle.Manifest, opts *testutil.DestinationStateOptions) {
opts.PipelineID = "other"
},
wantErr: "fail_conflict",
},
{
name: "same source allows different pipeline",
takeover: config.TakeoverPolicy{Mode: config.TakeoverModeSameSource},
mutateState: func(manifest *bundle.Manifest, opts *testutil.DestinationStateOptions) {
opts.PipelineID = "other"
},
wantAction: ActionReplaceTakeover,
},
{
name: "same source refuses different source",
takeover: config.TakeoverPolicy{Mode: config.TakeoverModeSameSource},
mutateState: func(manifest *bundle.Manifest, opts *testutil.DestinationStateOptions) {
manifest.ID = "other.source"
},
wantErr: "fail_conflict",
},
{
name: "any managed allows different pipeline",
takeover: config.TakeoverPolicy{Mode: config.TakeoverModeAnyManaged},
mutateState: func(manifest *bundle.Manifest, opts *testutil.DestinationStateOptions) {
manifest.ID = "other.source"
opts.PipelineID = "other"
},
wantAction: ActionReplaceTakeover,
},
{
name: "never refuses different source",
takeover: config.TakeoverPolicy{Mode: config.TakeoverModeNever},
mutateState: func(manifest *bundle.Manifest, opts *testutil.DestinationStateOptions) {
manifest.ID = "other.source"
},
wantErr: "fail_conflict",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
sourceBackend := fake.New()
sourceBundle := testutil.WriteFakeSourceBundle(t, sourceBackend, "bundle", testutil.BundleOptions{})
destinationBackend := fake.New()
destinationManifest := sourceBundle.Manifest
destinationManifest.Files = append([]bundle.ManifestFile(nil), sourceBundle.Manifest.Files...)
opts := testutil.DestinationStateOptions{}
tt.mutateState(&destinationManifest, &opts)
testutil.WriteFakeDestinationState(t, destinationBackend, "bundle", destinationManifest, opts)
req := takeoverRequest(sourceBackend, destinationBackend, sourceBundle, tt.takeover, config.ReconciliationModeReplace)
plan, err := Build(context.Background(), req)
if tt.wantErr != "" {
if err == nil || !strings.Contains(err.Error(), tt.wantErr) {
t.Fatalf("Build() error = %v, want %q", err, tt.wantErr)
}
return
}
if err != nil {
t.Fatalf("Build() error = %v", err)
}
if plan.Action != tt.wantAction {
t.Fatalf("plan action = %s, want %s", plan.Action, tt.wantAction)
}
})
}
}
func TestBuildDoesNotTakeOverInvalidOrUnmanagedDestination(t *testing.T) {
tests := []struct {
name string
prepare func(t *testing.T, backend *fake.Backend)
wantErr string
}{
{
name: "invalid state",
prepare: func(t *testing.T, backend *fake.Backend) {
t.Helper()
statePath, err := storage.StatePath("bundle")
if err != nil {
t.Fatalf("state path: %v", err)
}
testutil.WriteFakeFile(t, backend, statePath, "{invalid")
},
wantErr: "fail_conflict",
},
{
name: "unmanaged content",
prepare: func(t *testing.T, backend *fake.Backend) {
t.Helper()
testutil.WriteFakeFile(t, backend, "bundle/old.txt", "old")
},
wantErr: "fail_unmanaged",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
sourceBackend := fake.New()
sourceBundle := testutil.WriteFakeSourceBundle(t, sourceBackend, "bundle", testutil.BundleOptions{})
destinationBackend := fake.New()
tt.prepare(t, destinationBackend)
req := takeoverRequest(sourceBackend, destinationBackend, sourceBundle, config.TakeoverPolicy{Mode: config.TakeoverModeAnyManaged}, config.ReconciliationModeReplace)
_, err := Build(context.Background(), req)
if err == nil || !strings.Contains(err.Error(), tt.wantErr) {
t.Fatalf("Build() error = %v, want %q", err, tt.wantErr)
}
})
}
}
func TestExecuteTakeoverMergeDoesNotRetainOldSourceOutputs(t *testing.T) {
sourceBackend := fake.New()
sourceBundle := testutil.WriteFakeSourceBundle(t, sourceBackend, "bundle", testutil.BundleOptions{
Files: []testutil.SourceFile{{Path: "report.md", Data: "# Report\nNew.\n"}},
})
destinationBackend := fake.New()
oldManifest := sourceBundle.Manifest
oldManifest.ID = "old.source"
oldManifest.Files = []bundle.ManifestFile{
{Path: "report.md", SHA256: bundle.FileDigest([]byte("old\n")), Size: int64(len("old\n"))},
{Path: "summary.txt", SHA256: bundle.FileDigest([]byte("old summary\n")), Size: int64(len("old summary\n"))},
}
oldManifest.Digest = bundle.BundleDigest(oldManifest.Files)
testutil.WriteFakeDestinationState(t, destinationBackend, "bundle", oldManifest, testutil.DestinationStateOptions{})
req := takeoverRequest(sourceBackend, destinationBackend, sourceBundle, config.TakeoverPolicy{Mode: config.TakeoverModeSamePipeline}, config.ReconciliationModeMerge)
plan, err := Build(context.Background(), req)
if err != nil {
t.Fatalf("Build() error = %v", err)
}
if plan.Action != ActionReplaceTakeover {
t.Fatalf("plan action = %s, want %s", plan.Action, ActionReplaceTakeover)
}
if err := Execute(context.Background(), req, plan); err != nil {
t.Fatalf("Execute() error = %v", err)
}
testutil.AssertFakeFile(t, destinationBackend, "bundle/report.md", "# Report\nNew.\n")
testutil.AssertFakeMissing(t, destinationBackend, "bundle/summary.txt")
destinationState := readFakeState(t, destinationBackend, "bundle")
if got, want := len(destinationState.Outputs), 1; got != want {
t.Fatalf("state output count = %d, want %d", got, want)
}
if got, want := destinationState.Source.Manifest.ID, sourceBundle.Manifest.ID; got != want {
t.Fatalf("state source id = %q, want %q", got, want)
}
}
func takeoverRequest(sourceBackend, destinationBackend *fake.Backend, sourceBundle bundle.Bundle, takeover config.TakeoverPolicy, reconciliationMode string) Request {
return Request{
PipelineID: "reports",
DestinationID: "archive",
SourceBundle: sourceBundle,
SourceBackend: sourceBackend,
DestinationBackend: destinationBackend,
DestinationBundlePath: sourceBundle.RootRelativePath,
Publish: config.PublishPolicy{Source: true},
Reconciliation: config.ReconciliationPolicy{Mode: reconciliationMode},
Takeover: takeover,
Transfer: defaultTransfer(),
DistributorVersion: "test",
}
}

View File

@@ -30,37 +30,75 @@ type DestinationStatus struct {
type Comparison struct { type Comparison struct {
Outcome Outcome Outcome Outcome
Reason string Reason string
Detail ComparisonDetail
}
type ComparisonDetailKind string
const (
ComparisonDetailNone ComparisonDetailKind = ""
ComparisonDetailInvalidState ComparisonDetailKind = "invalid_state"
ComparisonDetailUnmanagedContent ComparisonDetailKind = "unmanaged_content"
ComparisonDetailPipelineIDMismatch ComparisonDetailKind = "pipeline_id_mismatch"
ComparisonDetailDestinationIDMismatch ComparisonDetailKind = "destination_id_mismatch"
ComparisonDetailDifferentSourceID ComparisonDetailKind = "different_source_id"
ComparisonDetailSameCreatedDigestConflict ComparisonDetailKind = "same_created_digest_conflict"
ComparisonDetailDestinationNewer ComparisonDetailKind = "destination_newer"
ComparisonDetailSharedRootOwnerAbsent ComparisonDetailKind = "shared_root_owner_absent"
ComparisonDetailSharedRootOutputOwner ComparisonDetailKind = "shared_root_output_owner_conflict"
)
type ComparisonDetail struct {
Kind ComparisonDetailKind
CurrentPipelineID string
CurrentDestinationID string
DestinationPipelineID string
DestinationDestinationID string
CurrentSourceID string
DestinationSourceID string
CurrentSourceDigest string
DestinationSourceDigest string
Path string
CurrentOwner OwnerScope
ConflictingOwner OwnerScope
} }
func CompareSharedRootOwner(source bundle.Manifest, scope OwnerScope, status DestinationStatus) Comparison { func CompareSharedRootOwner(source bundle.Manifest, scope OwnerScope, status DestinationStatus) Comparison {
if status.StateErr != nil { if status.StateErr != nil {
return Comparison{Outcome: OutcomeInvalidState, Reason: status.StateErr.Error()} return Comparison{Outcome: OutcomeInvalidState, Reason: status.StateErr.Error(), Detail: ComparisonDetail{Kind: ComparisonDetailInvalidState}}
} }
if status.SharedRoot != nil { if status.SharedRoot != nil {
if err := ValidateSharedRoot(*status.SharedRoot); err != nil { if err := ValidateSharedRoot(*status.SharedRoot); err != nil {
return Comparison{Outcome: OutcomeInvalidState, Reason: err.Error()} return Comparison{Outcome: OutcomeInvalidState, Reason: err.Error(), Detail: ComparisonDetail{Kind: ComparisonDetailInvalidState}}
} }
owner, ok := status.SharedRoot.Owner(scope) owner, ok := status.SharedRoot.Owner(scope)
if !ok { if !ok {
return Comparison{Outcome: OutcomeDestinationAbsent, Reason: fmt.Sprintf("destination owner %s/%s is absent", scope.PipelineID, scope.DestinationID)} return Comparison{
Outcome: OutcomeDestinationAbsent,
Reason: fmt.Sprintf("destination owner %s/%s is absent", scope.PipelineID, scope.DestinationID),
Detail: ComparisonDetail{
Kind: ComparisonDetailSharedRootOwnerAbsent,
CurrentOwner: scope,
},
}
} }
return compareManifests(source, owner.Source.Manifest) return compareManifests(source, owner.Source.Manifest)
} }
if status.State != nil { if status.State != nil {
destinationState := *status.State destinationState := *status.State
if err := Validate(destinationState); err != nil { if err := Validate(destinationState); err != nil {
return Comparison{Outcome: OutcomeInvalidState, Reason: err.Error()} return Comparison{Outcome: OutcomeInvalidState, Reason: err.Error(), Detail: ComparisonDetail{Kind: ComparisonDetailInvalidState}}
} }
if destinationState.PipelineID != scope.PipelineID { if destinationState.PipelineID != scope.PipelineID {
return Comparison{Outcome: OutcomeIdentityMismatch, Reason: fmt.Sprintf("pipeline id %q does not match %q", destinationState.PipelineID, scope.PipelineID)} return pipelineIDMismatchComparison(destinationState.PipelineID, scope.PipelineID)
} }
if destinationState.DestinationID != scope.DestinationID { if destinationState.DestinationID != scope.DestinationID {
return Comparison{Outcome: OutcomeIdentityMismatch, Reason: fmt.Sprintf("destination id %q does not match %q", destinationState.DestinationID, scope.DestinationID)} return destinationIDMismatchComparison(destinationState.DestinationID, scope.DestinationID)
} }
return compareManifests(source, destinationState.Source.Manifest) return compareManifests(source, destinationState.Source.Manifest)
} }
if status.HasContents { if status.HasContents {
return Comparison{Outcome: OutcomeDestinationUnmanaged, Reason: "destination has content but no distributor state"} return Comparison{Outcome: OutcomeDestinationUnmanaged, Reason: "destination has content but no distributor state", Detail: ComparisonDetail{Kind: ComparisonDetailUnmanagedContent}}
} }
return Comparison{Outcome: OutcomeDestinationAbsent, Reason: "destination state is absent"} return Comparison{Outcome: OutcomeDestinationAbsent, Reason: "destination state is absent"}
} }
@@ -70,45 +108,95 @@ func compareManifests(source, destination bundle.Manifest) Comparison {
return Comparison{Outcome: OutcomeSameSource, Reason: "destination source manifest matches source"} return Comparison{Outcome: OutcomeSameSource, Reason: "destination source manifest matches source"}
} }
if destination.ID != source.ID { if destination.ID != source.ID {
return Comparison{Outcome: OutcomeDifferentSourceConflict, Reason: "destination source id differs from source"} return Comparison{
Outcome: OutcomeDifferentSourceConflict,
Reason: "destination source id differs from source",
Detail: ComparisonDetail{
Kind: ComparisonDetailDifferentSourceID,
CurrentSourceID: source.ID,
DestinationSourceID: destination.ID,
},
}
} }
if destination.Created.Before(source.Created) { if destination.Created.Before(source.Created) {
return Comparison{Outcome: OutcomeDestinationOlder, Reason: "destination source is older than source"} return Comparison{Outcome: OutcomeDestinationOlder, Reason: "destination source is older than source"}
} }
if destination.Created.After(source.Created) { if destination.Created.After(source.Created) {
return Comparison{Outcome: OutcomeDestinationNewer, Reason: "destination source is newer than source"} return Comparison{
Outcome: OutcomeDestinationNewer,
Reason: "destination source is newer than source",
Detail: ComparisonDetail{
Kind: ComparisonDetailDestinationNewer,
CurrentSourceID: source.ID,
DestinationSourceID: destination.ID,
},
}
} }
if destination.Digest != source.Digest { if destination.Digest != source.Digest {
return Comparison{Outcome: OutcomeSameCreatedConflict, Reason: "destination source has same id and created time but different digest"} return Comparison{
Outcome: OutcomeSameCreatedConflict,
Reason: "destination source has same id and created time but different digest",
Detail: ComparisonDetail{
Kind: ComparisonDetailSameCreatedDigestConflict,
CurrentSourceID: source.ID,
DestinationSourceID: destination.ID,
CurrentSourceDigest: source.Digest,
DestinationSourceDigest: destination.Digest,
},
} }
return Comparison{Outcome: OutcomeInvalidState, Reason: "destination source differs from source without a supported comparison outcome"} }
return Comparison{Outcome: OutcomeInvalidState, Reason: "destination source differs from source without a supported comparison outcome", Detail: ComparisonDetail{Kind: ComparisonDetailInvalidState}}
} }
func Compare(source bundle.Manifest, pipelineID, destinationID string, status DestinationStatus) Comparison { func Compare(source bundle.Manifest, pipelineID, destinationID string, status DestinationStatus) Comparison {
if status.StateErr != nil { if status.StateErr != nil {
return Comparison{Outcome: OutcomeInvalidState, Reason: status.StateErr.Error()} return Comparison{Outcome: OutcomeInvalidState, Reason: status.StateErr.Error(), Detail: ComparisonDetail{Kind: ComparisonDetailInvalidState}}
} }
if status.State == nil { if status.State == nil {
if status.HasContents { if status.HasContents {
return Comparison{Outcome: OutcomeDestinationUnmanaged, Reason: "destination has content but no distributor state"} return Comparison{Outcome: OutcomeDestinationUnmanaged, Reason: "destination has content but no distributor state", Detail: ComparisonDetail{Kind: ComparisonDetailUnmanagedContent}}
} }
return Comparison{Outcome: OutcomeDestinationAbsent, Reason: "destination state is absent"} return Comparison{Outcome: OutcomeDestinationAbsent, Reason: "destination state is absent"}
} }
destinationState := *status.State destinationState := *status.State
if err := Validate(destinationState); err != nil { if err := Validate(destinationState); err != nil {
return Comparison{Outcome: OutcomeInvalidState, Reason: err.Error()} return Comparison{Outcome: OutcomeInvalidState, Reason: err.Error(), Detail: ComparisonDetail{Kind: ComparisonDetailInvalidState}}
} }
if destinationState.PipelineID != pipelineID { if destinationState.PipelineID != pipelineID {
return Comparison{Outcome: OutcomeIdentityMismatch, Reason: fmt.Sprintf("pipeline id %q does not match %q", destinationState.PipelineID, pipelineID)} return pipelineIDMismatchComparison(destinationState.PipelineID, pipelineID)
} }
if destinationState.DestinationID != destinationID { if destinationState.DestinationID != destinationID {
return Comparison{Outcome: OutcomeIdentityMismatch, Reason: fmt.Sprintf("destination id %q does not match %q", destinationState.DestinationID, destinationID)} return destinationIDMismatchComparison(destinationState.DestinationID, destinationID)
} }
return compareManifests(source, destinationState.Source.Manifest) return compareManifests(source, destinationState.Source.Manifest)
} }
func pipelineIDMismatchComparison(destinationPipelineID, currentPipelineID string) Comparison {
return Comparison{
Outcome: OutcomeIdentityMismatch,
Reason: fmt.Sprintf("pipeline id %q does not match %q", destinationPipelineID, currentPipelineID),
Detail: ComparisonDetail{
Kind: ComparisonDetailPipelineIDMismatch,
CurrentPipelineID: currentPipelineID,
DestinationPipelineID: destinationPipelineID,
},
}
}
func destinationIDMismatchComparison(destinationDestinationID, currentDestinationID string) Comparison {
return Comparison{
Outcome: OutcomeIdentityMismatch,
Reason: fmt.Sprintf("destination id %q does not match %q", destinationDestinationID, currentDestinationID),
Detail: ComparisonDetail{
Kind: ComparisonDetailDestinationIDMismatch,
CurrentDestinationID: currentDestinationID,
DestinationDestinationID: destinationDestinationID,
},
}
}
func manifestsEqual(a, b bundle.Manifest) bool { func manifestsEqual(a, b bundle.Manifest) bool {
if a.SchemaVersion != b.SchemaVersion || if a.SchemaVersion != b.SchemaVersion ||
a.ID != b.ID || a.ID != b.ID ||

View File

@@ -97,6 +97,93 @@ func TestCompareOutcomes(t *testing.T) {
} }
} }
func TestCompareReportsStructuredDetails(t *testing.T) {
source := validManifest(t)
tests := []struct {
name string
status DestinationStatus
wantKind ComparisonDetailKind
assertions func(t *testing.T, detail ComparisonDetail)
}{
{
name: "pipeline mismatch",
status: DestinationStatus{State: withState(t, source, func(s *DistributorState) { s.PipelineID = "other" })},
wantKind: ComparisonDetailPipelineIDMismatch,
assertions: func(t *testing.T, detail ComparisonDetail) {
t.Helper()
if detail.DestinationPipelineID != "other" || detail.CurrentPipelineID != "reports" {
t.Fatalf("detail = %#v, want pipeline ids", detail)
}
},
},
{
name: "destination mismatch",
status: DestinationStatus{State: withState(t, source, func(s *DistributorState) { s.DestinationID = "other" })},
wantKind: ComparisonDetailDestinationIDMismatch,
assertions: func(t *testing.T, detail ComparisonDetail) {
t.Helper()
if detail.DestinationDestinationID != "other" || detail.CurrentDestinationID != "archive" {
t.Fatalf("detail = %#v, want destination ids", detail)
}
},
},
{
name: "different source id",
status: DestinationStatus{State: withState(t, source, func(s *DistributorState) { s.Source.Manifest.ID = "other.source" })},
wantKind: ComparisonDetailDifferentSourceID,
assertions: func(t *testing.T, detail ComparisonDetail) {
t.Helper()
if detail.DestinationSourceID != "other.source" || detail.CurrentSourceID != source.ID {
t.Fatalf("detail = %#v, want source ids", detail)
}
},
},
{
name: "same created digest conflict",
status: DestinationStatus{State: withState(t, source, func(s *DistributorState) {
s.Source.Manifest.Files[0].SHA256 = "sha256:3333333333333333333333333333333333333333333333333333333333333333"
s.Source.Manifest.Digest = bundle.BundleDigest(s.Source.Manifest.Files)
})},
wantKind: ComparisonDetailSameCreatedDigestConflict,
assertions: func(t *testing.T, detail ComparisonDetail) {
t.Helper()
if detail.CurrentSourceDigest == "" || detail.DestinationSourceDigest == "" || detail.CurrentSourceDigest == detail.DestinationSourceDigest {
t.Fatalf("detail = %#v, want different source digests", detail)
}
},
},
{
name: "destination newer",
status: DestinationStatus{State: withState(t, source, func(s *DistributorState) {
s.Source.Manifest.Created = source.Created.Add(time.Hour)
})},
wantKind: ComparisonDetailDestinationNewer,
},
{
name: "invalid state",
status: DestinationStatus{StateErr: errors.New("invalid json")},
wantKind: ComparisonDetailInvalidState,
},
{
name: "unmanaged content",
status: DestinationStatus{HasContents: true},
wantKind: ComparisonDetailUnmanagedContent,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := Compare(source, "reports", "archive", tt.status)
if got.Detail.Kind != tt.wantKind {
t.Fatalf("Compare() detail kind = %q, want %q; comparison=%#v", got.Detail.Kind, tt.wantKind, got)
}
if tt.assertions != nil {
tt.assertions(t, got.Detail)
}
})
}
}
func withState(t *testing.T, source bundle.Manifest, mutate func(*DistributorState)) *DistributorState { func withState(t *testing.T, source bundle.Manifest, mutate func(*DistributorState)) *DistributorState {
t.Helper() t.Helper()
stateManifest := source stateManifest := source

View File

@@ -191,7 +191,17 @@ func (s SharedRootState) PathOwnershipConflict(scope OwnerScope, paths []string)
for _, path := range paths { for _, path := range paths {
owner, exists := s.OutputOwner(path) owner, exists := s.OutputOwner(path)
if exists && owner != scope { if exists && owner != scope {
return PathOwnershipConflict{Path: path, Owner: owner}, true return PathOwnershipConflict{
Path: path,
Owner: owner,
CurrentOwner: scope,
Detail: ComparisonDetail{
Kind: ComparisonDetailSharedRootOutputOwner,
Path: path,
CurrentOwner: scope,
ConflictingOwner: owner,
},
}, true
} }
} }
return PathOwnershipConflict{}, false return PathOwnershipConflict{}, false

View File

@@ -59,6 +59,8 @@ type SharedRootOutputFile struct {
type PathOwnershipConflict struct { type PathOwnershipConflict struct {
Path string Path string
Owner OwnerScope Owner OwnerScope
CurrentOwner OwnerScope
Detail ComparisonDetail
} }
type rawSharedRootState struct { type rawSharedRootState struct {

View File

@@ -130,6 +130,12 @@ func TestSharedRootOutputHelpers(t *testing.T) {
if !ok || conflict.Owner != html { if !ok || conflict.Owner != html {
t.Fatalf("conflict = %#v ok=%t, want html owner conflict", conflict, ok) t.Fatalf("conflict = %#v ok=%t, want html owner conflict", conflict, ok)
} }
if conflict.Detail.Kind != ComparisonDetailSharedRootOutputOwner {
t.Fatalf("conflict detail kind = %q, want %q", conflict.Detail.Kind, ComparisonDetailSharedRootOutputOwner)
}
if conflict.Detail.Path != "report.html" || conflict.Detail.CurrentOwner != archive || conflict.Detail.ConflictingOwner != html {
t.Fatalf("conflict detail = %#v, want path and owners", conflict.Detail)
}
} }
func TestRemoveMissingSharedRootOwnerOutputs(t *testing.T) { func TestRemoveMissingSharedRootOwnerOutputs(t *testing.T) {
@@ -241,6 +247,12 @@ func TestCompareSharedRootOwnerScopesCurrentOwner(t *testing.T) {
if missing.Outcome != OutcomeDestinationAbsent { if missing.Outcome != OutcomeDestinationAbsent {
t.Fatalf("missing owner comparison = %#v, want destination absent", missing) t.Fatalf("missing owner comparison = %#v, want destination absent", missing)
} }
if missing.Detail.Kind != ComparisonDetailSharedRootOwnerAbsent {
t.Fatalf("missing owner detail kind = %q, want %q", missing.Detail.Kind, ComparisonDetailSharedRootOwnerAbsent)
}
if missing.Detail.CurrentOwner != CurrentOwnerScope("missing", "archive") {
t.Fatalf("missing owner detail = %#v, want missing/archive", missing.Detail)
}
} }
func TestCompareSharedRootOwnerAcceptsMatchingSingleOwnerState(t *testing.T) { func TestCompareSharedRootOwnerAcceptsMatchingSingleOwnerState(t *testing.T) {

View File

@@ -123,7 +123,7 @@ func (t *Transformer) render(ctx context.Context, req transform.Request, sourceF
if err := t.renderer.Convert(data, &rendered); err != nil { if err := t.renderer.Convert(data, &rendered); err != nil {
return nil, fmt.Errorf("render markdown source %q: %w", sourceFile, err) return nil, fmt.Errorf("render markdown source %q: %w", sourceFile, err)
} }
return wrapHTML(rendered.Bytes()), nil return wrapHTML(rendered.Bytes(), req.Markdown.CssHref), nil
} }
func markdownMode(mode string) string { func markdownMode(mode string) string {

View File

@@ -40,6 +40,43 @@ func TestGenerateMarkdownSidecar(t *testing.T) {
} }
} }
func TestGenerateMarkdownWithoutCSSHrefPreservesWrapper(t *testing.T) {
backend, sourceBundle := markdownFixture(t, "# Title\n\nHello.\n")
outputs, err := New().Generate(context.Background(), transform.Request{SourceBackend: backend, SourceBundle: sourceBundle})
if err != nil {
t.Fatalf("Generate() error = %v", err)
}
want := "<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<title></title>\n</head>\n<body>\n<h1>Title</h1>\n<p>Hello.</p>\n</body>\n</html>\n"
if got := string(outputs[0].Data); got != want {
t.Fatalf("html = %q, want existing wrapper %q", got, want)
}
}
func TestGenerateMarkdownSidecarWithCSSHref(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{CssHref: "/assets/report.css?v=1&theme=main"},
})
if err != nil {
t.Fatalf("Generate() error = %v", err)
}
output := outputs[0]
html := string(output.Data)
wantLink := "<meta charset=\"utf-8\">\n<link rel=\"stylesheet\" href=\"/assets/report.css?v=1&amp;theme=main\">\n<title></title>"
if !strings.Contains(html, wantLink) {
t.Fatalf("html = %q, want stylesheet link %q", html, wantLink)
}
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 TestGenerateMarkdownIndexExplicitInput(t *testing.T) { func TestGenerateMarkdownIndexExplicitInput(t *testing.T) {
backend := fake.New() backend := fake.New()
sourceBundle := testutil.WriteFakeSourceBundle(t, backend, "", testutil.BundleOptions{ sourceBundle := testutil.WriteFakeSourceBundle(t, backend, "", testutil.BundleOptions{
@@ -74,6 +111,29 @@ func TestGenerateMarkdownIndexExplicitInput(t *testing.T) {
} }
} }
func TestGenerateMarkdownIndexWithCSSHref(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,
CssHref: "https://example.com/assets/report.css",
},
})
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 !strings.Contains(string(outputs[0].Data), `<link rel="stylesheet" href="https://example.com/assets/report.css">`) {
t.Fatalf("html = %q, want stylesheet link", outputs[0].Data)
}
}
func TestGenerateMarkdownIndexSelectsOnlyMarkdownFile(t *testing.T) { func TestGenerateMarkdownIndexSelectsOnlyMarkdownFile(t *testing.T) {
backend, sourceBundle := markdownFixture(t, "# Title\n\nHello.\n") backend, sourceBundle := markdownFixture(t, "# Title\n\nHello.\n")

View File

@@ -1,10 +1,19 @@
package markdown package markdown
import "bytes" import (
"bytes"
"html"
)
func wrapHTML(body []byte) []byte { func wrapHTML(body []byte, cssHref string) []byte {
var buf bytes.Buffer var buf bytes.Buffer
buf.WriteString("<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<title></title>\n</head>\n<body>\n") buf.WriteString("<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n")
if cssHref != "" {
buf.WriteString("<link rel=\"stylesheet\" href=\"")
buf.WriteString(html.EscapeString(cssHref))
buf.WriteString("\">\n")
}
buf.WriteString("<title></title>\n</head>\n<body>\n")
buf.Write(body) buf.Write(body)
buf.WriteString("</body>\n</html>\n") buf.WriteString("</body>\n</html>\n")
return buf.Bytes() return buf.Bytes()

View File

@@ -25,6 +25,7 @@ type Request struct {
type MarkdownOptions struct { type MarkdownOptions struct {
Mode string Mode string
Input string Input string
CssHref string
} }
type Transformer interface { type Transformer interface {