feat: add obipipeline crate with typed multi-threaded pipelines
Release / release (push) Successful in 1m12s
Release / release (push) Successful in 1m12s
Introduce the `obipipeline` crate, providing typed, composable multi-threaded pipelines with memory-bounded throttling. The crate includes a scheduler for managing pipeline stages, a throttle mechanism for concurrency control, and comprehensive build and release tooling via `.crate-kit`. - Add `Cargo.toml`, `Cargo.lock`, and `Makefile` to define the `obipipeline` package (v0.1.1) with `crossbeam-channel` dependency and build targets. - Add `LICENSE` and `LICENSE.en` files containing the CeCILL free software license agreement under French law. - Add `.gitignore` to exclude `target` and `/.cargo/config.toml` from version control. - Add `.crate-kit/` directory with build configuration (`VERSION`, `crate.mk`, `org.mk`, `dev-patch.mk`, `jj.mk`) and 21 shell scripts for API tracking, dependency management, release workflows, and wiki generation. - Add `.gitea/workflows/release.yaml` to automate releases on tag pushes, including building, publishing, and updating the wiki. - Add `src/lib.rs` to expose `scheduler` and `throttle` modules, re-exporting core types like `Pipe`, `Pipeline`, `WorkerPool`, and `Throttle`. - Add `src/scheduler/` module with `error.rs` (`PipelineError`), `macros.rs` (`make_pipe!`, `make_pipeline!`), `pipe.rs` (`Pipe`, `PipeIter`), `pool.rs` (`Pipeline`, `WorkerPool`), `runner.rs` (thread runners), and `types.rs` (`Stage`, `WorkerTask`, function aliases). - Add `src/throttle.rs` implementing `Throttle`, `ThrottleGuard`, and `throttle` function for memory-bounded concurrency control using semaphores. - Add `api/` directory with public API snapshots (`0.1.0`, `0.1.1`) in JSON, text, and stamp formats for version tracking. - Add `examples/sandbox_pipeline.rs` demonstrating pipeline construction with `make_pipeline!` and `WorkerPool` using sample transformation steps. - Add `tests/pipe.rs` with tests for pipe composition, flat transforms, and empty input handling. - Add `tests/throttle.rs` with tests verifying throttle ordering, concurrency bounds, and guard blocking behavior. - Update `README.md` with documentation for `obipipeline`, including core concepts, API details, and installation instructions.
This commit is contained in:
1 parent
873f7f7f24
commit
e14fb6a287
54 files changed
+4763
No files matched your search
@@ -0,0 +1 @@
|
|||||||
|
0.3.7+0.1.1
|
||||||
@@ -0,0 +1,240 @@
|
|||||||
|
# crate-kit: common targets for the crates of a multi-crate Rust project.
|
||||||
|
#
|
||||||
|
# This directory (.crate-kit/) is a COPY of the kit/ folder of the crate-kit repository: do not
|
||||||
|
# modify it here, fix it in crate-kit then run `make kit-update`.
|
||||||
|
#
|
||||||
|
# Usage, in the crate's Makefile:
|
||||||
|
# RELEASE_PROJECT_DESC = acmexxx (short description) # optional
|
||||||
|
# include .crate-kit/crate.mk
|
||||||
|
#
|
||||||
|
# Adjustable variables (before the include or on the command line):
|
||||||
|
# CARGO, CARGO_TOML, FEATURES, API_DIR, RELEASE_NOTES_DIR, REGISTRY, KIT_SRC
|
||||||
|
# KIT_LANG language of LLM-generated documents (default en; any language name or ISO code)
|
||||||
|
# RELEASE=x.y.z forces the version of bump-version / jjrelease
|
||||||
|
# DRY_RUN=1 publish: checks the package without sending it
|
||||||
|
#
|
||||||
|
# Crate kind: CRATE_KIND (default "crate"). kinds/<kind>.mk sets, before the targets, the generic variables
|
||||||
|
# that the kit reads: BUILD_TARGET (--target of the builds), EXTRA_TARGETS (targets that check and clippy
|
||||||
|
# go through in addition to the host), PUBLISH, API_TRACKED, WIKI (yes|no: publication to the registry,
|
||||||
|
# API snapshot and version verdict, wiki), AFTER_RELEASE (command run after the tag). A kind
|
||||||
|
# can also add its own targets. Kinds specific to an organization come from its overlay (org.mk
|
||||||
|
# sets REGISTRY and REGISTRY_INDEX); see tools/kit-assemble.sh.
|
||||||
|
|
||||||
|
KIT_DIR := $(patsubst %/,%,$(dir $(lastword $(MAKEFILE_LIST))))
|
||||||
|
KIT_SRC ?= ../crate-kit
|
||||||
|
|
||||||
|
CARGO ?= cargo
|
||||||
|
CARGO_TOML ?= Cargo.toml
|
||||||
|
FEATURES ?=
|
||||||
|
API_DIR ?= api
|
||||||
|
RELEASE_NOTES_DIR ?= ReleaseNotes
|
||||||
|
CRATE_KIND ?= crate
|
||||||
|
BUILD_TARGET ?=
|
||||||
|
PUBLISH ?= yes
|
||||||
|
API_TRACKED ?= yes
|
||||||
|
WIKI ?= yes
|
||||||
|
AFTER_RELEASE ?=
|
||||||
|
# Additional targets that check and clippy go through (e.g. EXTRA_TARGETS = wasm32-unknown-unknown).
|
||||||
|
EXTRA_TARGETS ?=
|
||||||
|
RELEASE_PROJECT_DESC ?= $(shell sed -n 's/^name = "\(.*\)"/\1/p' $(CARGO_TOML) | head -n 1)
|
||||||
|
|
||||||
|
|
||||||
|
GREEN = \033[0;32m
|
||||||
|
YELLOW = \033[1;33m
|
||||||
|
BLUE = \033[1;34m
|
||||||
|
NC = \033[0m
|
||||||
|
|
||||||
|
include $(KIT_DIR)/dev-patch.mk
|
||||||
|
include $(KIT_DIR)/jj.mk
|
||||||
|
|
||||||
|
# Language of the documents an LLM generates (release notes). Default English; an extension kit
|
||||||
|
# overrides it in its org.mk (KIT_LANG ?= fr), included above, or the user on the command line.
|
||||||
|
KIT_LANG ?= en
|
||||||
|
# Language of the commit messages written by `jj auto-doc` (pmojj reads PMOJJ_LANG).
|
||||||
|
export PMOJJ_LANG = $(KIT_LANG)
|
||||||
|
|
||||||
|
ifeq ($(wildcard $(KIT_DIR)/kinds/$(CRATE_KIND).mk),)
|
||||||
|
$(error unknown crate kind: CRATE_KIND = $(CRATE_KIND) (kinds: $(patsubst $(KIT_DIR)/kinds/%.mk,%,$(wildcard $(KIT_DIR)/kinds/*.mk))))
|
||||||
|
endif
|
||||||
|
include $(KIT_DIR)/kinds/$(CRATE_KIND).mk
|
||||||
|
export KIT_LANG CARGO CARGO_TOML API_DIR RELEASE_NOTES_DIR REGISTRY RELEASE_PROJECT_DESC KIT_SRC CRATE_KIND PUBLISH API_TRACKED WIKI
|
||||||
|
|
||||||
|
.DEFAULT_GOAL := build
|
||||||
|
|
||||||
|
.PHONY: help build release debug test test-doc doc doc-build clean check fmt fmt-check clippy \
|
||||||
|
watch ci deps update bench coverage bump-version api-level api-snapshot publish wiki \
|
||||||
|
jjnew jjpush jjfetch jjrelease bookmark-check kit-check needs-commit kit-update kit-version
|
||||||
|
|
||||||
|
help:
|
||||||
|
@echo "$(GREEN)Available commands:$(NC)"
|
||||||
|
@sed -n "s/^## *\([^:]*\): */\1$$(printf '\t')/p" $(MAKEFILE_LIST) | column -t -s "$$(printf '\t')" | sed -e 's/^/ /'
|
||||||
|
|
||||||
|
## build: Release build (alias of release)
|
||||||
|
build: release
|
||||||
|
|
||||||
|
## release: Release build (the kind's BUILD_TARGET, if it sets one)
|
||||||
|
release:
|
||||||
|
@echo "$(YELLOW)→ Building (release)...$(NC)"
|
||||||
|
$(CARGO) build --release $(if $(BUILD_TARGET),--target $(BUILD_TARGET)) $(FEATURES)
|
||||||
|
@echo "$(GREEN)✓ Build finished$(NC)"
|
||||||
|
|
||||||
|
## debug: Debug build (the kind's BUILD_TARGET, if it sets one)
|
||||||
|
debug:
|
||||||
|
@echo "$(YELLOW)→ Building (debug)...$(NC)"
|
||||||
|
$(CARGO) build $(if $(BUILD_TARGET),--target $(BUILD_TARGET)) $(FEATURES)
|
||||||
|
@echo "$(GREEN)✓ Build finished$(NC)"
|
||||||
|
|
||||||
|
## test: All tests
|
||||||
|
test:
|
||||||
|
@echo "$(YELLOW)→ Running the tests...$(NC)"
|
||||||
|
$(CARGO) test --all --all-features
|
||||||
|
@echo "$(GREEN)✓ Tests finished$(NC)"
|
||||||
|
|
||||||
|
## test-doc: Documentation example tests
|
||||||
|
test-doc:
|
||||||
|
@echo "$(YELLOW)→ Testing the documentation examples...$(NC)"
|
||||||
|
$(CARGO) test --doc --all-features
|
||||||
|
@echo "$(GREEN)✓ Documentation tests finished$(NC)"
|
||||||
|
|
||||||
|
## doc: Generates the documentation and opens it
|
||||||
|
doc:
|
||||||
|
@echo "$(YELLOW)→ Generating the documentation...$(NC)"
|
||||||
|
$(CARGO) doc --no-deps --document-private-items --all-features --open
|
||||||
|
|
||||||
|
## doc-build: Generates the documentation without opening it
|
||||||
|
doc-build:
|
||||||
|
@echo "$(YELLOW)→ Generating the documentation...$(NC)"
|
||||||
|
$(CARGO) doc --no-deps --document-private-items --all-features
|
||||||
|
|
||||||
|
## clean: Cleanup
|
||||||
|
clean:
|
||||||
|
@echo "$(YELLOW)→ Cleaning...$(NC)"
|
||||||
|
$(CARGO) clean
|
||||||
|
|
||||||
|
## check: Code check (host, then EXTRA_TARGETS)
|
||||||
|
check:
|
||||||
|
@$(KIT_DIR)/scripts/publish-guard.sh
|
||||||
|
@echo "$(YELLOW)→ Checking the code...$(NC)"
|
||||||
|
$(CARGO) check --all
|
||||||
|
@for t in $(EXTRA_TARGETS); do $(CARGO) check --all --target $$t || exit 1; done
|
||||||
|
@echo "$(GREEN)✓ Code valid$(NC)"
|
||||||
|
|
||||||
|
## fmt: Code formatting
|
||||||
|
fmt:
|
||||||
|
$(CARGO) fmt --all
|
||||||
|
|
||||||
|
## fmt-check: Formatting check
|
||||||
|
fmt-check:
|
||||||
|
$(CARGO) fmt --all -- --check
|
||||||
|
|
||||||
|
## clippy: Static analysis on the host then EXTRA_TARGETS (warnings = errors)
|
||||||
|
clippy:
|
||||||
|
@echo "$(YELLOW)→ Analysing with clippy...$(NC)"
|
||||||
|
$(CARGO) clippy --all-targets --all-features -- -D warnings
|
||||||
|
@for t in $(EXTRA_TARGETS); do $(CARGO) clippy --lib --all-features --target $$t -- -D warnings || exit 1; done
|
||||||
|
@echo "$(GREEN)✓ Clippy analysis finished$(NC)"
|
||||||
|
|
||||||
|
## watch: Continuous check
|
||||||
|
watch:
|
||||||
|
$(CARGO) watch -x check
|
||||||
|
|
||||||
|
## ci: Verification pipeline (deps-check fmt-check clippy test doc-build)
|
||||||
|
ci: deps-check fmt-check clippy test doc-build
|
||||||
|
@echo "$(GREEN)✓ All CI checks passed$(NC)"
|
||||||
|
|
||||||
|
## deps: Outdated dependencies
|
||||||
|
deps:
|
||||||
|
$(CARGO) outdated
|
||||||
|
|
||||||
|
## update: Updates the dependencies
|
||||||
|
update:
|
||||||
|
$(CARGO) update
|
||||||
|
|
||||||
|
## bench: Benchmarks
|
||||||
|
bench:
|
||||||
|
$(CARGO) bench
|
||||||
|
|
||||||
|
## coverage: Coverage report (cargo-llvm-cov)
|
||||||
|
coverage:
|
||||||
|
@echo "$(YELLOW)→ Generating the coverage report...$(NC)"
|
||||||
|
@mkdir -p target/coverage
|
||||||
|
$(CARGO) llvm-cov --json --output-path target/coverage/llvm-cov-report.json
|
||||||
|
$(CARGO) llvm-cov report
|
||||||
|
@echo "$(GREEN)✓ Report: target/coverage/llvm-cov-report.json$(NC)"
|
||||||
|
|
||||||
|
## api-level: Compares the public API to the last snapshot (initial, unchanged, additive or breaking)
|
||||||
|
api-level:
|
||||||
|
@$(KIT_DIR)/scripts/api-level.sh
|
||||||
|
|
||||||
|
## api-snapshot: Records the public API of the current version (api/<version>.txt and .json.gz)
|
||||||
|
api-snapshot:
|
||||||
|
@$(KIT_DIR)/scripts/api-snapshot.sh
|
||||||
|
|
||||||
|
## bump-version: Next version according to the API (breaking: x.y+1.0 in 0.x), or fixed RELEASE=x.y.z
|
||||||
|
bump-version:
|
||||||
|
@$(KIT_DIR)/scripts/bump-version.sh
|
||||||
|
|
||||||
|
## publish: Publishes to the $(REGISTRY) registry (done by the CI after the tag; manual troubleshooting, DRY_RUN=1: without sending)
|
||||||
|
publish:
|
||||||
|
@$(KIT_DIR)/scripts/publish.sh
|
||||||
|
|
||||||
|
## wiki: Publishes the API doc to the wiki (done by the CI after the tag; manual troubleshooting, DRY_RUN=1: without push)
|
||||||
|
wiki:
|
||||||
|
@$(KIT_DIR)/scripts/wiki.sh
|
||||||
|
|
||||||
|
## jjpush: Version bump, API snapshot, documentation, then main advances to the commit and is pushed
|
||||||
|
jjpush: bookmark-check deps-check bump-version api-snapshot
|
||||||
|
@echo "$(YELLOW)→ Pushing the commit to main...$(NC)"
|
||||||
|
@jj auto-doc
|
||||||
|
@$(KIT_DIR)/scripts/push-main.sh
|
||||||
|
@$(KIT_DIR)/scripts/new-commit.sh
|
||||||
|
@echo "$(GREEN)✓ main pushed; new working commit created on top of it$(NC)"
|
||||||
|
|
||||||
|
## jjrelease: Release (ci, version according to the API, snapshot, notes, push of main, tag; the CI then publishes)
|
||||||
|
jjrelease: bookmark-check kit-check ci bump-version api-snapshot
|
||||||
|
@echo "$(BLUE)→ Documenting the undocumented commits...$(NC)"
|
||||||
|
@jj auto-doc
|
||||||
|
@echo "$(BLUE)→ Synchronizing the tags with the remote repository...$(NC)"
|
||||||
|
@jj git fetch
|
||||||
|
@$(KIT_DIR)/scripts/release-notes.sh
|
||||||
|
@echo "$(BLUE)→ Documenting the current commit...$(NC)"
|
||||||
|
@jj auto-doc
|
||||||
|
@echo "$(BLUE)→ Pushing main...$(NC)"
|
||||||
|
@$(KIT_DIR)/scripts/push-main.sh
|
||||||
|
@$(KIT_DIR)/scripts/tag.sh
|
||||||
|
@$(KIT_DIR)/scripts/new-commit.sh
|
||||||
|
@echo "$(GREEN)✓ Tag pushed: the CI (Release workflow) publishes the crate, updates the wiki and creates the release$(NC)"
|
||||||
|
ifneq ($(strip $(AFTER_RELEASE)),)
|
||||||
|
@echo "$(BLUE)→ After the release: $(AFTER_RELEASE)$(NC)"
|
||||||
|
@$(AFTER_RELEASE)
|
||||||
|
endif
|
||||||
|
@name=$$(sed -n 's/^name = "\(.*\)"/\1/p' $(CARGO_TOML) | head -n 1); \
|
||||||
|
v=$$(sed -n 's/^version = "\(.*\)"/\1/p' $(CARGO_TOML) | head -n 1); \
|
||||||
|
case "$$v" in 0.*) req=$$(echo "$$v" | cut -d. -f1,2);; *) req=$$(echo "$$v" | cut -d. -f1);; esac; \
|
||||||
|
echo "$(YELLOW)⚠ Dependent projects: the requirement must accept $$v. If it does not, the local [patch] is ignored: raise it in their Cargo.toml $$name = { version = \"$$req\", registry = \"$(REGISTRY)\" } then cargo update -p $$name$(NC)"
|
||||||
|
|
||||||
|
## bookmark-check: Does main track main@origin? Otherwise the push of main would fail at the end of the release (read-only)
|
||||||
|
bookmark-check:
|
||||||
|
@$(KIT_DIR)/scripts/bookmark-check.sh
|
||||||
|
|
||||||
|
## kit-check: Is this crate's kit and release workflow identical to crate-kit's? (read-only)
|
||||||
|
kit-check:
|
||||||
|
@$(KIT_DIR)/scripts/kit-check.sh
|
||||||
|
|
||||||
|
## needs-commit: Are there changes other than the kit's to commit? (read-only, code 1 if not)
|
||||||
|
needs-commit:
|
||||||
|
@$(KIT_DIR)/scripts/needs-commit.sh
|
||||||
|
|
||||||
|
## kit-update: Updates .crate-kit/ from the extension kit (KIT_SRC)
|
||||||
|
kit-update:
|
||||||
|
@test -x "$(KIT_SRC)/tools/kit-copy.sh" || { echo "crate-kit not found: $(KIT_SRC) (set KIT_SRC=...)"; exit 1; }
|
||||||
|
@"$(KIT_SRC)/tools/kit-copy.sh" $(KIT_DIR)
|
||||||
|
@echo "$(GREEN)✓ .crate-kit/ up to date: crate-kit $$(cat $(KIT_DIR)/VERSION)$(NC)"
|
||||||
|
|
||||||
|
## print-%: Value of a make variable (e.g. make print-PUBLISH); for the tools
|
||||||
|
print-%:
|
||||||
|
@echo '$($*)'
|
||||||
|
|
||||||
|
## kit-version: Kit version installed in this crate
|
||||||
|
kit-version:
|
||||||
|
@cat $(KIT_DIR)/VERSION
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
# Private registry and local Cargo configuration (joint development).
|
||||||
|
# Fragment included by crate.mk and by the Makefiles that are not crates (workspace):
|
||||||
|
# include .crate-kit/dev-patch.mk
|
||||||
|
|
||||||
|
DEVPATCH_DIR := $(patsubst %/,%,$(dir $(lastword $(MAKEFILE_LIST))))
|
||||||
|
CARGO_TOML ?= Cargo.toml
|
||||||
|
|
||||||
|
# Values specific to the organization (REGISTRY, REGISTRY_INDEX, FORGE_URL…): org.mk, provided by the
|
||||||
|
# extension that the crate declares (KIT_OVERLAY, tools/kit-assemble.sh). REGISTRY = crates-io: crates.io, without
|
||||||
|
# index or [patch]. Without org.mk, no registry: publish and deps-check fail saying so.
|
||||||
|
-include $(DEVPATCH_DIR)/org.mk
|
||||||
|
REGISTRY ?=
|
||||||
|
REGISTRY_INDEX ?=
|
||||||
|
# MEMBERS_DIR: folder of the workspace when it is not the project root (e.g. src): its Cargo.toml and its
|
||||||
|
# members are scanned by dev-patch and deps-check, in addition to the root ones.
|
||||||
|
MEMBERS_DIR ?=
|
||||||
|
export CARGO_TOML MEMBERS_DIR REGISTRY REGISTRY_INDEX FORGE_TOKEN_FILE
|
||||||
|
|
||||||
|
# Private registry: the index comes from the environment, never from a file tracked by the repository (CI,
|
||||||
|
# Docker and a repository cloned alone therefore work without configuration).
|
||||||
|
ifneq ($(filter-out crates-io,$(strip $(REGISTRY))),)
|
||||||
|
REGISTRY_UP := $(shell echo '$(REGISTRY)' | tr 'a-z-' 'A-Z_')
|
||||||
|
CARGO_REGISTRIES_$(REGISTRY_UP)_INDEX := $(REGISTRY_INDEX)
|
||||||
|
export CARGO_REGISTRIES_$(REGISTRY_UP)_INDEX
|
||||||
|
endif
|
||||||
|
|
||||||
|
# Joint development: .cargo/config.toml (local, ignored) is regenerated at EVERY invocation of
|
||||||
|
# make, whatever the target, from the project's actual dependencies. Nothing to remember.
|
||||||
|
DEV_PATCH_RUN := $(shell CARGO_TOML='$(CARGO_TOML)' MEMBERS_DIR='$(MEMBERS_DIR)' REGISTRY='$(REGISTRY)' REGISTRY_INDEX='$(REGISTRY_INDEX)' $(DEVPATCH_DIR)/scripts/dev-patch.sh)
|
||||||
|
|
||||||
|
.PHONY: dev-patch
|
||||||
|
## dev-patch: Regenerates .cargo/config.toml (registry + local patches); already done at every make
|
||||||
|
dev-patch:
|
||||||
|
@$(DEVPATCH_DIR)/scripts/dev-patch.sh
|
||||||
|
@echo "ok: .cargo/config.toml up to date"
|
||||||
|
|
||||||
|
.PHONY: deps-check deps-bump
|
||||||
|
## deps-check: Dependencies up to date? from the private registry (requirement, lock, neighbour, duplicates) and external (requirement, minor, lock)
|
||||||
|
deps-check:
|
||||||
|
@rc=0; $(DEVPATCH_DIR)/scripts/deps-check.sh || rc=1; $(DEVPATCH_DIR)/scripts/deps-check-external.sh || rc=1; exit $$rc
|
||||||
|
|
||||||
|
## deps-bump: Raises the outdated requirements (private registry and external) to the latest version, then cargo update -p
|
||||||
|
deps-bump:
|
||||||
|
@$(DEVPATCH_DIR)/scripts/deps-check.sh bump
|
||||||
|
@$(DEVPATCH_DIR)/scripts/deps-check-external.sh bump
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
# Jujutsu targets common to all the crates and to crate-kit itself.
|
||||||
|
# Included by crate.mk; a repository that is not a crate includes it directly.
|
||||||
|
|
||||||
|
JJ_KIT_DIR := $(patsubst %/,%,$(dir $(lastword $(MAKEFILE_LIST))))
|
||||||
|
GREEN ?= \033[0;32m
|
||||||
|
YELLOW ?= \033[1;33m
|
||||||
|
BLUE ?= \033[1;34m
|
||||||
|
NC ?= \033[0m
|
||||||
|
|
||||||
|
## jjnew: Documents the current commit then creates a new one
|
||||||
|
jjnew:
|
||||||
|
@echo "$(YELLOW)→ Creating a new commit...$(NC)"
|
||||||
|
@jj auto-doc
|
||||||
|
@$(JJ_KIT_DIR)/scripts/new-commit.sh
|
||||||
|
@echo "$(GREEN)✓ Done$(NC)"
|
||||||
|
|
||||||
|
## jjfetch: Fetches the origin and rebases the local work on top of main@origin (nothing is lost)
|
||||||
|
jjfetch:
|
||||||
|
@$(JJ_KIT_DIR)/scripts/jjfetch.sh
|
||||||
|
@# Reruns make to resynchronize .crate-kit/: the Makefile does it at startup, before the rebase, and
|
||||||
|
@# the rebase may have left conflict markers there (kit copy newer than the origin's).
|
||||||
|
@$(MAKE) --no-print-directory -s help >/dev/null
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
# "crate" kind (default): ordinary Rust crate, published to the private registry, API tracked, wiki.
|
||||||
|
# The default values of BUILD_TARGET, EXTRA_TARGETS, PUBLISH, API_TRACKED, WIKI and AFTER_RELEASE
|
||||||
|
# (crate.mk) describe this kind: nothing to set here.
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
# Values specific to obi, read by dev-patch.mk (hence by every Makefile of the cluster) and by crate-kit.
|
||||||
|
# The cargo registry to publish to (a private name, or crates-io) and the forge hosting it.
|
||||||
|
REGISTRY ?= obi
|
||||||
|
FORGE_URL ?= https://forge.metabarcoding.org
|
||||||
|
REGISTRY_INDEX ?= sparse+$(FORGE_URL)/api/packages/$(REGISTRY)/cargo/
|
||||||
|
# No token here: the forge tokens of a workstation are files of the cluster, in secrets/ next to the
|
||||||
|
# repositories (secrets/forge.metabarcoding.org.token, ...), outside every repository. FORGETOKEN (CI) overrides them.
|
||||||
|
# Language of the documents an LLM generates (release notes, commit messages, Claude agents' notes).
|
||||||
|
KIT_LANG ?= en
|
||||||
Executable
+96
@@ -0,0 +1,96 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Compares the current public API to the last snapshot and prints on standard output:
|
||||||
|
# initial no snapshot: first tracked version
|
||||||
|
# unchanged no change in the public API
|
||||||
|
# additive additions only (nothing removed or modified)
|
||||||
|
# breaking break: element removed/modified, or break seen by cargo-semver-checks
|
||||||
|
# All the detail goes to standard error.
|
||||||
|
#
|
||||||
|
# Two combined checks: cargo-semver-checks is the reference for breaks, but it does not
|
||||||
|
# report plain additions; the text diff of cargo public-api acts as a safety net (any removed
|
||||||
|
# or modified line = break) and provides the count of additions.
|
||||||
|
set -euo pipefail
|
||||||
|
. "$(dirname "$0")/common.sh"
|
||||||
|
|
||||||
|
if [ "${API_TRACKED:-yes}" = no ]; then
|
||||||
|
echo unchanged # no tracked Rust API: the version advances by patch (or RELEASE=x.y.z)
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
require_cargo_tool public-api cargo-public-api
|
||||||
|
require_cargo_tool semver-checks cargo-semver-checks
|
||||||
|
|
||||||
|
# A proc-macro crate has no library target: cargo-semver-checks cannot analyse it.
|
||||||
|
# Its API (the exported macros) is still tracked by the text diff of cargo public-api; this diff does
|
||||||
|
# not see a change in the macro's behaviour (rejected inputs, generated code): to be judged by hand.
|
||||||
|
is_proc_macro() {
|
||||||
|
"$CARGO" metadata --format-version 1 --no-deps | grep -q '"kind":\["proc-macro"\]'
|
||||||
|
}
|
||||||
|
|
||||||
|
last=$(latest_snapshot)
|
||||||
|
if [ -z "$last" ]; then
|
||||||
|
info " No snapshot in $API_DIR/: first tracked version"
|
||||||
|
echo initial
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
# A snapshot written with other tools (rustc, cargo-public-api) than today's is no longer
|
||||||
|
# comparable: cargo-semver-checks crashes on another rustdoc format, and the text diff sees
|
||||||
|
# breaks where only the rendering changed. It is regenerated from the tag of its version (no stamp =
|
||||||
|
# written before stamps existed, hence unknown).
|
||||||
|
if [ "$(cat "$API_DIR/$last.stamp" 2>/dev/null || true)" != "$(toolchain_stamp)" ]; then
|
||||||
|
info " Snapshot $last written with other tools: regenerating from tag version-$last"
|
||||||
|
regenerate_snapshot "$last" || {
|
||||||
|
err "✗ cannot regenerate snapshot $last: the comparison would be wrong"
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
fi
|
||||||
|
|
||||||
|
tmp=$(mktemp -d)
|
||||||
|
trap 'rm -r "$tmp"' EXIT
|
||||||
|
info " Reference: API published in version $last"
|
||||||
|
|
||||||
|
"$CARGO" public-api -s >"$tmp/current.txt" 2>/dev/null || {
|
||||||
|
err "✗ cargo public-api failed"
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
# `filter_unstable` (common.sh) removes from the cargo public-api text whatever is not the crate's API.
|
||||||
|
diff_out=$(diff <(filter_unstable "$API_DIR/$last.txt") <(filter_unstable "$tmp/current.txt") || true)
|
||||||
|
removed=$(printf '%s\n' "$diff_out" | grep -c '^<' || true)
|
||||||
|
added=$(printf '%s\n' "$diff_out" | grep -c '^>' || true)
|
||||||
|
|
||||||
|
# Code 100 = break; 0 = nothing to report; other = tool failure.
|
||||||
|
set +e
|
||||||
|
if is_proc_macro; then
|
||||||
|
info " proc-macro crate: cargo-semver-checks not applicable, text diff only"
|
||||||
|
rc=0
|
||||||
|
else
|
||||||
|
gzip -d -c "$API_DIR/$last.json.gz" >"$tmp/baseline.json"
|
||||||
|
"$CARGO" semver-checks --baseline-rustdoc "$tmp/baseline.json" --release-type minor >"$tmp/semver.log" 2>&1
|
||||||
|
rc=$?
|
||||||
|
fi
|
||||||
|
set -e
|
||||||
|
|
||||||
|
level=unchanged
|
||||||
|
if [ "$rc" -eq 100 ]; then
|
||||||
|
level=breaking
|
||||||
|
warn " Break detected by cargo-semver-checks:"
|
||||||
|
grep -E '^ +[A-Za-z0-9_]+::|^--- failure' "$tmp/semver.log" >&2 || true
|
||||||
|
elif [ "$rc" -ne 0 ]; then
|
||||||
|
err "✗ cargo-semver-checks failed (code $rc):"
|
||||||
|
tail -n 15 "$tmp/semver.log" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ "$removed" -gt 0 ]; then
|
||||||
|
level=breaking
|
||||||
|
warn " $removed API line(s) removed or modified compared to $last:"
|
||||||
|
printf '%s\n' "$diff_out" | grep '^<' >&2
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ "$level" = unchanged ] && [ "$added" -gt 0 ]; then
|
||||||
|
level=additive
|
||||||
|
fi
|
||||||
|
|
||||||
|
info " API: +$added / -$removed lines; verdict: $level"
|
||||||
|
echo "$level"
|
||||||
Executable
+20
@@ -0,0 +1,20 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Records the public API of the current version:
|
||||||
|
# $API_DIR/<version>.txt readable, diffable list (cargo public-api)
|
||||||
|
# $API_DIR/<version>.json.gz compressed rustdoc JSON, reference of cargo-semver-checks
|
||||||
|
# $API_DIR/<version>.stamp rustc and cargo-public-api used (api-level regenerates if they change)
|
||||||
|
set -euo pipefail
|
||||||
|
. "$(dirname "$0")/common.sh"
|
||||||
|
|
||||||
|
if [ "${API_TRACKED:-yes}" = no ]; then
|
||||||
|
info " (kind ${CRATE_KIND:-crate}: no Rust API to record)"
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
require_cargo_tool public-api cargo-public-api
|
||||||
|
|
||||||
|
version=$(current_version)
|
||||||
|
name=$(crate_name)
|
||||||
|
warn "→ Public API snapshot of $name $version..."
|
||||||
|
emit_snapshot "$version" "$API_DIR"
|
||||||
|
ok "✓ $API_DIR/$version.txt and $API_DIR/$version.json.gz written"
|
||||||
Executable
+14
@@ -0,0 +1,14 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Checks that the local `main` bookmark tracks `main@origin` (read-only). Without this tracking, jj refuses
|
||||||
|
# to push main ("Non-tracking remote bookmark"), and jjrelease would fail at the very end,
|
||||||
|
# after the tests and the version bump: this check detects it beforehand.
|
||||||
|
# Without a jj repository, without a `main` bookmark or without `main@origin`, there is nothing to check: success.
|
||||||
|
set -euo pipefail
|
||||||
|
. "$(dirname "$0")/common.sh"
|
||||||
|
|
||||||
|
rows=$(jj bookmark list main --all-remotes -T 'remote ++ "|" ++ tracked ++ "\n"' 2>/dev/null) || exit 0
|
||||||
|
if printf '%s\n' "$rows" | grep -qx 'origin|false'; then
|
||||||
|
err "✗ main@origin exists but the local main bookmark does not track it: the push of main would be refused"
|
||||||
|
info " Fix once and for all: jj bookmark track main@origin"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
Executable
+67
@@ -0,0 +1,67 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Computes and applies the next version according to the public API (see api-level.sh):
|
||||||
|
# break -> x.y+1.0 while x = 0, otherwise x+1.0.0
|
||||||
|
# additions -> x.y+1.0 once x >= 1 (SemVer: new feature), x.y.z+1 while x = 0
|
||||||
|
# otherwise -> x.y.z+1
|
||||||
|
# RELEASE=x.y.z forces the version. Updates Cargo.toml, version.txt and the
|
||||||
|
# dependency line `<crate> = "x.y"` of README.md when they exist.
|
||||||
|
set -euo pipefail
|
||||||
|
. "$(dirname "$0")/common.sh"
|
||||||
|
|
||||||
|
warn "→ Computing the next version..."
|
||||||
|
current=$(current_version)
|
||||||
|
name=$(crate_name)
|
||||||
|
info " Current version: $current"
|
||||||
|
IFS=. read -r major minor patch <<<"$current"
|
||||||
|
|
||||||
|
if [ -n "${RELEASE:-}" ]; then
|
||||||
|
new_version="$RELEASE"
|
||||||
|
else
|
||||||
|
level=$("$(dirname "$0")/api-level.sh")
|
||||||
|
case "$level" in
|
||||||
|
breaking)
|
||||||
|
if [ "$major" = "0" ]; then
|
||||||
|
new_version="0.$((minor + 1)).0"
|
||||||
|
else
|
||||||
|
new_version="$((major + 1)).0.0"
|
||||||
|
fi
|
||||||
|
;;
|
||||||
|
additive)
|
||||||
|
if [ "$major" = "0" ]; then
|
||||||
|
new_version="0.$minor.$((patch + 1))"
|
||||||
|
else
|
||||||
|
new_version="$major.$((minor + 1)).0"
|
||||||
|
fi
|
||||||
|
;;
|
||||||
|
initial | unchanged)
|
||||||
|
new_version="$major.$minor.$((patch + 1))"
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
err "✗ unexpected API verdict: '$level'"
|
||||||
|
exit 1
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
fi
|
||||||
|
|
||||||
|
# No silent jump to another version: a break must never be downgraded.
|
||||||
|
rc=0
|
||||||
|
"$(dirname "$0")/tag-exists.sh" "$new_version" || rc=$?
|
||||||
|
case "$rc" in
|
||||||
|
0)
|
||||||
|
err "✗ The release version-$new_version already exists (locally or on the server)"
|
||||||
|
info " Use RELEASE=x.y.z to force another version"
|
||||||
|
exit 1
|
||||||
|
;;
|
||||||
|
1) ;;
|
||||||
|
*) warn " (remote tags not checked: no jj repository or origin unreachable)" ;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
info " New version: $new_version"
|
||||||
|
sed -i.bak "s/^version = \"$current\"/version = \"$new_version\"/" "$CARGO_TOML"
|
||||||
|
rm "$CARGO_TOML.bak"
|
||||||
|
[ -f version.txt ] && echo "$new_version" >version.txt
|
||||||
|
if [ -f README.md ]; then
|
||||||
|
sed -i.bak "s/^$name = \"[0-9][0-9.]*\"/$name = \"$(echo "$new_version" | cut -d. -f1,2)\"/" README.md
|
||||||
|
rm README.md.bak
|
||||||
|
fi
|
||||||
|
ok "✓ Version $new_version written to $CARGO_TOML (and version.txt, README.md if they exist)"
|
||||||
Executable
+266
@@ -0,0 +1,266 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Functions shared by the kit scripts. To be sourced: `. "$(dirname "$0")/common.sh"`.
|
||||||
|
#
|
||||||
|
# Parameters read from the environment (default values below); crate.mk exports
|
||||||
|
# them, the scripts also remain usable on their own from the root of a crate.
|
||||||
|
|
||||||
|
CARGO="${CARGO:-cargo}"
|
||||||
|
CARGO_TOML="${CARGO_TOML:-Cargo.toml}"
|
||||||
|
API_DIR="${API_DIR:-api}"
|
||||||
|
RELEASE_NOTES_DIR="${RELEASE_NOTES_DIR:-ReleaseNotes}"
|
||||||
|
# Private cargo registry and its sparse index: provided by the organisation overlay (org.mk), empty otherwise.
|
||||||
|
REGISTRY="${REGISTRY:-}"
|
||||||
|
REGISTRY_INDEX="${REGISTRY_INDEX:-}"
|
||||||
|
|
||||||
|
info() { printf '\033[1;34m%s\033[0m\n' "$*" >&2; }
|
||||||
|
warn() { printf '\033[1;33m%s\033[0m\n' "$*" >&2; }
|
||||||
|
ok() { printf '\033[0;32m%s\033[0m\n' "$*" >&2; }
|
||||||
|
err() { printf '\033[0;31m%s\033[0m\n' "$*" >&2; }
|
||||||
|
|
||||||
|
# API call: `forge_call <operation> <curl args…>`. Returns the response body on standard output;
|
||||||
|
# on an HTTP response ≥ 400 (or a transport failure), states the operation, the code and the body on standard
|
||||||
|
# error and returns 1. Replaces `curl -sf`, which fails silently (code 22).
|
||||||
|
forge_call() {
|
||||||
|
local operation="$1" body code
|
||||||
|
shift
|
||||||
|
body=$(mktemp)
|
||||||
|
code=$(curl -s -o "$body" -w '%{http_code}' "$@") || code="000"
|
||||||
|
if [ "$code" -ge 400 ] || [ "$code" = "000" ]; then
|
||||||
|
err "✗ $operation : HTTP $code : $(head -c 500 "$body")"
|
||||||
|
rm -f "$body"
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
cat "$body"
|
||||||
|
rm -f "$body"
|
||||||
|
}
|
||||||
|
|
||||||
|
# Directory of the forge tokens of a workstation: `secrets/` of the cluster, i.e. next to the repositories
|
||||||
|
# (the parent of the current repository), outside every repository. FORGE_SECRETS_DIR overrides it.
|
||||||
|
forge_secrets_dir() {
|
||||||
|
if [ -n "${FORGE_SECRETS_DIR:-}" ]; then
|
||||||
|
printf '%s' "$FORGE_SECRETS_DIR"
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
local root
|
||||||
|
root=$(jj root 2>/dev/null) || root=$(pwd)
|
||||||
|
printf '%s/secrets' "$(dirname "$root")"
|
||||||
|
}
|
||||||
|
|
||||||
|
# "host owner repo" of a git or registry URL: ssh://git@host[:port]/owner/repo.git, git@host:owner/repo.git,
|
||||||
|
# https://host/owner/repo, sparse+https://host/api/packages/owner/cargo/ (owner of the registry, no repo).
|
||||||
|
# Fails if the URL has no known form. Fields are empty when absent.
|
||||||
|
forge_parse_url() {
|
||||||
|
local u="${1#sparse+}" host path owner repo
|
||||||
|
case "$u" in
|
||||||
|
*://*) u="${u#*://}"; u="${u#*@}"; host="${u%%/*}"; path="${u#*/}" ;;
|
||||||
|
*@*:*) u="${u#*@}"; host="${u%%:*}"; path="${u#*:}" ;;
|
||||||
|
*) return 1 ;;
|
||||||
|
esac
|
||||||
|
[ "$path" = "$u" ] && path=""
|
||||||
|
host="${host%%:*}"
|
||||||
|
path="${path%/}"; path="${path%.git}"
|
||||||
|
case "$path" in
|
||||||
|
api/packages/*) owner="${path#api/packages/}"; owner="${owner%%/*}"; repo="" ;;
|
||||||
|
*) owner="${path%%/*}"; repo="${path#*/}"; [ "$repo" = "$path" ] && repo="" ;;
|
||||||
|
esac
|
||||||
|
[ -n "$host" ] || return 1
|
||||||
|
printf '%s %s %s\n' "$host" "$owner" "$repo"
|
||||||
|
}
|
||||||
|
|
||||||
|
# Forge token. `forge_token [url]`: the forge is that of the URL (registry index, repository), by default that of
|
||||||
|
# the `origin` remote. Order, the first that exists wins:
|
||||||
|
# 1. $FORGETOKEN: the CI, where each forge provides its own secret to its own jobs;
|
||||||
|
# 2. the token files of the cluster, most specific first (one line, mode 0600; see forge_secrets_dir):
|
||||||
|
# <secrets>/<host>/<owner>/<repo>.token, <secrets>/<host>/<owner>.token, <secrets>/<host>.token;
|
||||||
|
# 3. the file $FORGE_TOKEN_FILE (former single-token layout).
|
||||||
|
# Nothing on standard output if there is none; the caller then says where to put it. Never displayed.
|
||||||
|
forge_token() {
|
||||||
|
if [ -n "${FORGETOKEN:-}" ]; then
|
||||||
|
printf '%s' "$FORGETOKEN"
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
local url="${1:-}" host owner repo dir f
|
||||||
|
[ -n "$url" ] || url=$(jj git remote list 2>/dev/null | awk '$1=="origin"{print $2; exit}')
|
||||||
|
if [ -n "$url" ] && read -r host owner repo < <(forge_parse_url "$url"); then
|
||||||
|
dir=$(forge_secrets_dir)
|
||||||
|
for f in ${repo:+"$dir/$host/$owner/$repo.token"} ${owner:+"$dir/$host/$owner.token"} "$dir/$host.token"; do
|
||||||
|
if [ -f "$f" ]; then
|
||||||
|
head -n 1 "$f" | tr -d '[:space:]'
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
fi
|
||||||
|
if [ -n "${FORGE_TOKEN_FILE:-}" ] && [ -f "$FORGE_TOKEN_FILE" ]; then
|
||||||
|
head -n 1 "$FORGE_TOKEN_FILE" | tr -d '[:space:]'
|
||||||
|
fi
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
# cargo authentication against the private registry: CARGO_REGISTRIES_<REGISTRY>_TOKEN ("Bearer <token>"),
|
||||||
|
# built from the forge token if not already defined. Needed by any cargo call that
|
||||||
|
# resolves registry dependencies (publish, wiki doc). For crates.io (REGISTRY = crates-io) nothing
|
||||||
|
# is built: the crates.io token is CARGO_REGISTRY_TOKEN, supplied by the user.
|
||||||
|
if [ -n "$REGISTRY" ] && [ "$REGISTRY" != crates-io ]; then
|
||||||
|
reg_var="CARGO_REGISTRIES_$(printf '%s' "$REGISTRY" | tr 'a-z-' 'A-Z_')_TOKEN"
|
||||||
|
if [ -z "${!reg_var:-}" ] && [ -n "$(forge_token "$REGISTRY_INDEX")" ]; then
|
||||||
|
export "$reg_var=Bearer $(forge_token "$REGISTRY_INDEX")"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Version: content of $VERSION_FILE if set (repositories that are not crates, like
|
||||||
|
# crate-kit itself), otherwise first occurrence in the crate's Cargo.toml.
|
||||||
|
current_version() {
|
||||||
|
# Source of the version: VERSION_FILE (exported by the Makefiles of the kits), else the Cargo.toml of a crate.
|
||||||
|
# Without either (script run by hand at the root of a kit, not through make): kit/VERSION (crate-kit) or
|
||||||
|
# overlay/kit/VERSION (extension kit), if present.
|
||||||
|
local file="${VERSION_FILE:-}" candidate
|
||||||
|
if [ -z "$file" ] && [ ! -f "$CARGO_TOML" ]; then
|
||||||
|
for candidate in kit/VERSION overlay/kit/VERSION; do
|
||||||
|
[ -f "$candidate" ] && { file="$candidate"; break; }
|
||||||
|
done
|
||||||
|
fi
|
||||||
|
if [ -n "$file" ]; then
|
||||||
|
head -n 1 "$file"
|
||||||
|
elif [ -f "$CARGO_TOML" ]; then
|
||||||
|
sed -n 's/^version = "\(.*\)"/\1/p' "$CARGO_TOML" | head -n 1
|
||||||
|
else
|
||||||
|
err "✗ no source for the version: no VERSION_FILE, no $CARGO_TOML, no kit/VERSION nor overlay/kit/VERSION here"
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
# Package name: first occurrence in the crate's Cargo.toml.
|
||||||
|
# Abandons the empty commits without a description between trunk() and @ (excluding @ itself): jj refuses to
|
||||||
|
# push a commit without a description, and these carry nothing (leftovers of `jj new`). Descendants
|
||||||
|
# are rebased automatically; neither work nor an already pushed (immutable) commit is touched.
|
||||||
|
abandon_blank_commits() {
|
||||||
|
jj abandon 'trunk()..@ & mutable() & empty() & description(exact:"") ~ @' >/dev/null 2>&1 || true
|
||||||
|
}
|
||||||
|
|
||||||
|
# The commit to publish: @, unless it is empty and without a description (the working commit that `jj new`
|
||||||
|
# leaves after a release or a push); we then go up to the first ancestor that carries work.
|
||||||
|
# Such a commit is not pushed (jj refuses a commit without a description) and deserves neither tag nor main.
|
||||||
|
release_rev() {
|
||||||
|
local rev='@' blank
|
||||||
|
while :; do
|
||||||
|
blank=$(jj log -r "$rev" --no-graph -T 'if(empty && description == "", "1", "0")')
|
||||||
|
[ "$blank" = 1 ] || break
|
||||||
|
rev="$rev-"
|
||||||
|
done
|
||||||
|
echo "$rev"
|
||||||
|
}
|
||||||
|
|
||||||
|
crate_name() { sed -n 's/^name = "\(.*\)"/\1/p' "$CARGO_TOML" | head -n 1; }
|
||||||
|
|
||||||
|
# Last version having an API snapshot (sorted by version number), empty if there is none.
|
||||||
|
latest_snapshot() {
|
||||||
|
ls "$API_DIR"/*.json.gz 2>/dev/null | sed 's|.*/||; s|\.json\.gz$||' | sort -V | tail -n 1 || true
|
||||||
|
}
|
||||||
|
|
||||||
|
# Fingerprint of the tools that produce a snapshot. The rustdoc JSON (format number) and the text
|
||||||
|
# rendering of cargo public-api change with rustc and cargo-public-api: a snapshot written with other
|
||||||
|
# tools than today's is no longer comparable (cargo-semver-checks crashes, or the text diff
|
||||||
|
# announces a break where only the rendering changed).
|
||||||
|
toolchain_stamp() {
|
||||||
|
printf '%s | %s\n' "$(rustc -V)" "$("$CARGO" public-api --version)"
|
||||||
|
}
|
||||||
|
|
||||||
|
# Writes the snapshot of version <version> of the code in the current directory (root of a
|
||||||
|
# crate), into <api_dir>: <version>.txt, <version>.json.gz and <version>.stamp (toolchain_stamp).
|
||||||
|
# Parameters: version, snapshot directory (absolute if the current directory is not the crate).
|
||||||
|
emit_snapshot() {
|
||||||
|
local version="$1" api_dir="$2" name target_dir
|
||||||
|
name=$(crate_name)
|
||||||
|
mkdir -p "$api_dir"
|
||||||
|
|
||||||
|
# -s: without the blanket implementations (`impl<T> Into<U> for Type`…), added by rustc to
|
||||||
|
# every public type and unrelated to its API (they made up half of the file).
|
||||||
|
"$CARGO" public-api -s >"$api_dir/$version.txt"
|
||||||
|
# The rustdoc JSON is unstable; RUSTC_BOOTSTRAP makes it possible to produce it with the stable toolchain,
|
||||||
|
# the same one cargo-semver-checks uses to build the current state.
|
||||||
|
# --document-private-items: cargo-semver-checks builds the current state with private items
|
||||||
|
# (private fields included); a reference without them makes a struct with a private field look like
|
||||||
|
# it "gains a private field" and gives a break wrongly.
|
||||||
|
RUSTC_BOOTSTRAP=1 "$CARGO" rustdoc --lib -q -- -Zunstable-options --output-format json --document-private-items
|
||||||
|
|
||||||
|
target_dir=$("$CARGO" metadata --format-version 1 --no-deps |
|
||||||
|
sed -n 's/.*"target_directory":"\([^"]*\)".*/\1/p')
|
||||||
|
# Compressed (gzip -n: reproducible output): the JSON exceeds 1 MB, jj's limit for a new file.
|
||||||
|
gzip -9 -n -c "$target_dir/doc/${name//-/_}.json" >"$api_dir/$version.json.gz"
|
||||||
|
toolchain_stamp >"$api_dir/$version.stamp"
|
||||||
|
}
|
||||||
|
|
||||||
|
# Regenerates the snapshot of the published version <version> with the current tools, from the code of
|
||||||
|
# its tag `version-<version>` (read-only: `jj file list/show`, no modification of the repository).
|
||||||
|
# The tag is exported into a sibling folder of the crate (`<crate>.baseline.tmp`): the relative paths
|
||||||
|
# of `.cargo/config.toml` (`[patch.<registry>]` towards the neighbours) remain valid there. Only `.cargo/` (ignored
|
||||||
|
# by the repository, generated by `make`) is copied in addition.
|
||||||
|
regenerate_snapshot() {
|
||||||
|
local version="$1" api_dir root tmp rev="version-$1" f
|
||||||
|
api_dir="$(pwd)/$API_DIR"
|
||||||
|
root="$(pwd)"
|
||||||
|
tmp="$root.baseline.tmp"
|
||||||
|
if ! jj file list -r "$rev" >/dev/null 2>&1; then
|
||||||
|
err "✗ tag $rev not found: cannot regenerate the snapshot of $version"
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
rm -rf "$tmp"
|
||||||
|
mkdir -p "$tmp"
|
||||||
|
while IFS= read -r f; do
|
||||||
|
mkdir -p "$tmp/$(dirname "$f")"
|
||||||
|
jj file show -r "$rev" "$f" >"$tmp/$f"
|
||||||
|
done < <(jj file list -r "$rev")
|
||||||
|
[ -d "$root/.cargo" ] && cp -R "$root/.cargo" "$tmp/.cargo"
|
||||||
|
(
|
||||||
|
cd "$tmp"
|
||||||
|
CARGO_TARGET_DIR="$tmp/target" emit_snapshot "$version" "$api_dir"
|
||||||
|
) || { rm -rf "$tmp"; return 1; }
|
||||||
|
rm -rf "$tmp"
|
||||||
|
}
|
||||||
|
|
||||||
|
# Fails with an installation message if a cargo tool is missing.
|
||||||
|
require_cargo_tool() {
|
||||||
|
local sub="$1" crate="$2"
|
||||||
|
if ! command -v "cargo-$sub" >/dev/null 2>&1; then
|
||||||
|
err "✗ cargo-$sub is required: cargo install $crate --locked"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
# Lines that are not the crate's API and that the text diff must not see:
|
||||||
|
# - `impl core::marker::Freeze`: unstable auto trait, invisible on stable; it appears or
|
||||||
|
# disappears as soon as a field goes under `Mutex`/`Atomic*`, with no effect for a caller;
|
||||||
|
# - the blanket implementations (`impl<T> other_crate::Trait for Type`) of traits of OTHER crates
|
||||||
|
# and their associated items: rustdoc lists them for every trait of the dependency graph, so
|
||||||
|
# they appear or disappear when a dependency changes (e.g. `crossbeam_epoch::Pointable`,
|
||||||
|
# `either::IntoEither`), without the crate's API having moved. Those of `core`,
|
||||||
|
# `alloc`, `std` and of the crate itself are kept.
|
||||||
|
filter_unstable() {
|
||||||
|
grep -v '^impl core::marker::Freeze for ' "$1" | awk -v crate="$(crate_name)" '
|
||||||
|
/^impl</ {
|
||||||
|
skip = 0
|
||||||
|
rest = $0
|
||||||
|
sub(/^impl<[^>]*> /, "", rest)
|
||||||
|
split(rest, parts, " ")
|
||||||
|
trait = parts[1]
|
||||||
|
if (trait !~ /^(core|alloc|std)::/ && index(trait, crate "::") != 1 && match($0, / for [^ ]+/)) {
|
||||||
|
self = substr($0, RSTART + 5, RLENGTH - 5)
|
||||||
|
skip = 1
|
||||||
|
next
|
||||||
|
}
|
||||||
|
print
|
||||||
|
next
|
||||||
|
}
|
||||||
|
skip && (index($0, "pub fn " self "::") == 1 || index($0, "pub unsafe fn " self "::") == 1 ||
|
||||||
|
index($0, "pub type " self "::") == 1 || index($0, "pub const " self "::") == 1) { next }
|
||||||
|
{ skip = 0; print }
|
||||||
|
' || true
|
||||||
|
}
|
||||||
|
|
||||||
|
# API text for the release notes: `filter_unstable`, then without the auto traits
|
||||||
|
# (`Send`, `Sync`, `Unpin`, `UnwindSafe`, `RefUnwindSafe`, `Freeze`, `Forget`, `Move`, `UnsafeUnpin`,
|
||||||
|
# `StructuralPartialEq`) that cargo public-api lists for every type: a new type adds nine
|
||||||
|
# lines that drown the API. They remain in the snapshot, hence in the verdict of `make api-level`
|
||||||
|
# (losing `Send` is a break); only the readable notes omit them.
|
||||||
|
filter_notes() {
|
||||||
|
filter_unstable "$1" | grep -v -E '^impl core::(marker::(Forget|Freeze|Move|Send|Sync|Unpin|UnsafeUnpin|StructuralPartialEq)|panic::unwind_safe::(RefUnwindSafe|UnwindSafe)) for ' || true
|
||||||
|
}
|
||||||
Executable
+193
@@ -0,0 +1,193 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Freshness of the EXTERNAL dependencies (crates.io) declared by the project. `cargo outdated` compares the
|
||||||
|
# Cargo.lock version to the latest published one, but not the requirement written in Cargo.toml: a
|
||||||
|
# requirement `os_info = "3.8"` with a lock up to date at 3.15 goes unnoticed, and a consumer of the
|
||||||
|
# crate may end up with a version seven minor versions old.
|
||||||
|
#
|
||||||
|
# For each direct dependency `name = "x.y"` or `name = { version = "x.y", … }` (excluding `path`, `git`,
|
||||||
|
# `registry`, `workspace`), in [dependencies], [dev-dependencies], [build-dependencies], their
|
||||||
|
# `target.*` variants and [workspace.dependencies], it checks:
|
||||||
|
# 1. the requirement accepts the latest published version (for a 0.x, `0.5` does not accept 0.6);
|
||||||
|
# 2. for a version ≥ 1, the required minor version is not behind the latest
|
||||||
|
# (`tokio = "1.35"` while 1.52 exists). A 0.x is not checked at this level: its
|
||||||
|
# patch number does not count;
|
||||||
|
# 3. Cargo.lock is on the latest version that the requirement accepts.
|
||||||
|
# Requirements that are not written `x`, `x.y` or `x.y.z` (`=1.2.3`, `~1.2`, `>=1`, ranges) are
|
||||||
|
# explicit choices: ignored.
|
||||||
|
#
|
||||||
|
# deps-check-external.sh check (read-only, except for the network)
|
||||||
|
# deps-check-external.sh bump raises the outdated requirements then `cargo update -p`
|
||||||
|
#
|
||||||
|
# Variables: DEPS_CHECK_EXTERNAL=0 disables the check (workspace too large to be kept up
|
||||||
|
# to date all at once); DEPS_CHECK_EXTERNAL_IGNORE="crate1 crate2" sets crates aside (to be justified in
|
||||||
|
# the Makefile: for example a public dependency that must move up with the neighbouring crates); CRATES_IO_INDEX (default https://index.crates.io); DEPS_CHECK_OFFLINE=1 ignores
|
||||||
|
# the absence of network (warning).
|
||||||
|
# shellcheck disable=SC2154 # manifests comes from deps-lib.sh
|
||||||
|
set -euo pipefail
|
||||||
|
. "$(dirname "$0")/common.sh"
|
||||||
|
. "$(dirname "$0")/deps-lib.sh"
|
||||||
|
|
||||||
|
mode="${1:-check}"
|
||||||
|
case "$mode" in check | bump) ;; *)
|
||||||
|
err "usage: deps-check-external.sh [check|bump]"
|
||||||
|
exit 2
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
if [ "${DEPS_CHECK_EXTERNAL:-1}" = 0 ]; then
|
||||||
|
info " (external dependencies: check disabled by DEPS_CHECK_EXTERNAL=0)"
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
[ -f "$CARGO_TOML" ] || exit 0
|
||||||
|
|
||||||
|
crates_index="${CRATES_IO_INDEX:-https://index.crates.io}"
|
||||||
|
crates_index="${crates_index%/}"
|
||||||
|
|
||||||
|
fail=0
|
||||||
|
bad() {
|
||||||
|
err " ✗ $*"
|
||||||
|
fail=1
|
||||||
|
}
|
||||||
|
|
||||||
|
# External declarations of a manifest: "key<TAB>crate<TAB>requirement" (the crate differs from the key
|
||||||
|
# when the dependency is renamed by `package = "…"`).
|
||||||
|
declarations() {
|
||||||
|
awk '
|
||||||
|
/^\[/ { dep = ($0 ~ /^\[(workspace\.|target\..*\.)?(dev-|build-)?dependencies\]$/); next }
|
||||||
|
!dep { next }
|
||||||
|
/^[ \t]*#/ { next }
|
||||||
|
{
|
||||||
|
if (match($0, /^[A-Za-z0-9_-]+[ \t]*=/) == 0) next
|
||||||
|
key = $0; sub(/[ \t]*=.*/, "", key)
|
||||||
|
rest = $0; sub(/^[A-Za-z0-9_-]+[ \t]*=[ \t]*/, "", rest)
|
||||||
|
crate = key
|
||||||
|
if (rest ~ /^"/) {
|
||||||
|
req = rest; sub(/^"/, "", req); sub(/".*/, "", req)
|
||||||
|
} else if (rest ~ /^\{/) {
|
||||||
|
if (rest ~ /(path|git|registry|workspace)[ \t]*=/) next
|
||||||
|
if (match(rest, /version[ \t]*=[ \t]*"[^"]*"/) == 0) next
|
||||||
|
req = substr(rest, RSTART, RLENGTH)
|
||||||
|
sub(/^version[ \t]*=[ \t]*"/, "", req); sub(/"$/, "", req)
|
||||||
|
if (match(rest, /package[ \t]*=[ \t]*"[^"]*"/)) {
|
||||||
|
crate = substr(rest, RSTART, RLENGTH)
|
||||||
|
sub(/^package[ \t]*=[ \t]*"/, "", crate); sub(/"$/, "", crate)
|
||||||
|
}
|
||||||
|
} else next
|
||||||
|
print key "\t" crate "\t" req
|
||||||
|
}
|
||||||
|
' "$1"
|
||||||
|
}
|
||||||
|
|
||||||
|
# Replaces the requirement of the dependency `key` (in a dependencies section) of manifest $1 with $3.
|
||||||
|
rewrite_req() {
|
||||||
|
awk -v n="$2" -v r="$3" '
|
||||||
|
/^\[/ { dep = ($0 ~ /dependencies\]$/) }
|
||||||
|
dep && $0 ~ "^" n "[ \t]*=" {
|
||||||
|
if ($0 ~ /\{/) sub(/version[ \t]*=[ \t]*"[^"]*"/, "version = \"" r "\"")
|
||||||
|
else sub(/"[^"]*"/, "\"" r "\"")
|
||||||
|
}
|
||||||
|
{ print }
|
||||||
|
' "$1" >"$1.tmp" && mv "$1.tmp" "$1"
|
||||||
|
}
|
||||||
|
|
||||||
|
# Requirement to write for version $1: x.y (≥ 1) or 0.y.
|
||||||
|
floor_for() { echo "$1" | cut -d. -f1,2; }
|
||||||
|
|
||||||
|
tmp=$(mktemp -d)
|
||||||
|
trap 'rm -r "$tmp"' EXIT
|
||||||
|
|
||||||
|
info "→ Freshness of the external dependencies (crates.io)..."
|
||||||
|
count=0
|
||||||
|
offline=0
|
||||||
|
updates=""
|
||||||
|
for manifest in "${manifests[@]}"; do
|
||||||
|
while IFS=$'\t' read -r key crate req; do
|
||||||
|
[ -n "$crate" ] || continue
|
||||||
|
# Dependency deliberately set aside (DEPS_CHECK_EXTERNAL_IGNORE, with its reason in the Makefile).
|
||||||
|
case " ${DEPS_CHECK_EXTERNAL_IGNORE:-} " in *" $crate "*) continue ;; esac
|
||||||
|
# Explicit requirement (=, ~, >=, range): a choice, not checked (and no network request).
|
||||||
|
case "${req#^}" in '' | *[!0-9.]*) continue ;; esac
|
||||||
|
count=$((count + 1))
|
||||||
|
|
||||||
|
if [ ! -f "$tmp/$crate" ]; then
|
||||||
|
rc=0
|
||||||
|
found=$(latest_published "$crate" "$crates_index") || rc=$?
|
||||||
|
printf '%s %s\n' "$rc" "$found" >"$tmp/$crate"
|
||||||
|
fi
|
||||||
|
read -r rc latest <"$tmp/$crate"
|
||||||
|
if [ "$rc" -eq 2 ]; then
|
||||||
|
offline=1
|
||||||
|
continue
|
||||||
|
fi
|
||||||
|
if [ "$rc" -eq 1 ] || [ -z "$latest" ]; then
|
||||||
|
warn " ⚠ $crate ($manifest): not found on crates.io, not checked"
|
||||||
|
continue
|
||||||
|
fi
|
||||||
|
|
||||||
|
acc=0
|
||||||
|
req_accepts "$req" "$latest" || acc=$?
|
||||||
|
|
||||||
|
|
||||||
|
if [ "$acc" -eq 1 ]; then
|
||||||
|
# Newer than the latest published (pre-release, yank): nothing to raise.
|
||||||
|
[ "$(printf '%s\n%s\n' "$req" "$latest" | sort -V | tail -n 1)" = "$latest" ] || continue
|
||||||
|
if [ "$mode" = bump ]; then
|
||||||
|
new=$(floor_for "$latest")
|
||||||
|
rewrite_req "$manifest" "$key" "$new"
|
||||||
|
info " $crate ($manifest): \"$req\" → \"$new\" (latest version: $latest)"
|
||||||
|
updates+="$crate "
|
||||||
|
else
|
||||||
|
bad "$crate ($manifest): the requirement \"$req\" does not accept the latest version $latest → \"$(floor_for "$latest")\" (make deps-bump)"
|
||||||
|
fi
|
||||||
|
continue
|
||||||
|
fi
|
||||||
|
|
||||||
|
# The requirement accepts the latest version: is the required minor (≥ 1.0) behind?
|
||||||
|
IFS=. read -r rmaj rmin _ <<<"${req#^}"
|
||||||
|
IFS=. read -r _ lmin _ <<<"$latest"
|
||||||
|
if [ "$rmaj" != 0 ] && [ -n "$rmin" ] && [ "$rmin" -lt "$lmin" ]; then
|
||||||
|
if [ "$mode" = bump ]; then
|
||||||
|
new=$(floor_for "$latest")
|
||||||
|
rewrite_req "$manifest" "$key" "$new"
|
||||||
|
info " $crate ($manifest): \"$req\" → \"$new\" (latest version: $latest)"
|
||||||
|
updates+="$crate "
|
||||||
|
else
|
||||||
|
bad "$crate ($manifest): the requirement \"$req\" is behind the latest version $latest → \"$(floor_for "$latest")\" (make deps-bump)"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Cargo.lock: on the latest version that the requirement accepts.
|
||||||
|
if [ -f Cargo.lock ]; then
|
||||||
|
locked=$(lock_entries | awk -v n="$crate" '$1 == n && index($3, "crates.io-index") { print $2 }' | sort -V | tail -n 1)
|
||||||
|
if [ -n "$locked" ] && [ "$locked" != "$latest" ] &&
|
||||||
|
[ "$(printf '%s\n%s\n' "$locked" "$latest" | sort -V | tail -n 1)" = "$latest" ]; then
|
||||||
|
if [ "$mode" = bump ]; then
|
||||||
|
updates+="$crate "
|
||||||
|
else
|
||||||
|
bad "$crate: Cargo.lock is on $locked, the latest version is $latest → cargo update -p $crate (make deps-bump)"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
done < <(declarations "$manifest")
|
||||||
|
done
|
||||||
|
|
||||||
|
if [ "$offline" -eq 1 ]; then
|
||||||
|
if [ "${DEPS_CHECK_OFFLINE:-}" = 1 ]; then
|
||||||
|
warn " ⚠ crates.io unreachable: freshness of the external dependencies not verified (DEPS_CHECK_OFFLINE=1)"
|
||||||
|
else
|
||||||
|
bad "crates.io unreachable ($crates_index): freshness cannot be verified (DEPS_CHECK_OFFLINE=1 to ignore)"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ "$mode" = bump ] && [ -n "$updates" ]; then
|
||||||
|
for n in $(printf '%s\n' $updates | sort -u); do
|
||||||
|
info " cargo update -p $n"
|
||||||
|
"$CARGO" update -p "$n" >/dev/null
|
||||||
|
done
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ "$fail" -ne 0 ]; then
|
||||||
|
err "✗ External dependencies out of date (see above)"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
ok "✓ External dependencies up to date ($count checked)"
|
||||||
Executable
+166
@@ -0,0 +1,166 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Freshness of the dependencies between crates of the private registry: we must never keep running with an
|
||||||
|
# old version of a registry crate when a new one is published. Fails (code 1) at the slightest discrepancy.
|
||||||
|
#
|
||||||
|
# For each dependency `name = { version = "x.y", registry = "<registry>" }` declared by the project
|
||||||
|
# (same reading as dev-patch.sh), it checks:
|
||||||
|
# 1. the requirement accepts the latest version published on the registry (for a 0.x, `0.1` never
|
||||||
|
# accepts 0.2: Cargo says nothing);
|
||||||
|
# 2. Cargo.lock is on that latest version (if it points to the registry);
|
||||||
|
# 3. the neighbouring folder ../<name>, which replaces the dependency in joint development, is not
|
||||||
|
# behind the registry (otherwise we build against stale code);
|
||||||
|
# 4. Cargo.lock contains no [[patch.unused]] (ignored local patch: requirement too low);
|
||||||
|
# 5. no registry crate appears in several versions in Cargo.lock (two copies in the build).
|
||||||
|
# A neighbour newer than the registry (pending publication) is reported without failing.
|
||||||
|
#
|
||||||
|
# deps-check.sh check (read-only, except for the network)
|
||||||
|
# deps-check.sh bump fixes the outdated requirements (rewrites the Cargo.toml) then `cargo update -p`
|
||||||
|
#
|
||||||
|
# Network: the sparse index of the registry ($REGISTRY_INDEX), public. Without network, the check
|
||||||
|
# fails; DEPS_CHECK_OFFLINE=1 explicitly ignores it (warning).
|
||||||
|
# shellcheck disable=SC2154 # index_url and manifests come from deps-lib.sh
|
||||||
|
set -euo pipefail
|
||||||
|
. "$(dirname "$0")/common.sh"
|
||||||
|
[ -n "$REGISTRY" ] || { err "✗ no registry: declare the kit extension (KIT_OVERLAY in the Makefile, org.mk) or set REGISTRY = crates-io"; exit 1; }
|
||||||
|
[ "$REGISTRY" != crates-io ] || { info " (crates.io registry: dependencies checked by deps-check-external)"; exit 0; }
|
||||||
|
|
||||||
|
mode="${1:-check}"
|
||||||
|
case "$mode" in check | bump) ;; *)
|
||||||
|
err "usage: deps-check.sh [check|bump]"
|
||||||
|
exit 2
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
[ -f "$CARGO_TOML" ] || exit 0
|
||||||
|
|
||||||
|
fail=0
|
||||||
|
bad() {
|
||||||
|
err " ✗ $*"
|
||||||
|
fail=1
|
||||||
|
}
|
||||||
|
|
||||||
|
. "$(dirname "$0")/deps-lib.sh"
|
||||||
|
|
||||||
|
decl=""
|
||||||
|
for m in "${manifests[@]}"; do
|
||||||
|
lines=$(grep -E "^[A-Za-z0-9_-]+[[:space:]]*=[[:space:]]*\{[^}]*registry[[:space:]]*=[[:space:]]*\"$REGISTRY\"" "$m" || true)
|
||||||
|
[ -n "$lines" ] && decl+="$(printf '%s\n' "$lines" | sed "s|^|$m |")"$'\n'
|
||||||
|
done
|
||||||
|
|
||||||
|
if [ -z "$decl" ]; then
|
||||||
|
ok "✓ No dependency on registry $REGISTRY to check"
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
info "→ Freshness of the registry dependencies (registry $REGISTRY)..."
|
||||||
|
count=0
|
||||||
|
updates=""
|
||||||
|
offline=0
|
||||||
|
while IFS=$'\t' read -r manifest line; do
|
||||||
|
[ -n "$manifest" ] || continue
|
||||||
|
name=${line%%[[:space:]=]*}
|
||||||
|
req=$(printf '%s' "$line" | sed -nE 's/.*version[[:space:]]*=[[:space:]]*"([^"]*)".*/\1/p')
|
||||||
|
count=$((count + 1))
|
||||||
|
if [ -z "$req" ]; then
|
||||||
|
bad "$name ($manifest): no \"version\" in the declaration"
|
||||||
|
continue
|
||||||
|
fi
|
||||||
|
|
||||||
|
rc=0
|
||||||
|
latest=$(latest_published "$name") || rc=$?
|
||||||
|
if [ "$rc" -eq 2 ]; then
|
||||||
|
offline=1
|
||||||
|
continue
|
||||||
|
fi
|
||||||
|
if [ "$rc" -eq 1 ] || [ -z "$latest" ]; then
|
||||||
|
bad "$name ($manifest): no version published on registry $REGISTRY"
|
||||||
|
continue
|
||||||
|
fi
|
||||||
|
|
||||||
|
acc=0
|
||||||
|
req_accepts "$req" "$latest" || acc=$?
|
||||||
|
case "$acc" in
|
||||||
|
2) bad "$name ($manifest): requirement \"$req\" cannot be parsed (write x.y, or x for a version ≥ 1)" ;;
|
||||||
|
1)
|
||||||
|
if [ "$(printf '%s\n%s\n' "$req" "$latest" | sort -V | tail -n 1)" = "$latest" ]; then
|
||||||
|
if [ "$mode" = bump ]; then
|
||||||
|
new=$(req_for "$latest")
|
||||||
|
sed -E "/^${name}[[:space:]]*=.*registry[[:space:]]*=[[:space:]]*\"$REGISTRY\"/ s/(version[[:space:]]*=[[:space:]]*\")[^\"]*/\1$new/" "$manifest" >"$manifest.tmp" &&
|
||||||
|
mv "$manifest.tmp" "$manifest"
|
||||||
|
info " $name ($manifest): \"$req\" → \"$new\" (latest published version: $latest)"
|
||||||
|
updates+="$name "
|
||||||
|
else
|
||||||
|
bad "$name ($manifest): the requirement \"$req\" does not accept the latest published version $latest → $name = { version = \"$(req_for "$latest")\", registry = \"$REGISTRY\" } (make deps-bump)"
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
bad "$name ($manifest): the requirement \"$req\" is newer than the latest published version $latest (publication pending?)"
|
||||||
|
fi
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
# Cargo.lock: on the latest version if the dependency comes from the registry.
|
||||||
|
if [ -f Cargo.lock ]; then
|
||||||
|
locked=$(lock_entries | awk -v n="$name" -v r="/api/packages/$REGISTRY/" '$1 == n && index($3, r) { print $2 }' | sort -V | tail -n 1)
|
||||||
|
if [ -n "$locked" ] && [ "$locked" != "$latest" ] && [ "$acc" -eq 0 ]; then
|
||||||
|
if [ "$mode" = bump ]; then
|
||||||
|
updates+="$name "
|
||||||
|
else
|
||||||
|
bad "$name: Cargo.lock is on $locked, the latest published version is $latest → cargo update -p $name (make deps-bump)"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Neighbouring folder: replaces the dependency in joint development.
|
||||||
|
if [ -f "../$name/Cargo.toml" ]; then
|
||||||
|
neighbor=$(sed -n 's/^version = "\(.*\)"/\1/p' "../$name/Cargo.toml" | head -n 1)
|
||||||
|
if [ -n "$neighbor" ] && [ "$neighbor" != "$latest" ]; then
|
||||||
|
if [ "$(printf '%s\n%s\n' "$neighbor" "$latest" | sort -V | tail -n 1)" = "$latest" ]; then
|
||||||
|
bad "$name: the neighbouring folder ../$name is at $neighbor, the registry at $latest → update the neighbour (jj git fetch)"
|
||||||
|
else
|
||||||
|
warn " ⚠ $name: the neighbouring folder ../$name ($neighbor) is newer than the published version ($latest): publication pending"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
done <<<"$decl"
|
||||||
|
|
||||||
|
if [ "$offline" -eq 1 ]; then
|
||||||
|
if [ "${DEPS_CHECK_OFFLINE:-}" = 1 ]; then
|
||||||
|
warn " ⚠ registry unreachable: freshness of the dependencies not verified (DEPS_CHECK_OFFLINE=1)"
|
||||||
|
else
|
||||||
|
bad "registry $REGISTRY unreachable ($index_url): freshness cannot be verified (DEPS_CHECK_OFFLINE=1 to ignore)"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Cargo.lock: ignored patch and duplicates.
|
||||||
|
if [ -f Cargo.lock ]; then
|
||||||
|
unused=$(awk '
|
||||||
|
/^\[\[patch.unused\]\]/ { u = 1; next }
|
||||||
|
/^\[/ { u = 0 }
|
||||||
|
u && /^name = / { gsub(/"/, "", $3); print $3 }
|
||||||
|
' Cargo.lock | sort -u | paste -sd' ' -)
|
||||||
|
if [ -n "$unused" ] && [ "$mode" = check ]; then
|
||||||
|
bad "Cargo.lock: local patch ignored for $unused — the project's requirement does not accept the version of the neighbouring folder"
|
||||||
|
fi
|
||||||
|
dups=$(lock_entries | awk -v r="/api/packages/$REGISTRY/" '
|
||||||
|
{ c[$1]++; vs[$1] = vs[$1] " " $2; if ($3 == "-" || index($3, r)) p[$1] = 1 }
|
||||||
|
END { for (n in c) if (c[n] > 1 && p[n]) print n ":" vs[n] }
|
||||||
|
')
|
||||||
|
if [ -n "$dups" ]; then
|
||||||
|
while IFS= read -r d; do
|
||||||
|
bad "Cargo.lock: several versions of ${d%%:*} in the build (${d#*: }) — align the requirements of the crates that depend on it"
|
||||||
|
done <<<"$dups"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ "$mode" = bump ] && [ -n "$updates" ]; then
|
||||||
|
for n in $(printf '%s\n' $updates | sort -u); do
|
||||||
|
info " cargo update -p $n"
|
||||||
|
"$CARGO" update -p "$n" >/dev/null
|
||||||
|
done
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ "$fail" -ne 0 ]; then
|
||||||
|
err "✗ Registry dependencies stale or inconsistent (see above)"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
ok "✓ Registry dependencies up to date ($count checked)"
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Functions shared by the dependency checks (deps-check.sh, deps-check-external.sh).
|
||||||
|
# To be sourced after common.sh. Nothing here writes a file.
|
||||||
|
|
||||||
|
index_url="${REGISTRY_INDEX#sparse+}"
|
||||||
|
index_url="${index_url%/}"
|
||||||
|
|
||||||
|
# Path of a crate in a sparse index (1, 2, 3 characters, then two pairs).
|
||||||
|
index_path() {
|
||||||
|
local n
|
||||||
|
n=$(printf '%s' "$1" | tr 'A-Z' 'a-z')
|
||||||
|
case ${#n} in
|
||||||
|
1) echo "1/$n" ;;
|
||||||
|
2) echo "2/$n" ;;
|
||||||
|
3) echo "3/${n:0:1}/$n" ;;
|
||||||
|
*) echo "${n:0:2}/${n:2:2}/$n" ;;
|
||||||
|
esac
|
||||||
|
}
|
||||||
|
|
||||||
|
# Latest published version (not yanked, excluding pre-releases) of $1 in the sparse index $2 (default:
|
||||||
|
# the private registry); empty if not found.
|
||||||
|
# Code: 0 found, 1 absent from the index, 2 index unreachable.
|
||||||
|
latest_published() {
|
||||||
|
local body rc=0 base="${2:-$index_url}"
|
||||||
|
body=$(curl -sS -f -m 20 "$base/$(index_path "$1")" 2>/dev/null) || rc=$?
|
||||||
|
if [ "$rc" -ne 0 ]; then
|
||||||
|
case "$rc" in 22 | 37) return 1 ;; *) return 2 ;; esac
|
||||||
|
fi
|
||||||
|
printf '%s\n' "$body" |
|
||||||
|
sed -n 's/.*"vers":"\([^"]*\)".*"yanked":false.*/\1/p' |
|
||||||
|
grep -v -- '-' | sort -V | tail -n 1
|
||||||
|
}
|
||||||
|
|
||||||
|
# Does the requirement $1 (x, x.y or x.y.z, with optional ^) accept version $2?
|
||||||
|
# Code: 0 yes, 1 no, 2 unsupported form.
|
||||||
|
req_accepts() {
|
||||||
|
local r="${1#^}" v="$2" rmaj rmin rest vmaj vmin
|
||||||
|
case "$r" in '' | *[!0-9.]*) return 2 ;; esac
|
||||||
|
IFS=. read -r rmaj rmin rest <<<"$r"
|
||||||
|
IFS=. read -r vmaj vmin rest <<<"$v"
|
||||||
|
[ "$rmaj" = "$vmaj" ] || return 1
|
||||||
|
if [ "$rmaj" = 0 ] && [ -n "$rmin" ]; then
|
||||||
|
[ "$rmin" = "$vmin" ] || return 1
|
||||||
|
fi
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
# Minimal requirement that accepts version $1: x.y for a 0.x, x otherwise.
|
||||||
|
req_for() {
|
||||||
|
case "$1" in
|
||||||
|
0.*) echo "$1" | cut -d. -f1,2 ;;
|
||||||
|
*) echo "$1" | cut -d. -f1 ;;
|
||||||
|
esac
|
||||||
|
}
|
||||||
|
|
||||||
|
# Packages of Cargo.lock, one per line: "name version source" ("-" without source). The
|
||||||
|
# [[patch.unused]] blocks are excluded.
|
||||||
|
lock_entries() {
|
||||||
|
awk '
|
||||||
|
function flush() { if (n != "") print n, v, (s == "" ? "-" : s); n = v = s = "" }
|
||||||
|
/^\[\[package\]\]/ { flush(); inpkg = 1; next }
|
||||||
|
/^\[/ { flush(); inpkg = 0; next }
|
||||||
|
inpkg && /^name = / { gsub(/"/, "", $3); n = $3 }
|
||||||
|
inpkg && /^version = / { gsub(/"/, "", $3); v = $3 }
|
||||||
|
inpkg && /^source = / { gsub(/"/, "", $3); s = $3 }
|
||||||
|
END { flush() }
|
||||||
|
' Cargo.lock
|
||||||
|
}
|
||||||
|
|
||||||
|
manifests=("$CARGO_TOML")
|
||||||
|
# Root of a workspace whose member CARGO_TOML designates (workspace): shared dependencies.
|
||||||
|
[ "$CARGO_TOML" != Cargo.toml ] && [ -f Cargo.toml ] && manifests+=(Cargo.toml)
|
||||||
|
# MEMBERS_DIR: folder holding the workspace (root Cargo.toml and members) when it is not the project root.
|
||||||
|
for m in */Cargo.toml ${MEMBERS_DIR:+"$MEMBERS_DIR/Cargo.toml" "$MEMBERS_DIR"/*/Cargo.toml}; do
|
||||||
|
if [ -f "$m" ] && [ "$m" != "$CARGO_TOML" ]; then manifests+=("$m"); fi
|
||||||
|
done
|
||||||
Executable
+75
@@ -0,0 +1,75 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Generates .cargo/config.toml (local, ignored by jj) for joint development:
|
||||||
|
# - the definition of the private registry;
|
||||||
|
# - a [patch.<registry>] for each registry dependency that has a neighbouring folder
|
||||||
|
# (../<name>/Cargo.toml), so that the project builds against the neighbouring code without publishing.
|
||||||
|
# Only the dependencies actually declared by this project are patched: no unused patch
|
||||||
|
# (Cargo complains about it), whatever the number of crates coming out of a workspace.
|
||||||
|
#
|
||||||
|
# Run by crate.mk on every make invocation. The file is rewritten only if it changes.
|
||||||
|
# Reads the root Cargo.toml and those of the direct subfolders (workspace members), and, if MEMBERS_DIR is set,
|
||||||
|
# those of that folder (its Cargo.toml and its direct subfolders);
|
||||||
|
# only the dependencies on one line `name = { …, registry = "<registry>" }` are seen.
|
||||||
|
# A .cargo/config.toml that was not generated by this script is never overwritten (warning).
|
||||||
|
set -euo pipefail
|
||||||
|
. "$(dirname "$0")/common.sh"
|
||||||
|
|
||||||
|
[ -f "$CARGO_TOML" ] || exit 0
|
||||||
|
# Nothing to generate without a registry (no extension) nor for crates.io (cargo's default index and token).
|
||||||
|
[ -n "$REGISTRY" ] && [ "$REGISTRY" != crates-io ] || exit 0
|
||||||
|
|
||||||
|
marker="# Generated by .crate-kit/scripts/dev-patch.sh"
|
||||||
|
config=".cargo/config.toml"
|
||||||
|
|
||||||
|
if [ -f "$config" ] && ! grep -q "^$marker" "$config"; then
|
||||||
|
warn "⚠ $config was not generated by the kit: left as is. If it is tracked by the repository,"
|
||||||
|
warn " delete it and add /.cargo/config.toml to .gitignore (the CI uses an environment variable)."
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
self=$(crate_name)
|
||||||
|
manifests=("$CARGO_TOML")
|
||||||
|
# Root of a workspace whose member CARGO_TOML designates (workspace): this is where the shared
|
||||||
|
# dependencies ([workspace.dependencies]) are declared.
|
||||||
|
[ "$CARGO_TOML" != Cargo.toml ] && [ -f Cargo.toml ] && manifests+=(Cargo.toml)
|
||||||
|
# MEMBERS_DIR: folder holding the workspace (root Cargo.toml and members), when it is not the project root
|
||||||
|
# (application workspace with its crates under src/: MEMBERS_DIR := src).
|
||||||
|
for m in */Cargo.toml ${MEMBERS_DIR:+"$MEMBERS_DIR/Cargo.toml" "$MEMBERS_DIR"/*/Cargo.toml}; do
|
||||||
|
[ -f "$m" ] && [ "$m" != "$CARGO_TOML" ] && manifests+=("$m")
|
||||||
|
done
|
||||||
|
|
||||||
|
registry_deps() {
|
||||||
|
sed -nE "s/^([A-Za-z0-9_-]+)[[:space:]]*=[[:space:]]*\{[^}]*registry[[:space:]]*=[[:space:]]*\"$REGISTRY\".*/\1/p" "$@"
|
||||||
|
}
|
||||||
|
names=$(registry_deps "${manifests[@]}" | sort -u)
|
||||||
|
# Transitive closure through the neighbours: a dependency of a patched neighbour (a -> a-macros)
|
||||||
|
# must be patched too, otherwise the project builds the neighbour against the published version of its own
|
||||||
|
# dependency and not against the neighbouring code.
|
||||||
|
while :; do
|
||||||
|
more=$(for n in $names; do [ -f "../$n/Cargo.toml" ] && registry_deps "../$n/Cargo.toml"; done | sort -u)
|
||||||
|
merged=$(printf '%s\n%s\n' "$names" "$more" | sed '/^$/d' | sort -u)
|
||||||
|
[ "$merged" = "$names" ] && break
|
||||||
|
names=$merged
|
||||||
|
done
|
||||||
|
|
||||||
|
patches=""
|
||||||
|
for n in $names; do
|
||||||
|
[ "$n" = "$self" ] && continue
|
||||||
|
[ -f "../$n/Cargo.toml" ] && patches+="$n = { path = \"../$n\" }"$'\n'
|
||||||
|
done
|
||||||
|
|
||||||
|
new="$marker on every \`make\`: do not edit, do not commit (ignored by the repository).
|
||||||
|
# Private registry and, for joint development, dependencies resolved to the neighbouring folders.
|
||||||
|
[registries.$REGISTRY]
|
||||||
|
index = \"$REGISTRY_INDEX\"
|
||||||
|
"
|
||||||
|
[ -n "$patches" ] && new+="
|
||||||
|
[patch.$REGISTRY]
|
||||||
|
$patches"
|
||||||
|
|
||||||
|
if [ ! -f "$config" ] || [ "$(cat "$config")" != "${new%$'\n'}" ]; then
|
||||||
|
mkdir -p .cargo
|
||||||
|
printf '%s' "$new" >"$config"
|
||||||
|
list=$(printf '%s' "$patches" | sed 's/ = .*//' | paste -sd' ' -)
|
||||||
|
info " $config updated (local patches: ${list:-none})"
|
||||||
|
fi
|
||||||
Executable
+56
@@ -0,0 +1,56 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Creates the Forgejo release associated with the tag version-x.y.z. Description: the message of the tag if it is
|
||||||
|
# annotated, otherwise (lightweight tag created by tag.sh) the file $RELEASE_NOTES_DIR/version-x.y.z.md of the
|
||||||
|
# working directory, which must be the checkout of the tag. Meant for the CI; idempotent: an already existing release is
|
||||||
|
# reused, and an attached file that is already present is not sent again.
|
||||||
|
#
|
||||||
|
# Variables (provided by the workflow):
|
||||||
|
# FORGETOKEN Forgejo API token (write access to releases)
|
||||||
|
# TAG tag to publish (e.g. version-0.1.4)
|
||||||
|
# SERVER Forgejo server URL (e.g. https://forge.example.org)
|
||||||
|
# REPO owner/repository (e.g. org/crate)
|
||||||
|
# ASSET optional: file to attach to the release (e.g. dist/crate-kit-0.1.4.tar.gz)
|
||||||
|
set -euo pipefail
|
||||||
|
. "$(dirname "$0")/common.sh"
|
||||||
|
|
||||||
|
: "${FORGETOKEN:?FORGETOKEN required}" "${TAG:?TAG required}" "${SERVER:?SERVER required}" "${REPO:?REPO required}"
|
||||||
|
command -v jq >/dev/null || { err "✗ jq is required"; exit 1; }
|
||||||
|
|
||||||
|
api="$SERVER/api/v1/repos/$REPO"
|
||||||
|
auth="Authorization: token $FORGETOKEN"
|
||||||
|
|
||||||
|
if release_json=$(curl -sf -H "$auth" "$api/releases/tags/$TAG"); then
|
||||||
|
warn " The release $TAG already exists: reused"
|
||||||
|
else
|
||||||
|
# Message of the annotated tag (object of type "tag"); empty for a lightweight tag.
|
||||||
|
ref_json=$(forge_call "reading tag $TAG" -H "$auth" "$api/git/refs/tags/$TAG") || exit 1
|
||||||
|
obj_sha=$(echo "$ref_json" | jq -r '.[0]?.object.sha // empty')
|
||||||
|
obj_type=$(echo "$ref_json" | jq -r '.[0]?.object.type // empty')
|
||||||
|
body=""
|
||||||
|
if [ "$obj_type" = "tag" ]; then
|
||||||
|
tag_json=$(forge_call "reading the message of tag $TAG" -H "$auth" "$api/git/tags/$obj_sha") || exit 1
|
||||||
|
body=$(echo "$tag_json" | jq -r '.message // empty')
|
||||||
|
fi
|
||||||
|
# Lightweight tag (tag.sh, jj only): the notes are the file committed in the tagged revision, read in the
|
||||||
|
# working directory (the workflow runs in the checkout of the tag).
|
||||||
|
if [ -z "$body" ] && [ -f "$RELEASE_NOTES_DIR/$TAG.md" ]; then
|
||||||
|
body=$(cat "$RELEASE_NOTES_DIR/$TAG.md")
|
||||||
|
fi
|
||||||
|
release_json=$(forge_call "creating release $TAG" -X POST "$api/releases" -H "$auth" \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-d "$(jq -n --arg tag "$TAG" --arg body "$body" '{tag_name: $tag, name: $tag, body: $body}')") || exit 1
|
||||||
|
ok "✓ Release $TAG created"
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ -n "${ASSET:-}" ]; then
|
||||||
|
[ -f "$ASSET" ] || { err "✗ file to attach not found: $ASSET"; exit 1; }
|
||||||
|
release_id=$(echo "$release_json" | jq -r '.id')
|
||||||
|
name=$(basename "$ASSET")
|
||||||
|
if echo "$release_json" | jq -e --arg n "$name" '.assets[]? | select(.name == $n)' >/dev/null; then
|
||||||
|
warn " $name is already attached to the release: nothing to do"
|
||||||
|
else
|
||||||
|
forge_call "uploading $name to release $TAG" -X POST "$api/releases/$release_id/assets?name=$name" \
|
||||||
|
-H "$auth" -F "attachment=@$ASSET" >/dev/null || exit 1
|
||||||
|
ok "✓ $name attached to release $TAG"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
Executable
+74
@@ -0,0 +1,74 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Fetches the latest commits from origin WITHOUT losing local work: the mutable revisions
|
||||||
|
# sitting on the old main are rebased on top of the fetched main@origin.
|
||||||
|
#
|
||||||
|
# - local work (mutable revisions between main@origin and @, including an empty working
|
||||||
|
# copy): rebased onto main@origin;
|
||||||
|
# - work sitting on a pushed revision not yet merged into main@origin (pending
|
||||||
|
# PR): left in place, with a warning (rebasing it would cut it off from that revision);
|
||||||
|
# - working copy already contained in main@origin: we start again from a new revision on top of it.
|
||||||
|
#
|
||||||
|
# JJ_BASE (default main@origin): the base to join.
|
||||||
|
set -euo pipefail
|
||||||
|
. "$(dirname "$0")/common.sh"
|
||||||
|
|
||||||
|
base="${JJ_BASE:-main@origin}"
|
||||||
|
|
||||||
|
info "→ Fetching the latest commits..."
|
||||||
|
jj git fetch
|
||||||
|
|
||||||
|
jj log -r "$base" --no-graph -T 'change_id' >/dev/null 2>&1 || {
|
||||||
|
err "✗ $base not found after the fetch"
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
# Local work = mutable revisions between the base and @ that are NOT already published (reachable
|
||||||
|
# from a remote bookmark): we do not rewrite what origin knows. We only keep the roots
|
||||||
|
# whose parent is already in the base's history.
|
||||||
|
work="(mutable() & ($base..@)) ~ ::remote_bookmarks()"
|
||||||
|
|
||||||
|
# A local revision rewritten AFTER its push (describe, rebase…) then merged on the server side in its
|
||||||
|
# pushed version has a twin in $base: same change id, other commit, hence a divergent
|
||||||
|
# change. We never designate a revision by its change id (jj refuses a divergent
|
||||||
|
# identifier), and we do not rebase what is already merged:
|
||||||
|
# - same content as the merged twin: the local revision is abandoned (nothing is lost);
|
||||||
|
# - different content: we stop before rewriting anything, with the course of action to follow.
|
||||||
|
for c in $(jj log --no-graph -r "($work) & divergent()" -T 'commit_id ++ "\n"'); do
|
||||||
|
cid=$(jj log --no-graph -r "$c" -T 'change_id')
|
||||||
|
twin=$(jj log --no-graph -r "change_id($cid) & ::$base" -T 'commit_id ++ "\n"' | head -n 1)
|
||||||
|
[ -n "$twin" ] || continue
|
||||||
|
short=$(jj log --no-graph -r "$c" -T 'commit_id.short(12)')
|
||||||
|
if [ -z "$(jj interdiff --from "$twin" --to "$c" --summary)" ]; then
|
||||||
|
jj abandon "$c"
|
||||||
|
ok "✓ Revision $short already merged into $base (same content): abandoned"
|
||||||
|
else
|
||||||
|
err "✗ The local revision $short has already been merged into $base in another version"
|
||||||
|
err " (same change id, different content): nothing was rewritten."
|
||||||
|
err " See the difference: jj interdiff --from $twin --to $c"
|
||||||
|
err " Keep the merged version: jj abandon $c"
|
||||||
|
err " Keep the local version: jj metaedit --update-change-id $c, then rerun"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
|
||||||
|
roots=$(jj log --no-graph -r "roots($work) & children(::$base)" -T 'commit_id ++ "\n"')
|
||||||
|
|
||||||
|
if [ -n "$roots" ]; then
|
||||||
|
args=()
|
||||||
|
for r in $roots; do args+=(-s "$r"); done
|
||||||
|
jj rebase "${args[@]}" -d "$base"
|
||||||
|
ok "✓ Local work rebased onto $base"
|
||||||
|
elif [ -n "$(jj log --no-graph -r "@ & ::$base" -T 'change_id')" ]; then
|
||||||
|
# The working copy is already part of the base: nothing to keep.
|
||||||
|
jj new "$base"
|
||||||
|
ok "✓ New revision on $base"
|
||||||
|
elif [ -n "$(jj log --no-graph -r "($base..@) & (::remote_bookmarks() | immutable())" -T 'change_id')" ]; then
|
||||||
|
warn "⚠ The work rests on pushed revisions not merged into $base (pending PR):"
|
||||||
|
warn " left in place. Merge the PR then rerun, if needed."
|
||||||
|
else
|
||||||
|
ok "✓ Already up to date on $base"
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ -n "$(jj log --no-graph -r 'conflicts() & ::@ & mutable()' -T 'change_id' 2>/dev/null)" ]; then
|
||||||
|
warn "⚠ Conflicts after the rebase: jj st, then jj resolve."
|
||||||
|
fi
|
||||||
Executable
+68
@@ -0,0 +1,68 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Checks that the crate is adopted: the CI release workflow is installed and up to date with the template of
|
||||||
|
# its kind (comments and step names ignored; opt out with a `# kit-workflow: custom` line), and the kit copy
|
||||||
|
# (.crate-kit/) is identical to the reference kit (crate-kit + overlay, assembled by $KIT_SRC/tools/kit-assemble.sh; default ../crate-kit). Read-only.
|
||||||
|
#
|
||||||
|
# Compares the CONTENT, not VERSION: a fix to the kit does not always change its number.
|
||||||
|
# `--fix`: instead of failing on an out-of-date workflow, replace it with the template of its kind.
|
||||||
|
# Without a crate-kit repository alongside (clone of the crate alone, CI), there is nothing to compare: success.
|
||||||
|
set -euo pipefail
|
||||||
|
. "$(dirname "$0")/common.sh"
|
||||||
|
|
||||||
|
fix=0
|
||||||
|
[ "${1:-}" = "--fix" ] && fix=1
|
||||||
|
kit_dir="$(cd "$(dirname "$0")/.." && pwd)"
|
||||||
|
crate_dir="$(dirname "$kit_dir")"
|
||||||
|
|
||||||
|
# Without this workflow, a version-* tag publishes nothing: the crate was not adopted all the way.
|
||||||
|
workflow=".gitea/workflows/release.yaml"
|
||||||
|
if [ ! -f "$crate_dir/$workflow" ]; then
|
||||||
|
err "✗ $workflow is missing in $crate_dir: the release CI will not trigger"
|
||||||
|
info " Complete the adoption: crate-kit/adopt.sh [--kind <kind>] $crate_dir"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
kit_src="${KIT_SRC:-../crate-kit}"
|
||||||
|
|
||||||
|
# Workflow up to date with the template of the crate's kind (the same one adopt.sh lays down). Only the
|
||||||
|
# logic counts: comment lines and `- name:` labels are ignored, so a rewording is not a difference.
|
||||||
|
if [ -x "$kit_src/tools/kit-assemble.sh" ] && ! grep -q '^# kit-workflow: custom' "$crate_dir/$workflow"; then
|
||||||
|
kind="${CRATE_KIND:-}"
|
||||||
|
if [ -z "$kind" ] && [ -f "$crate_dir/Makefile" ]; then
|
||||||
|
kind=$(sed -n 's/^CRATE_KIND *[:?]*= *\([a-z]*\).*/\1/p' "$crate_dir/Makefile" | head -n 1)
|
||||||
|
fi
|
||||||
|
template="$("$kit_src/tools/kit-assemble.sh" --root)/template"
|
||||||
|
overlay=$("$kit_src/tools/kit-assemble.sh" --overlay 2>/dev/null || true)
|
||||||
|
[ -n "$kind" ] && [ -n "$overlay" ] && [ -d "$overlay/templates/$kind" ] && template="$overlay/templates/$kind"
|
||||||
|
norm() { grep -v '^ *#' "$1" | grep -v '^ *- name:' | sed 's/[[:space:]]*$//'; }
|
||||||
|
if [ -f "$template/$workflow" ] && ! diff <(norm "$crate_dir/$workflow") <(norm "$template/$workflow") >/dev/null; then
|
||||||
|
if [ "$fix" = 1 ]; then
|
||||||
|
cp "$template/$workflow" "$crate_dir/$workflow"
|
||||||
|
ok "→ $workflow replaced with the template of its kind"
|
||||||
|
else
|
||||||
|
err "✗ $workflow differs from the template of its kind: the release CI is out of date"
|
||||||
|
diff <(norm "$crate_dir/$workflow") <(norm "$template/$workflow") >&2 || true
|
||||||
|
info " Replace it: cp $template/$workflow $crate_dir/$workflow"
|
||||||
|
info " (keep a deliberate customization by adding the line \"# kit-workflow: custom\" to the workflow)"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ ! -x "$kit_src/tools/kit-assemble.sh" ]; then
|
||||||
|
info " (reference kit not found: $kit_src, check skipped)"
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
ref="$(mktemp -d "${TMPDIR:-/tmp}/kit-check.XXXXXX")"
|
||||||
|
trap 'rm -r "$ref"' EXIT
|
||||||
|
"$kit_src/tools/kit-assemble.sh" "$ref"
|
||||||
|
|
||||||
|
if diff -rq "$ref" "$kit_dir" >/dev/null 2>&1; then
|
||||||
|
ok "✓ Kit up to date (crate-kit $(cat "$ref/VERSION"))"
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
err "✗ This crate's kit is not the one from $kit_src:"
|
||||||
|
diff -rq "$ref" "$kit_dir" >&2 || true
|
||||||
|
info " Update: make kit-update"
|
||||||
|
exit 1
|
||||||
Executable
+77
@@ -0,0 +1,77 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Is there, in the crate's jj working copy (current directory), a change that justifies a
|
||||||
|
# commit, that is, something other than what the kit itself produces or modifies? Read-only.
|
||||||
|
#
|
||||||
|
# Do not count:
|
||||||
|
# - .crate-kit/ (kit copy) and .cargo/ (generated local configuration);
|
||||||
|
# - a template file (.gitea/workflows/release.yaml, LICENSE, .gitignore, Makefile…) identical to
|
||||||
|
# that of the kind's template (<extension>/templates/<kind>, otherwise crate-kit/template): adopt.sh laid it down as is;
|
||||||
|
# - Cargo.lock when only the `version` line of the crate itself changed (version bump);
|
||||||
|
# - the Makefile when only its kit bootstrap lines changed (KIT_SRC, copy or sync of
|
||||||
|
# .crate-kit/, comments that talk about the kit): the rest (description, PLUGIN_ID…) belongs to the crate.
|
||||||
|
# Without a crate-kit repository alongside ($KIT_SRC), the second filter cannot apply: these files
|
||||||
|
# then count as changes.
|
||||||
|
#
|
||||||
|
# Output: one file per line on standard output. Code 0 if there are any, 1 otherwise (nothing to commit).
|
||||||
|
set -euo pipefail
|
||||||
|
. "$(dirname "$0")/common.sh"
|
||||||
|
|
||||||
|
kit_src="${KIT_SRC:-../crate-kit}"
|
||||||
|
kind="${CRATE_KIND:-}"
|
||||||
|
if [ -z "$kind" ] && [ -f Makefile ]; then
|
||||||
|
kind=$(sed -n 's/^CRATE_KIND *[:?]*= *\([a-z]*\).*/\1/p' Makefile | head -n 1)
|
||||||
|
fi
|
||||||
|
template="$("$kit_src/tools/kit-assemble.sh" --root)/template"
|
||||||
|
overlay=$("$kit_src/tools/kit-assemble.sh" --overlay 2>/dev/null || true)
|
||||||
|
[ -n "$kind" ] && [ -n "$overlay" ] && [ -d "$overlay/templates/$kind" ] && template="$overlay/templates/$kind"
|
||||||
|
|
||||||
|
# Cargo.lock: did only the `version` line of the crate's package change?
|
||||||
|
lock_is_version_bump() {
|
||||||
|
local name
|
||||||
|
name=$(crate_name)
|
||||||
|
jj diff --git --context 1 Cargo.lock 2>/dev/null | awk -v name="$name" '
|
||||||
|
/^(\+\+\+|---)/ { next }
|
||||||
|
/^@@/ { prev = ""; next }
|
||||||
|
/^[-+]/ {
|
||||||
|
changed++
|
||||||
|
if ($0 !~ /^[-+]version = / || prev != " name = \"" name "\"") bad = 1
|
||||||
|
next
|
||||||
|
}
|
||||||
|
/^ / { prev = $0 }
|
||||||
|
END { exit (changed > 0 && !bad) ? 0 : 1 }'
|
||||||
|
}
|
||||||
|
|
||||||
|
# Makefile: did only the kit bootstrap lines change? Those that name KIT_SRC or
|
||||||
|
# `crate-kit` (variable, sync, copy of .crate-kit/) and the comments that talk about the kit; a
|
||||||
|
# modification of any other line (description, PLUGIN_ID, targets) is a real change of the crate.
|
||||||
|
makefile_is_kit_bootstrap() {
|
||||||
|
jj diff --git --context 1 Makefile 2>/dev/null | awk '
|
||||||
|
/^(\+\+\+|---)/ { next }
|
||||||
|
/^[-+]/ {
|
||||||
|
changed++
|
||||||
|
if ($0 !~ /KIT_SRC|crate-kit|kit-copy|^[-+]# .*[Kk]it/) bad = 1
|
||||||
|
}
|
||||||
|
END { exit (changed > 0 && !bad) ? 0 : 1 }'
|
||||||
|
}
|
||||||
|
|
||||||
|
found=0
|
||||||
|
while IFS= read -r line; do
|
||||||
|
# Format of `jj diff --summary`: "M path"; a rename "R {a => b}" remains a change.
|
||||||
|
path="${line#? }"
|
||||||
|
case "$path" in
|
||||||
|
.crate-kit/* | .cargo/*) continue ;;
|
||||||
|
Cargo.lock)
|
||||||
|
if lock_is_version_bump; then continue; fi
|
||||||
|
;;
|
||||||
|
Makefile)
|
||||||
|
if makefile_is_kit_bootstrap; then continue; fi
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
if [ "${line%% *}" = M ] && [ -f "$template/$path" ] && cmp -s "$template/$path" "$path"; then
|
||||||
|
continue
|
||||||
|
fi
|
||||||
|
echo "$path"
|
||||||
|
found=1
|
||||||
|
done < <(jj diff --summary)
|
||||||
|
|
||||||
|
[ "$found" -eq 1 ] || { info " nothing to commit outside the kit" ; exit 1; }
|
||||||
Executable
+14
@@ -0,0 +1,14 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Starts a new working commit (`jj new`), unless @ already is a blank one (empty, without a description).
|
||||||
|
# After a push of main, @ is usually already blank: when the pushed commit was @, it became immutable and jj
|
||||||
|
# itself created an empty working commit on top of it (operation "push bookmark main"). An unconditional
|
||||||
|
# `jj new` would then stack a second, useless empty commit.
|
||||||
|
set -euo pipefail
|
||||||
|
. "$(dirname "$0")/common.sh"
|
||||||
|
|
||||||
|
blank=$(jj log -r @ --no-graph -T 'if(empty && description == "", "1", "0")')
|
||||||
|
if [ "$blank" = 1 ]; then
|
||||||
|
info " (@ is already an empty working commit: no new commit)"
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
jj new
|
||||||
Executable
+12
@@ -0,0 +1,12 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Safeguard: a crate published on a private registry declares `publish = ["<registry>"]` in its
|
||||||
|
# Cargo.toml, so that cargo itself refuses any publication elsewhere (crates.io for example).
|
||||||
|
# Not applicable: kind without publication (PUBLISH=no), registry absent or crates-io.
|
||||||
|
set -euo pipefail
|
||||||
|
. "$(dirname "$0")/common.sh"
|
||||||
|
[ "${PUBLISH:-yes}" = no ] && exit 0
|
||||||
|
{ [ -n "$REGISTRY" ] && [ "$REGISTRY" != crates-io ]; } || exit 0
|
||||||
|
[ -f "$CARGO_TOML" ] || exit 0
|
||||||
|
grep -qE "^publish[[:space:]]*=[[:space:]]*\[[[:space:]]*\"$REGISTRY\"[[:space:]]*\]" "$CARGO_TOML" && exit 0
|
||||||
|
err "✗ $CARGO_TOML : publish = [\"$REGISTRY\"] missing in [package] (without it, cargo publish would accept crates.io)"
|
||||||
|
exit 1
|
||||||
Executable
+38
@@ -0,0 +1,38 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Publishes the current version on the $REGISTRY registry (private, or crates-io with CARGO_REGISTRY_TOKEN).
|
||||||
|
# DRY_RUN non-empty: assembles and builds the package without sending it.
|
||||||
|
#
|
||||||
|
# Idempotent: if the version is already published, it is a success (allows replaying the release
|
||||||
|
# workflow after a later failure). Authentication: variable CARGO_REGISTRIES_<REGISTRY>_TOKEN
|
||||||
|
# ("Bearer <token>"), otherwise built from the forge token (forge_token: FORGETOKEN in CI).
|
||||||
|
#
|
||||||
|
# --allow-dirty: in a colocated jj repository, git always sees the working copy as
|
||||||
|
# modified relative to its HEAD, even when the jj commit is already pushed.
|
||||||
|
set -euo pipefail
|
||||||
|
. "$(dirname "$0")/common.sh"
|
||||||
|
|
||||||
|
if [ "${PUBLISH:-yes}" = no ]; then
|
||||||
|
info " (kind ${CRATE_KIND:-crate}: nothing to publish on the registry)"
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
[ -n "$REGISTRY" ] || { err "✗ no registry: declare the kit extension (KIT_OVERLAY in the Makefile, org.mk) or set REGISTRY = crates-io"; exit 1; }
|
||||||
|
version=$(current_version)
|
||||||
|
name=$(crate_name)
|
||||||
|
if [ -n "${DRY_RUN:-}" ]; then
|
||||||
|
warn "→ Checking the publication of $name $version (without sending)..."
|
||||||
|
"$CARGO" publish --registry "$REGISTRY" --allow-dirty --dry-run
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
warn "→ Publishing $name $version on registry $REGISTRY..."
|
||||||
|
log=$(mktemp)
|
||||||
|
trap 'rm -f -- "$log"' EXIT
|
||||||
|
if "$CARGO" publish --registry "$REGISTRY" --allow-dirty 2>&1 | tee "$log" >&2; then
|
||||||
|
ok "✓ $name $version published"
|
||||||
|
elif grep -qiE 'already (exists|uploaded)|crate version .* is already' "$log"; then
|
||||||
|
warn " $name $version is already published on $REGISTRY: nothing to do"
|
||||||
|
else
|
||||||
|
err "✗ Publication of $name $version failed"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
Executable
+16
@@ -0,0 +1,16 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Advances the main bookmark to the current commit (@, or its first non-empty ancestor if @ is an
|
||||||
|
# empty working commit without a description: release_rev) and pushes it: no PR branch, main receives
|
||||||
|
# the commit directly. Moving main must be a fast-forward (jj refuses otherwise): if
|
||||||
|
# main@origin has advanced, `make jjfetch` first rebases the local work onto it.
|
||||||
|
set -euo pipefail
|
||||||
|
. "$(dirname "$0")/common.sh"
|
||||||
|
|
||||||
|
abandon_blank_commits
|
||||||
|
rev=$(release_rev)
|
||||||
|
if ! jj bookmark set main -r "$rev" 2>/dev/null; then
|
||||||
|
err "✗ main cannot advance to $rev (main has diverged or $rev does not descend from it)"
|
||||||
|
info " Run make jjfetch to rebase the work onto main@origin, then start again."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
jj git push --bookmark main
|
||||||
Executable
+24
@@ -0,0 +1,24 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Generates $RELEASE_NOTES_DIR/version-<version>.md: notes produced by `jj release-notes`
|
||||||
|
# (fallback to one line if they fail, e.g. before the first tag), then adds a
|
||||||
|
# "Public API" section with the snapshot diff since the previous version.
|
||||||
|
set -euo pipefail
|
||||||
|
. "$(dirname "$0")/common.sh"
|
||||||
|
|
||||||
|
version=$(current_version)
|
||||||
|
notes="$RELEASE_NOTES_DIR/version-$version.md"
|
||||||
|
info "→ Generating the release notes ($notes)..."
|
||||||
|
mkdir -p "$RELEASE_NOTES_DIR"
|
||||||
|
|
||||||
|
PMOJJ_RELEASE_LANG="${KIT_LANG:-en}" PMOJJ_RELEASE_PROJECT="${RELEASE_PROJECT_DESC:-$(crate_name)}" jj release-notes --release "$version" >"$notes" ||
|
||||||
|
echo "Release version-$version" >"$notes"
|
||||||
|
|
||||||
|
prev=$(ls "$API_DIR"/*.txt 2>/dev/null | sed 's|.*/||; s|\.txt$||' | sort -V |
|
||||||
|
grep -v -x "$version" | tail -n 1 || true)
|
||||||
|
if [ -n "$prev" ] && [ -f "$API_DIR/$version.txt" ]; then
|
||||||
|
api_diff=$(diff <(filter_notes "$API_DIR/$prev.txt") <(filter_notes "$API_DIR/$version.txt") | grep '^[<>]' || true)
|
||||||
|
if [ -n "$api_diff" ]; then
|
||||||
|
printf '\n## Public API (changes since %s)\n\n```diff\n%s\n```\n' \
|
||||||
|
"$prev" "$api_diff" >>"$notes"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
Executable
+17
@@ -0,0 +1,17 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Does the release tag `version-<version>` already exist (locally or on origin)? jj only, no git command.
|
||||||
|
# Usage: tag-exists.sh <version>
|
||||||
|
# Exit: 0 = the tag exists, 1 = it does not, 2 = not checked (no jj repository, origin unreachable).
|
||||||
|
# jj has no equivalent of `ls-remote`: the tag alone is fetched (`jj git fetch --tag`), which imports it as a
|
||||||
|
# tracked remote tag if it exists on origin and changes nothing else, then `jj tag list` tells.
|
||||||
|
set -uo pipefail
|
||||||
|
|
||||||
|
version="${1:?usage: tag-exists.sh <version>}"
|
||||||
|
tag="version-$version"
|
||||||
|
|
||||||
|
jj root >/dev/null 2>&1 || exit 2
|
||||||
|
jj git fetch --tag "exact:$tag" >/dev/null 2>&1 || exit 2
|
||||||
|
if [ -n "$(jj tag list "exact:$tag" -T 'name ++ "\n"' 2>/dev/null)" ]; then
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
exit 1
|
||||||
Executable
+20
@@ -0,0 +1,20 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Creates and pushes the tag version-<version> on the published commit (release_rev: @, or its first
|
||||||
|
# non-empty ancestor), with jj only. The tag is lightweight (jj creates no annotated tag): the release notes
|
||||||
|
# are not its message but the file $RELEASE_NOTES_DIR/version-<version>.md committed in the tagged revision,
|
||||||
|
# which forgejo-release.sh reads in the CI as the body of the release.
|
||||||
|
set -euo pipefail
|
||||||
|
. "$(dirname "$0")/common.sh"
|
||||||
|
|
||||||
|
version=$(current_version)
|
||||||
|
tag="version-$version"
|
||||||
|
notes="$RELEASE_NOTES_DIR/$tag.md"
|
||||||
|
[ -f "$notes" ] || { err "✗ release notes missing: $notes (make release-notes)"; exit 1; }
|
||||||
|
if [ -n "$(jj tag list "exact:$tag" 2>/dev/null)" ]; then
|
||||||
|
err "✗ tag $tag already exists"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
rev=$(release_rev)
|
||||||
|
jj tag set "$tag" -r "$rev"
|
||||||
|
jj git push --tag "exact:$tag"
|
||||||
|
ok "✓ Release $tag published"
|
||||||
Executable
+141
@@ -0,0 +1,141 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Publishes the API documentation (rustdoc -> JSON -> Markdown) to the crate's Forgejo wiki.
|
||||||
|
#
|
||||||
|
# The Forgejo wiki is a second repository (<repository>.wiki.git). It is never kept: the script
|
||||||
|
# clones it into a temporary directory (git), replaces the generated pages, commits and pushes, then
|
||||||
|
# removes the clone. Works identically locally and in the CI (release workflow).
|
||||||
|
#
|
||||||
|
# Pages produced: Home.md (module index), _Sidebar.md, one page per module.
|
||||||
|
# The wiki content is ENTIRELY replaced: any page written by hand on the Forgejo side
|
||||||
|
# disappears at the next run.
|
||||||
|
#
|
||||||
|
# Variables:
|
||||||
|
# WIKI_URL wiki repository URL (default: `origin` URL with .git replaced by .wiki.git)
|
||||||
|
# WIKI_TOKEN access token (CI, https URL): sent in the header "Authorization: token …"
|
||||||
|
# GIT_USER_NAME / GIT_USER_EMAIL commit identity if git has none configured
|
||||||
|
# DRY_RUN non-empty: generates and commits in the temporary clone, shows the diff, does not push
|
||||||
|
#
|
||||||
|
# Prerequisites: cargo-doc-md (cargo install cargo-doc-md --locked); the wiki must exist on the
|
||||||
|
# Forgejo side (create a first page by hand once per crate, otherwise the repository is not found).
|
||||||
|
set -euo pipefail
|
||||||
|
. "$(dirname "$0")/common.sh"
|
||||||
|
|
||||||
|
if [ "${WIKI:-yes}" = no ]; then
|
||||||
|
info " (kind ${CRATE_KIND:-crate}: no API documentation for the wiki)"
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
require_cargo_tool doc-md cargo-doc-md
|
||||||
|
|
||||||
|
name=$(crate_name)
|
||||||
|
version=$(current_version)
|
||||||
|
|
||||||
|
# Wiki URL: that of origin, with .git replaced by .wiki.git.
|
||||||
|
if [ -z "${WIKI_URL:-}" ]; then
|
||||||
|
origin=$(git remote get-url origin 2>/dev/null || true)
|
||||||
|
[ -n "$origin" ] || { err "✗ remote origin not found: set WIKI_URL=..."; exit 1; }
|
||||||
|
WIKI_URL="${origin%.git}.wiki.git"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Common git options: token in a header (CI) and fallback identity.
|
||||||
|
git_opts=()
|
||||||
|
if [ -n "${WIKI_TOKEN:-}" ]; then
|
||||||
|
git_opts+=(-c "http.extraHeader=Authorization: token $WIKI_TOKEN")
|
||||||
|
fi
|
||||||
|
if [ -z "$(git config user.name 2>/dev/null || true)" ]; then
|
||||||
|
git_opts+=(-c "user.name=${GIT_USER_NAME:-crate-kit}")
|
||||||
|
fi
|
||||||
|
if [ -z "$(git config user.email 2>/dev/null || true)" ]; then
|
||||||
|
git_opts+=(-c "user.email=${GIT_USER_EMAIL:-crate-kit@localhost}")
|
||||||
|
fi
|
||||||
|
wgit() { git "${git_opts[@]}" "$@"; }
|
||||||
|
|
||||||
|
work=$(mktemp -d "${TMPDIR:-/tmp}/crate-kit-wiki.XXXXXX")
|
||||||
|
[ -n "$work" ] && [ -d "$work" ] || { err "✗ temporary directory not created"; exit 1; }
|
||||||
|
trap 'rm -rf -- "$work"' EXIT
|
||||||
|
|
||||||
|
# 1. Rustdoc -> Markdown (one file per module, in $work/md/<crate>/).
|
||||||
|
info "→ Generating the Markdown ($name $version)..."
|
||||||
|
"$CARGO" doc-md --no-deps -o "$work/md" >&2
|
||||||
|
src="$work/md/$name"
|
||||||
|
[ -f "$src/index.md" ] || {
|
||||||
|
# The folder name follows the library name (hyphens -> underscores).
|
||||||
|
src="$work/md/${name//-/_}"
|
||||||
|
[ -f "$src/index.md" ] || { err "✗ index.md not found in $work/md"; exit 1; }
|
||||||
|
}
|
||||||
|
|
||||||
|
# 2. Wiki pages: flat, links between pages without the .md extension (Forgejo wiki convention).
|
||||||
|
pages="$work/pages"
|
||||||
|
mkdir -p "$pages"
|
||||||
|
for f in "$src"/*.md; do
|
||||||
|
base=$(basename "$f")
|
||||||
|
[ "$base" = index.md ] && continue
|
||||||
|
cp "$f" "$pages/$base"
|
||||||
|
done
|
||||||
|
# Home = crate index as produced by cargo-doc-md (title, crate doc, modules);
|
||||||
|
# the version appears in the sidebar.
|
||||||
|
sed -E 's/\]\(([^)#]+)\.md\)/](\1)/g' "$src/index.md" >"$pages/Home.md"
|
||||||
|
{
|
||||||
|
printf '**[%s](Home)** %s\n\n' "$name" "$version"
|
||||||
|
sed -nE 's/^### \[`([^`]+)`\]\(([^)]+)\.md\).*/- [\1](\2)/p' "$src/index.md"
|
||||||
|
} >"$pages/_Sidebar.md"
|
||||||
|
|
||||||
|
# Rustdoc intra-doc links (``[`item`]``, ``[`module::item`]``): cargo-doc-md does not resolve them
|
||||||
|
# and leaves them in literal brackets. We resolve them here to the wiki page that defines
|
||||||
|
# the item (table built from the "Contents" of each module page); a module
|
||||||
|
# points to its own page. Names not found (std, other crates) lose their
|
||||||
|
# brackets and remain as code.
|
||||||
|
map="$work/map"
|
||||||
|
: >"$map"
|
||||||
|
for f in "$pages"/*.md; do
|
||||||
|
p=$(basename "$f" .md)
|
||||||
|
case "$p" in Home | _Sidebar) continue ;; esac
|
||||||
|
echo "$p $p" >>"$map"
|
||||||
|
done
|
||||||
|
for f in "$pages"/*.md; do
|
||||||
|
p=$(basename "$f" .md)
|
||||||
|
case "$p" in Home | _Sidebar) continue ;; esac
|
||||||
|
sed -nE 's/^- \[`([A-Za-z0-9_]+)`\]\(#.*/\1 '"$p"'/p' "$f" >>"$map"
|
||||||
|
done
|
||||||
|
resolve="$work/resolve.sed"
|
||||||
|
: >"$resolve"
|
||||||
|
while read -r item page; do
|
||||||
|
# First wins: the module pages (lines at the start) take precedence; an item already
|
||||||
|
# turned into a link is no longer a candidate (it is followed by "(").
|
||||||
|
printf 's/\\[`((([A-Za-z0-9_]+::)*)%s)`\\]([^(:[]|$)/[`\\1`](%s)\\4/g\n' "$item" "$page" >>"$resolve"
|
||||||
|
done <"$map"
|
||||||
|
for f in "$pages"/*.md; do
|
||||||
|
sed -E -f "$resolve" "$f" | sed -E 's/\[(`[^`]+`)\]([^(:[]|$)/\1\2/g' >"$f.tmp"
|
||||||
|
mv "$f.tmp" "$f"
|
||||||
|
done
|
||||||
|
|
||||||
|
# 3. Clone the wiki, replace the pages, commit, push.
|
||||||
|
info "→ Cloning the wiki ${WIKI_URL}..."
|
||||||
|
clone="$work/clone"
|
||||||
|
wgit clone --quiet "$WIKI_URL" "$clone" >&2 || {
|
||||||
|
err "✗ cannot clone: does the wiki exist? (create a first page on Forgejo)"
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
cd "$clone"
|
||||||
|
|
||||||
|
# Default branch of the wiki (master or main depending on the instance): the one the clone checked out.
|
||||||
|
branch=$(git symbolic-ref --short HEAD)
|
||||||
|
|
||||||
|
# The generated files replace all the .md; the rest (images…) is kept.
|
||||||
|
find . -maxdepth 1 -name '*.md' -type f -delete
|
||||||
|
cp "$pages"/*.md .
|
||||||
|
git add -A
|
||||||
|
|
||||||
|
if [ -z "$(git status --porcelain)" ]; then
|
||||||
|
ok "✓ Wiki already up to date"
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
git diff --cached --stat >&2
|
||||||
|
wgit commit --quiet -m "API documentation: $name $version"
|
||||||
|
if [ -n "${DRY_RUN:-}" ]; then
|
||||||
|
warn "→ DRY_RUN: local commit in the temporary clone, nothing is pushed"
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
wgit push --quiet origin "$branch" >&2
|
||||||
|
ok "✓ Wiki of $name updated ($version)"
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
name: Release
|
||||||
|
|
||||||
|
# Triggered by the version-x.y.z tag that `make jjrelease` pushes. The workflow publishes the crate to
|
||||||
|
# the private registry, updates the wiki, then creates the Forgejo release with the tag notes.
|
||||||
|
# Each step is replayable: rerunning the workflow after a failure is safe.
|
||||||
|
#
|
||||||
|
# Repository secret: FORGETOKEN (Forgejo token with write rights on the packages,
|
||||||
|
# the repository, the wiki and the releases).
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
tags:
|
||||||
|
- "version-*"
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
release:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
timeout-minutes: 30
|
||||||
|
env:
|
||||||
|
FORGETOKEN: ${{ secrets.FORGETOKEN }}
|
||||||
|
TAG: ${{ github.ref_name }}
|
||||||
|
SERVER: ${{ github.server_url }}
|
||||||
|
REPO: ${{ github.repository }}
|
||||||
|
WIKI_TOKEN: ${{ secrets.FORGETOKEN }}
|
||||||
|
steps:
|
||||||
|
- name: System tools
|
||||||
|
run: |
|
||||||
|
apt-get update -qq
|
||||||
|
apt-get install -y -qq git curl jq make build-essential pkg-config
|
||||||
|
|
||||||
|
- name: Version sources
|
||||||
|
run: |
|
||||||
|
git -c http.extraHeader="Authorization: token $FORGETOKEN" \
|
||||||
|
clone --depth 1 --branch "$TAG" "$SERVER/$REPO.git" src
|
||||||
|
|
||||||
|
- name: Rust
|
||||||
|
run: |
|
||||||
|
curl -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain stable
|
||||||
|
. "$HOME/.cargo/env"
|
||||||
|
cargo install cargo-doc-md --locked
|
||||||
|
|
||||||
|
- name: Publish to the private registry
|
||||||
|
working-directory: src
|
||||||
|
run: |
|
||||||
|
. "$HOME/.cargo/env"
|
||||||
|
make publish
|
||||||
|
|
||||||
|
- name: Update the wiki
|
||||||
|
working-directory: src
|
||||||
|
run: |
|
||||||
|
. "$HOME/.cargo/env"
|
||||||
|
make wiki
|
||||||
|
|
||||||
|
- name: Create the Forgejo release
|
||||||
|
working-directory: src
|
||||||
|
run: .crate-kit/scripts/forgejo-release.sh
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
target
|
||||||
|
/.cargo/config.toml
|
||||||
Generated
+25
@@ -0,0 +1,25 @@
|
|||||||
|
# This file is automatically @generated by Cargo.
|
||||||
|
# It is not intended for manual editing.
|
||||||
|
version = 4
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "crossbeam-channel"
|
||||||
|
version = "0.5.17"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "98b0cc327b5bc766e7fda9c9260cc0fa81b43a8e240440422dff70788e3f9ef1"
|
||||||
|
dependencies = [
|
||||||
|
"crossbeam-utils",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "crossbeam-utils"
|
||||||
|
version = "0.8.23"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "obipipeline"
|
||||||
|
version = "0.1.1"
|
||||||
|
dependencies = [
|
||||||
|
"crossbeam-channel",
|
||||||
|
]
|
||||||
+14
@@ -0,0 +1,14 @@
|
|||||||
|
[package]
|
||||||
|
name = "obipipeline"
|
||||||
|
version = "0.1.1"
|
||||||
|
edition = "2024"
|
||||||
|
description = "Typed, composable multi-threaded pipelines over channels, with memory-bounded throttling of iterators"
|
||||||
|
repository = "https://forge.metabarcoding.org/obi/obipipeline"
|
||||||
|
license = "CECILL-2.1"
|
||||||
|
readme = "README.md"
|
||||||
|
keywords = ["pipeline", "parallel", "threads", "channels", "throttle"]
|
||||||
|
categories = ["concurrency"]
|
||||||
|
publish = ["obi"]
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
crossbeam-channel = "0.5.15"
|
||||||
@@ -0,0 +1,550 @@
|
|||||||
|
|
||||||
|
CONTRAT DE LICENCE DE LOGICIEL LIBRE CeCILL
|
||||||
|
|
||||||
|
Version 2.1 du 2013-06-21
|
||||||
|
|
||||||
|
|
||||||
|
Avertissement
|
||||||
|
|
||||||
|
Ce contrat est une licence de logiciel libre issue d'une concertation
|
||||||
|
entre ses auteurs afin que le respect de deux grands principes préside à
|
||||||
|
sa rédaction:
|
||||||
|
|
||||||
|
* d'une part, le respect des principes de diffusion des logiciels
|
||||||
|
libres: accès au code source, droits étendus conférés aux utilisateurs,
|
||||||
|
* d'autre part, la désignation d'un droit applicable, le droit
|
||||||
|
français, auquel elle est conforme, tant au regard du droit de la
|
||||||
|
responsabilité civile que du droit de la propriété intellectuelle et
|
||||||
|
de la protection qu'il offre aux auteurs et titulaires des droits
|
||||||
|
patrimoniaux sur un logiciel.
|
||||||
|
|
||||||
|
Les auteurs de la licence CeCILL (Ce[a] C[nrs] I[nria] L[ogiciel] L[ibre])
|
||||||
|
sont:
|
||||||
|
|
||||||
|
Commissariat à l'énergie atomique et aux énergies alternatives - CEA,
|
||||||
|
établissement public de recherche à caractère scientifique, technique et
|
||||||
|
industriel, dont le siège est situé 25 rue Leblanc, immeuble Le Ponant
|
||||||
|
D, 75015 Paris.
|
||||||
|
|
||||||
|
Centre National de la Recherche Scientifique - CNRS, établissement
|
||||||
|
public à caractère scientifique et technologique, dont le siège est
|
||||||
|
situé 3 rue Michel-Ange, 75794 Paris cedex 16.
|
||||||
|
|
||||||
|
Institut National de Recherche en Informatique et en Automatique -
|
||||||
|
Inria, établissement public à caractère scientifique et technologique,
|
||||||
|
dont le siège est situé Domaine de Voluceau, Rocquencourt, BP 105, 78153
|
||||||
|
Le Chesnay cedex.
|
||||||
|
|
||||||
|
|
||||||
|
Préambule
|
||||||
|
|
||||||
|
Ce contrat est une licence de logiciel libre dont l'objectif est de
|
||||||
|
conférer aux utilisateurs la liberté de modification et de
|
||||||
|
redistribution du logiciel régi par cette licence dans le cadre d'un
|
||||||
|
modèle de diffusion en logiciel libre.
|
||||||
|
|
||||||
|
L'exercice de ces libertés est assorti de certains devoirs à la charge
|
||||||
|
des utilisateurs afin de préserver ce statut au cours des
|
||||||
|
redistributions ultérieures.
|
||||||
|
|
||||||
|
L'accessibilité au code source et les droits de copie, de modification
|
||||||
|
et de redistribution qui en découlent ont pour contrepartie de n'offrir
|
||||||
|
aux utilisateurs qu'une garantie limitée et de ne faire peser sur
|
||||||
|
l'auteur du logiciel, le titulaire des droits patrimoniaux et les
|
||||||
|
concédants successifs qu'une responsabilité restreinte.
|
||||||
|
|
||||||
|
A cet égard l'attention de l'utilisateur est attirée sur les risques
|
||||||
|
associés au chargement, à l'utilisation, à la modification et/ou au
|
||||||
|
développement et à la reproduction du logiciel par l'utilisateur étant
|
||||||
|
donné sa spécificité de logiciel libre, qui peut le rendre complexe à
|
||||||
|
manipuler et qui le réserve donc à des développeurs ou des
|
||||||
|
professionnels avertis possédant des connaissances informatiques
|
||||||
|
approfondies. Les utilisateurs sont donc invités à charger et tester
|
||||||
|
l'adéquation du logiciel à leurs besoins dans des conditions permettant
|
||||||
|
d'assurer la sécurité de leurs systèmes et/ou de leurs données et, plus
|
||||||
|
généralement, à l'utiliser et l'exploiter dans les mêmes conditions de
|
||||||
|
sécurité. Ce contrat peut être reproduit et diffusé librement, sous
|
||||||
|
réserve de le conserver en l'état, sans ajout ni suppression de clauses.
|
||||||
|
|
||||||
|
Ce contrat est susceptible de s'appliquer à tout logiciel dont le
|
||||||
|
titulaire des droits patrimoniaux décide de soumettre l'exploitation aux
|
||||||
|
dispositions qu'il contient.
|
||||||
|
|
||||||
|
Une liste de questions fréquemment posées se trouve sur le site web
|
||||||
|
officiel de la famille des licences CeCILL
|
||||||
|
(http://www.cecill.info/index.fr.html) pour toute clarification qui
|
||||||
|
serait nécessaire.
|
||||||
|
|
||||||
|
|
||||||
|
Article 1 - DEFINITIONS
|
||||||
|
|
||||||
|
Dans ce contrat, les termes suivants, lorsqu'ils seront écrits avec une
|
||||||
|
lettre capitale, auront la signification suivante:
|
||||||
|
|
||||||
|
Contrat: désigne le présent contrat de licence, ses éventuelles versions
|
||||||
|
postérieures et annexes.
|
||||||
|
|
||||||
|
Logiciel: désigne le logiciel sous sa forme de Code Objet et/ou de Code
|
||||||
|
Source et le cas échéant sa documentation, dans leur état au moment de
|
||||||
|
l'acceptation du Contrat par le Licencié.
|
||||||
|
|
||||||
|
Logiciel Initial: désigne le Logiciel sous sa forme de Code Source et
|
||||||
|
éventuellement de Code Objet et le cas échéant sa documentation, dans
|
||||||
|
leur état au moment de leur première diffusion sous les termes du Contrat.
|
||||||
|
|
||||||
|
Logiciel Modifié: désigne le Logiciel modifié par au moins une
|
||||||
|
Contribution.
|
||||||
|
|
||||||
|
Code Source: désigne l'ensemble des instructions et des lignes de
|
||||||
|
programme du Logiciel et auquel l'accès est nécessaire en vue de
|
||||||
|
modifier le Logiciel.
|
||||||
|
|
||||||
|
Code Objet: désigne les fichiers binaires issus de la compilation du
|
||||||
|
Code Source.
|
||||||
|
|
||||||
|
Titulaire: désigne le ou les détenteurs des droits patrimoniaux d'auteur
|
||||||
|
sur le Logiciel Initial.
|
||||||
|
|
||||||
|
Licencié: désigne le ou les utilisateurs du Logiciel ayant accepté le
|
||||||
|
Contrat.
|
||||||
|
|
||||||
|
Contributeur: désigne le Licencié auteur d'au moins une Contribution.
|
||||||
|
|
||||||
|
Concédant: désigne le Titulaire ou toute personne physique ou morale
|
||||||
|
distribuant le Logiciel sous le Contrat.
|
||||||
|
|
||||||
|
Contribution: désigne l'ensemble des modifications, corrections,
|
||||||
|
traductions, adaptations et/ou nouvelles fonctionnalités intégrées dans
|
||||||
|
le Logiciel par tout Contributeur, ainsi que tout Module Interne.
|
||||||
|
|
||||||
|
Module: désigne un ensemble de fichiers sources y compris leur
|
||||||
|
documentation qui permet de réaliser des fonctionnalités ou services
|
||||||
|
supplémentaires à ceux fournis par le Logiciel.
|
||||||
|
|
||||||
|
Module Externe: désigne tout Module, non dérivé du Logiciel, tel que ce
|
||||||
|
Module et le Logiciel s'exécutent dans des espaces d'adressage
|
||||||
|
différents, l'un appelant l'autre au moment de leur exécution.
|
||||||
|
|
||||||
|
Module Interne: désigne tout Module lié au Logiciel de telle sorte
|
||||||
|
qu'ils s'exécutent dans le même espace d'adressage.
|
||||||
|
|
||||||
|
GNU GPL: désigne la GNU General Public License dans sa version 2 ou
|
||||||
|
toute version ultérieure, telle que publiée par Free Software Foundation
|
||||||
|
Inc.
|
||||||
|
|
||||||
|
GNU Affero GPL: désigne la GNU Affero General Public License dans sa
|
||||||
|
version 3 ou toute version ultérieure, telle que publiée par Free
|
||||||
|
Software Foundation Inc.
|
||||||
|
|
||||||
|
EUPL: désigne la Licence Publique de l'Union européenne dans sa version
|
||||||
|
1.1 ou toute version ultérieure, telle que publiée par la Commission
|
||||||
|
Européenne.
|
||||||
|
|
||||||
|
Parties: désigne collectivement le Licencié et le Concédant.
|
||||||
|
|
||||||
|
Ces termes s'entendent au singulier comme au pluriel.
|
||||||
|
|
||||||
|
|
||||||
|
Article 2 - OBJET
|
||||||
|
|
||||||
|
Le Contrat a pour objet la concession par le Concédant au Licencié d'une
|
||||||
|
licence non exclusive, cessible et mondiale du Logiciel telle que
|
||||||
|
définie ci-après à l'article 5 <#etendue> pour toute la durée de
|
||||||
|
protection des droits portant sur ce Logiciel.
|
||||||
|
|
||||||
|
|
||||||
|
Article 3 - ACCEPTATION
|
||||||
|
|
||||||
|
3.1 L'acceptation par le Licencié des termes du Contrat est réputée
|
||||||
|
acquise du fait du premier des faits suivants:
|
||||||
|
|
||||||
|
* (i) le chargement du Logiciel par tout moyen notamment par
|
||||||
|
téléchargement à partir d'un serveur distant ou par chargement à
|
||||||
|
partir d'un support physique;
|
||||||
|
* (ii) le premier exercice par le Licencié de l'un quelconque des
|
||||||
|
droits concédés par le Contrat.
|
||||||
|
|
||||||
|
3.2 Un exemplaire du Contrat, contenant notamment un avertissement
|
||||||
|
relatif aux spécificités du Logiciel, à la restriction de garantie et à
|
||||||
|
la limitation à un usage par des utilisateurs expérimentés a été mis à
|
||||||
|
disposition du Licencié préalablement à son acceptation telle que
|
||||||
|
définie à l'article 3.1 <#acceptation-acquise> ci dessus et le Licencié
|
||||||
|
reconnaît en avoir pris connaissance.
|
||||||
|
|
||||||
|
|
||||||
|
Article 4 - ENTREE EN VIGUEUR ET DUREE
|
||||||
|
|
||||||
|
|
||||||
|
4.1 ENTREE EN VIGUEUR
|
||||||
|
|
||||||
|
Le Contrat entre en vigueur à la date de son acceptation par le Licencié
|
||||||
|
telle que définie en 3.1 <#acceptation-acquise>.
|
||||||
|
|
||||||
|
|
||||||
|
4.2 DUREE
|
||||||
|
|
||||||
|
Le Contrat produira ses effets pendant toute la durée légale de
|
||||||
|
protection des droits patrimoniaux portant sur le Logiciel.
|
||||||
|
|
||||||
|
|
||||||
|
Article 5 - ETENDUE DES DROITS CONCEDES
|
||||||
|
|
||||||
|
Le Concédant concède au Licencié, qui accepte, les droits suivants sur
|
||||||
|
le Logiciel pour toutes destinations et pour la durée du Contrat dans
|
||||||
|
les conditions ci-après détaillées.
|
||||||
|
|
||||||
|
Par ailleurs, si le Concédant détient ou venait à détenir un ou
|
||||||
|
plusieurs brevets d'invention protégeant tout ou partie des
|
||||||
|
fonctionnalités du Logiciel ou de ses composants, il s'engage à ne pas
|
||||||
|
opposer les éventuels droits conférés par ces brevets aux Licenciés
|
||||||
|
successifs qui utiliseraient, exploiteraient ou modifieraient le
|
||||||
|
Logiciel. En cas de cession de ces brevets, le Concédant s'engage à
|
||||||
|
faire reprendre les obligations du présent alinéa aux cessionnaires.
|
||||||
|
|
||||||
|
|
||||||
|
5.1 DROIT D'UTILISATION
|
||||||
|
|
||||||
|
Le Licencié est autorisé à utiliser le Logiciel, sans restriction quant
|
||||||
|
aux domaines d'application, étant ci-après précisé que cela comporte:
|
||||||
|
|
||||||
|
1.
|
||||||
|
|
||||||
|
la reproduction permanente ou provisoire du Logiciel en tout ou
|
||||||
|
partie par tout moyen et sous toute forme.
|
||||||
|
|
||||||
|
2.
|
||||||
|
|
||||||
|
le chargement, l'affichage, l'exécution, ou le stockage du Logiciel
|
||||||
|
sur tout support.
|
||||||
|
|
||||||
|
3.
|
||||||
|
|
||||||
|
la possibilité d'en observer, d'en étudier, ou d'en tester le
|
||||||
|
fonctionnement afin de déterminer les idées et principes qui sont à
|
||||||
|
la base de n'importe quel élément de ce Logiciel; et ceci, lorsque
|
||||||
|
le Licencié effectue toute opération de chargement, d'affichage,
|
||||||
|
d'exécution, de transmission ou de stockage du Logiciel qu'il est en
|
||||||
|
droit d'effectuer en vertu du Contrat.
|
||||||
|
|
||||||
|
|
||||||
|
5.2 DROIT D'APPORTER DES CONTRIBUTIONS
|
||||||
|
|
||||||
|
Le droit d'apporter des Contributions comporte le droit de traduire,
|
||||||
|
d'adapter, d'arranger ou d'apporter toute autre modification au Logiciel
|
||||||
|
et le droit de reproduire le logiciel en résultant.
|
||||||
|
|
||||||
|
Le Licencié est autorisé à apporter toute Contribution au Logiciel sous
|
||||||
|
réserve de mentionner, de façon explicite, son nom en tant qu'auteur de
|
||||||
|
cette Contribution et la date de création de celle-ci.
|
||||||
|
|
||||||
|
|
||||||
|
5.3 DROIT DE DISTRIBUTION
|
||||||
|
|
||||||
|
Le droit de distribution comporte notamment le droit de diffuser, de
|
||||||
|
transmettre et de communiquer le Logiciel au public sur tout support et
|
||||||
|
par tout moyen ainsi que le droit de mettre sur le marché à titre
|
||||||
|
onéreux ou gratuit, un ou des exemplaires du Logiciel par tout procédé.
|
||||||
|
|
||||||
|
Le Licencié est autorisé à distribuer des copies du Logiciel, modifié ou
|
||||||
|
non, à des tiers dans les conditions ci-après détaillées.
|
||||||
|
|
||||||
|
|
||||||
|
5.3.1 DISTRIBUTION DU LOGICIEL SANS MODIFICATION
|
||||||
|
|
||||||
|
Le Licencié est autorisé à distribuer des copies conformes du Logiciel,
|
||||||
|
sous forme de Code Source ou de Code Objet, à condition que cette
|
||||||
|
distribution respecte les dispositions du Contrat dans leur totalité et
|
||||||
|
soit accompagnée:
|
||||||
|
|
||||||
|
1.
|
||||||
|
|
||||||
|
d'un exemplaire du Contrat,
|
||||||
|
|
||||||
|
2.
|
||||||
|
|
||||||
|
d'un avertissement relatif à la restriction de garantie et de
|
||||||
|
responsabilité du Concédant telle que prévue aux articles 8
|
||||||
|
<#responsabilite> et 9 <#garantie>,
|
||||||
|
|
||||||
|
et que, dans le cas où seul le Code Objet du Logiciel est redistribué,
|
||||||
|
le Licencié permette un accès effectif au Code Source complet du
|
||||||
|
Logiciel pour une durée d'au moins 3 ans à compter de la distribution du
|
||||||
|
logiciel, étant entendu que le coût additionnel d'acquisition du Code
|
||||||
|
Source ne devra pas excéder le simple coût de transfert des données.
|
||||||
|
|
||||||
|
|
||||||
|
5.3.2 DISTRIBUTION DU LOGICIEL MODIFIE
|
||||||
|
|
||||||
|
Lorsque le Licencié apporte une Contribution au Logiciel, les conditions
|
||||||
|
de distribution du Logiciel Modifié en résultant sont alors soumises à
|
||||||
|
l'intégralité des dispositions du Contrat.
|
||||||
|
|
||||||
|
Le Licencié est autorisé à distribuer le Logiciel Modifié, sous forme de
|
||||||
|
code source ou de code objet, à condition que cette distribution
|
||||||
|
respecte les dispositions du Contrat dans leur totalité et soit
|
||||||
|
accompagnée:
|
||||||
|
|
||||||
|
1.
|
||||||
|
|
||||||
|
d'un exemplaire du Contrat,
|
||||||
|
|
||||||
|
2.
|
||||||
|
|
||||||
|
d'un avertissement relatif à la restriction de garantie et de
|
||||||
|
responsabilité du Concédant telle que prévue aux articles 8
|
||||||
|
<#responsabilite> et 9 <#garantie>,
|
||||||
|
|
||||||
|
et, dans le cas où seul le code objet du Logiciel Modifié est redistribué,
|
||||||
|
|
||||||
|
3.
|
||||||
|
|
||||||
|
d'une note précisant les conditions d'accès effectif au code source
|
||||||
|
complet du Logiciel Modifié, pendant une période d'au moins 3 ans à
|
||||||
|
compter de la distribution du Logiciel Modifié, étant entendu que le
|
||||||
|
coût additionnel d'acquisition du code source ne devra pas excéder
|
||||||
|
le simple coût de transfert des données.
|
||||||
|
|
||||||
|
|
||||||
|
5.3.3 DISTRIBUTION DES MODULES EXTERNES
|
||||||
|
|
||||||
|
Lorsque le Licencié a développé un Module Externe les conditions du
|
||||||
|
Contrat ne s'appliquent pas à ce Module Externe, qui peut être distribué
|
||||||
|
sous un contrat de licence différent.
|
||||||
|
|
||||||
|
|
||||||
|
5.3.4 COMPATIBILITE AVEC D'AUTRES LICENCES
|
||||||
|
|
||||||
|
Le Licencié peut inclure un code soumis aux dispositions d'une des
|
||||||
|
versions de la licence GNU GPL, GNU Affero GPL et/ou EUPL dans le
|
||||||
|
Logiciel modifié ou non et distribuer l'ensemble sous les conditions de
|
||||||
|
la même version de la licence GNU GPL, GNU Affero GPL et/ou EUPL.
|
||||||
|
|
||||||
|
Le Licencié peut inclure le Logiciel modifié ou non dans un code soumis
|
||||||
|
aux dispositions d'une des versions de la licence GNU GPL, GNU Affero
|
||||||
|
GPL et/ou EUPL et distribuer l'ensemble sous les conditions de la même
|
||||||
|
version de la licence GNU GPL, GNU Affero GPL et/ou EUPL.
|
||||||
|
|
||||||
|
|
||||||
|
Article 6 - PROPRIETE INTELLECTUELLE
|
||||||
|
|
||||||
|
|
||||||
|
6.1 SUR LE LOGICIEL INITIAL
|
||||||
|
|
||||||
|
Le Titulaire est détenteur des droits patrimoniaux sur le Logiciel
|
||||||
|
Initial. Toute utilisation du Logiciel Initial est soumise au respect
|
||||||
|
des conditions dans lesquelles le Titulaire a choisi de diffuser son
|
||||||
|
oeuvre et nul autre n'a la faculté de modifier les conditions de
|
||||||
|
diffusion de ce Logiciel Initial.
|
||||||
|
|
||||||
|
Le Titulaire s'engage à ce que le Logiciel Initial reste au moins régi
|
||||||
|
par le Contrat et ce, pour la durée visée à l'article 4.2 <#duree>.
|
||||||
|
|
||||||
|
|
||||||
|
6.2 SUR LES CONTRIBUTIONS
|
||||||
|
|
||||||
|
Le Licencié qui a développé une Contribution est titulaire sur celle-ci
|
||||||
|
des droits de propriété intellectuelle dans les conditions définies par
|
||||||
|
la législation applicable.
|
||||||
|
|
||||||
|
|
||||||
|
6.3 SUR LES MODULES EXTERNES
|
||||||
|
|
||||||
|
Le Licencié qui a développé un Module Externe est titulaire sur celui-ci
|
||||||
|
des droits de propriété intellectuelle dans les conditions définies par
|
||||||
|
la législation applicable et reste libre du choix du contrat régissant
|
||||||
|
sa diffusion.
|
||||||
|
|
||||||
|
|
||||||
|
6.4 DISPOSITIONS COMMUNES
|
||||||
|
|
||||||
|
Le Licencié s'engage expressément:
|
||||||
|
|
||||||
|
1.
|
||||||
|
|
||||||
|
à ne pas supprimer ou modifier de quelque manière que ce soit les
|
||||||
|
mentions de propriété intellectuelle apposées sur le Logiciel;
|
||||||
|
|
||||||
|
2.
|
||||||
|
|
||||||
|
à reproduire à l'identique lesdites mentions de propriété
|
||||||
|
intellectuelle sur les copies du Logiciel modifié ou non.
|
||||||
|
|
||||||
|
Le Licencié s'engage à ne pas porter atteinte, directement ou
|
||||||
|
indirectement, aux droits de propriété intellectuelle du Titulaire et/ou
|
||||||
|
des Contributeurs sur le Logiciel et à prendre, le cas échéant, à
|
||||||
|
l'égard de son personnel toutes les mesures nécessaires pour assurer le
|
||||||
|
respect des dits droits de propriété intellectuelle du Titulaire et/ou
|
||||||
|
des Contributeurs.
|
||||||
|
|
||||||
|
|
||||||
|
Article 7 - SERVICES ASSOCIES
|
||||||
|
|
||||||
|
7.1 Le Contrat n'oblige en aucun cas le Concédant à la réalisation de
|
||||||
|
prestations d'assistance technique ou de maintenance du Logiciel.
|
||||||
|
|
||||||
|
Cependant le Concédant reste libre de proposer ce type de services. Les
|
||||||
|
termes et conditions d'une telle assistance technique et/ou d'une telle
|
||||||
|
maintenance seront alors déterminés dans un acte séparé. Ces actes de
|
||||||
|
maintenance et/ou assistance technique n'engageront que la seule
|
||||||
|
responsabilité du Concédant qui les propose.
|
||||||
|
|
||||||
|
7.2 De même, tout Concédant est libre de proposer, sous sa seule
|
||||||
|
responsabilité, à ses licenciés une garantie, qui n'engagera que lui,
|
||||||
|
lors de la redistribution du Logiciel et/ou du Logiciel Modifié et ce,
|
||||||
|
dans les conditions qu'il souhaite. Cette garantie et les modalités
|
||||||
|
financières de son application feront l'objet d'un acte séparé entre le
|
||||||
|
Concédant et le Licencié.
|
||||||
|
|
||||||
|
|
||||||
|
Article 8 - RESPONSABILITE
|
||||||
|
|
||||||
|
8.1 Sous réserve des dispositions de l'article 8.2
|
||||||
|
<#limite-responsabilite>, le Licencié a la faculté, sous réserve de
|
||||||
|
prouver la faute du Concédant concerné, de solliciter la réparation du
|
||||||
|
préjudice direct qu'il subirait du fait du Logiciel et dont il apportera
|
||||||
|
la preuve.
|
||||||
|
|
||||||
|
8.2 La responsabilité du Concédant est limitée aux engagements pris en
|
||||||
|
application du Contrat et ne saurait être engagée en raison notamment:
|
||||||
|
(i) des dommages dus à l'inexécution, totale ou partielle, de ses
|
||||||
|
obligations par le Licencié, (ii) des dommages directs ou indirects
|
||||||
|
découlant de l'utilisation ou des performances du Logiciel subis par le
|
||||||
|
Licencié et (iii) plus généralement d'un quelconque dommage indirect. En
|
||||||
|
particulier, les Parties conviennent expressément que tout préjudice
|
||||||
|
financier ou commercial (par exemple perte de données, perte de
|
||||||
|
bénéfices, perte d'exploitation, perte de clientèle ou de commandes,
|
||||||
|
manque à gagner, trouble commercial quelconque) ou toute action dirigée
|
||||||
|
contre le Licencié par un tiers, constitue un dommage indirect et
|
||||||
|
n'ouvre pas droit à réparation par le Concédant.
|
||||||
|
|
||||||
|
|
||||||
|
Article 9 - GARANTIE
|
||||||
|
|
||||||
|
9.1 Le Licencié reconnaît que l'état actuel des connaissances
|
||||||
|
scientifiques et techniques au moment de la mise en circulation du
|
||||||
|
Logiciel ne permet pas d'en tester et d'en vérifier toutes les
|
||||||
|
utilisations ni de détecter l'existence d'éventuels défauts. L'attention
|
||||||
|
du Licencié a été attirée sur ce point sur les risques associés au
|
||||||
|
chargement, à l'utilisation, la modification et/ou au développement et à
|
||||||
|
la reproduction du Logiciel qui sont réservés à des utilisateurs avertis.
|
||||||
|
|
||||||
|
Il relève de la responsabilité du Licencié de contrôler, par tous
|
||||||
|
moyens, l'adéquation du produit à ses besoins, son bon fonctionnement et
|
||||||
|
de s'assurer qu'il ne causera pas de dommages aux personnes et aux biens.
|
||||||
|
|
||||||
|
9.2 Le Concédant déclare de bonne foi être en droit de concéder
|
||||||
|
l'ensemble des droits attachés au Logiciel (comprenant notamment les
|
||||||
|
droits visés à l'article 5 <#etendue>).
|
||||||
|
|
||||||
|
9.3 Le Licencié reconnaît que le Logiciel est fourni "en l'état" par le
|
||||||
|
Concédant sans autre garantie, expresse ou tacite, que celle prévue à
|
||||||
|
l'article 9.2 <#bonne-foi> et notamment sans aucune garantie sur sa
|
||||||
|
valeur commerciale, son caractère sécurisé, innovant ou pertinent.
|
||||||
|
|
||||||
|
En particulier, le Concédant ne garantit pas que le Logiciel est exempt
|
||||||
|
d'erreur, qu'il fonctionnera sans interruption, qu'il sera compatible
|
||||||
|
avec l'équipement du Licencié et sa configuration logicielle ni qu'il
|
||||||
|
remplira les besoins du Licencié.
|
||||||
|
|
||||||
|
9.4 Le Concédant ne garantit pas, de manière expresse ou tacite, que le
|
||||||
|
Logiciel ne porte pas atteinte à un quelconque droit de propriété
|
||||||
|
intellectuelle d'un tiers portant sur un brevet, un logiciel ou sur tout
|
||||||
|
autre droit de propriété. Ainsi, le Concédant exclut toute garantie au
|
||||||
|
profit du Licencié contre les actions en contrefaçon qui pourraient être
|
||||||
|
diligentées au titre de l'utilisation, de la modification, et de la
|
||||||
|
redistribution du Logiciel. Néanmoins, si de telles actions sont
|
||||||
|
exercées contre le Licencié, le Concédant lui apportera son expertise
|
||||||
|
technique et juridique pour sa défense. Cette expertise technique et
|
||||||
|
juridique est déterminée au cas par cas entre le Concédant concerné et
|
||||||
|
le Licencié dans le cadre d'un protocole d'accord. Le Concédant dégage
|
||||||
|
toute responsabilité quant à l'utilisation de la dénomination du
|
||||||
|
Logiciel par le Licencié. Aucune garantie n'est apportée quant à
|
||||||
|
l'existence de droits antérieurs sur le nom du Logiciel et sur
|
||||||
|
l'existence d'une marque.
|
||||||
|
|
||||||
|
|
||||||
|
Article 10 - RESILIATION
|
||||||
|
|
||||||
|
10.1 En cas de manquement par le Licencié aux obligations mises à sa
|
||||||
|
charge par le Contrat, le Concédant pourra résilier de plein droit le
|
||||||
|
Contrat trente (30) jours après notification adressée au Licencié et
|
||||||
|
restée sans effet.
|
||||||
|
|
||||||
|
10.2 Le Licencié dont le Contrat est résilié n'est plus autorisé à
|
||||||
|
utiliser, modifier ou distribuer le Logiciel. Cependant, toutes les
|
||||||
|
licences qu'il aura concédées antérieurement à la résiliation du Contrat
|
||||||
|
resteront valides sous réserve qu'elles aient été effectuées en
|
||||||
|
conformité avec le Contrat.
|
||||||
|
|
||||||
|
|
||||||
|
Article 11 - DISPOSITIONS DIVERSES
|
||||||
|
|
||||||
|
|
||||||
|
11.1 CAUSE EXTERIEURE
|
||||||
|
|
||||||
|
Aucune des Parties ne sera responsable d'un retard ou d'une défaillance
|
||||||
|
d'exécution du Contrat qui serait dû à un cas de force majeure, un cas
|
||||||
|
fortuit ou une cause extérieure, telle que, notamment, le mauvais
|
||||||
|
fonctionnement ou les interruptions du réseau électrique ou de
|
||||||
|
télécommunication, la paralysie du réseau liée à une attaque
|
||||||
|
informatique, l'intervention des autorités gouvernementales, les
|
||||||
|
catastrophes naturelles, les dégâts des eaux, les tremblements de terre,
|
||||||
|
le feu, les explosions, les grèves et les conflits sociaux, l'état de
|
||||||
|
guerre...
|
||||||
|
|
||||||
|
11.2 Le fait, par l'une ou l'autre des Parties, d'omettre en une ou
|
||||||
|
plusieurs occasions de se prévaloir d'une ou plusieurs dispositions du
|
||||||
|
Contrat, ne pourra en aucun cas impliquer renonciation par la Partie
|
||||||
|
intéressée à s'en prévaloir ultérieurement.
|
||||||
|
|
||||||
|
11.3 Le Contrat annule et remplace toute convention antérieure, écrite
|
||||||
|
ou orale, entre les Parties sur le même objet et constitue l'accord
|
||||||
|
entier entre les Parties sur cet objet. Aucune addition ou modification
|
||||||
|
aux termes du Contrat n'aura d'effet à l'égard des Parties à moins
|
||||||
|
d'être faite par écrit et signée par leurs représentants dûment habilités.
|
||||||
|
|
||||||
|
11.4 Dans l'hypothèse où une ou plusieurs des dispositions du Contrat
|
||||||
|
s'avèrerait contraire à une loi ou à un texte applicable, existants ou
|
||||||
|
futurs, cette loi ou ce texte prévaudrait, et les Parties feraient les
|
||||||
|
amendements nécessaires pour se conformer à cette loi ou à ce texte.
|
||||||
|
Toutes les autres dispositions resteront en vigueur. De même, la
|
||||||
|
nullité, pour quelque raison que ce soit, d'une des dispositions du
|
||||||
|
Contrat ne saurait entraîner la nullité de l'ensemble du Contrat.
|
||||||
|
|
||||||
|
|
||||||
|
11.5 LANGUE
|
||||||
|
|
||||||
|
Le Contrat est rédigé en langue française et en langue anglaise, ces
|
||||||
|
deux versions faisant également foi.
|
||||||
|
|
||||||
|
|
||||||
|
Article 12 - NOUVELLES VERSIONS DU CONTRAT
|
||||||
|
|
||||||
|
12.1 Toute personne est autorisée à copier et distribuer des copies de
|
||||||
|
ce Contrat.
|
||||||
|
|
||||||
|
12.2 Afin d'en préserver la cohérence, le texte du Contrat est protégé
|
||||||
|
et ne peut être modifié que par les auteurs de la licence, lesquels se
|
||||||
|
réservent le droit de publier périodiquement des mises à jour ou de
|
||||||
|
nouvelles versions du Contrat, qui posséderont chacune un numéro
|
||||||
|
distinct. Ces versions ultérieures seront susceptibles de prendre en
|
||||||
|
compte de nouvelles problématiques rencontrées par les logiciels libres.
|
||||||
|
|
||||||
|
12.3 Tout Logiciel diffusé sous une version donnée du Contrat ne pourra
|
||||||
|
faire l'objet d'une diffusion ultérieure que sous la même version du
|
||||||
|
Contrat ou une version postérieure, sous réserve des dispositions de
|
||||||
|
l'article 5.3.4 <#compatibilite>.
|
||||||
|
|
||||||
|
|
||||||
|
Article 13 - LOI APPLICABLE ET COMPETENCE TERRITORIALE
|
||||||
|
|
||||||
|
13.1 Le Contrat est régi par la loi française. Les Parties conviennent
|
||||||
|
de tenter de régler à l'amiable les différends ou litiges qui
|
||||||
|
viendraient à se produire par suite ou à l'occasion du Contrat.
|
||||||
|
|
||||||
|
13.2 A défaut d'accord amiable dans un délai de deux (2) mois à compter
|
||||||
|
de leur survenance et sauf situation relevant d'une procédure d'urgence,
|
||||||
|
les différends ou litiges seront portés par la Partie la plus diligente
|
||||||
|
devant les Tribunaux compétents de Paris.
|
||||||
|
|
||||||
|
|
||||||
+519
@@ -0,0 +1,519 @@
|
|||||||
|
|
||||||
|
CeCILL FREE SOFTWARE LICENSE AGREEMENT
|
||||||
|
|
||||||
|
Version 2.1 dated 2013-06-21
|
||||||
|
|
||||||
|
|
||||||
|
Notice
|
||||||
|
|
||||||
|
This Agreement is a Free Software license agreement that is the result
|
||||||
|
of discussions between its authors in order to ensure compliance with
|
||||||
|
the two main principles guiding its drafting:
|
||||||
|
|
||||||
|
* firstly, compliance with the principles governing the distribution
|
||||||
|
of Free Software: access to source code, broad rights granted to users,
|
||||||
|
* secondly, the election of a governing law, French law, with which it
|
||||||
|
is conformant, both as regards the law of torts and intellectual
|
||||||
|
property law, and the protection that it offers to both authors and
|
||||||
|
holders of the economic rights over software.
|
||||||
|
|
||||||
|
The authors of the CeCILL (for Ce[a] C[nrs] I[nria] L[ogiciel] L[ibre])
|
||||||
|
license are:
|
||||||
|
|
||||||
|
Commissariat à l'énergie atomique et aux énergies alternatives - CEA, a
|
||||||
|
public scientific, technical and industrial research establishment,
|
||||||
|
having its principal place of business at 25 rue Leblanc, immeuble Le
|
||||||
|
Ponant D, 75015 Paris, France.
|
||||||
|
|
||||||
|
Centre National de la Recherche Scientifique - CNRS, a public scientific
|
||||||
|
and technological establishment, having its principal place of business
|
||||||
|
at 3 rue Michel-Ange, 75794 Paris cedex 16, France.
|
||||||
|
|
||||||
|
Institut National de Recherche en Informatique et en Automatique -
|
||||||
|
Inria, a public scientific and technological establishment, having its
|
||||||
|
principal place of business at Domaine de Voluceau, Rocquencourt, BP
|
||||||
|
105, 78153 Le Chesnay cedex, France.
|
||||||
|
|
||||||
|
|
||||||
|
Preamble
|
||||||
|
|
||||||
|
The purpose of this Free Software license agreement is to grant users
|
||||||
|
the right to modify and redistribute the software governed by this
|
||||||
|
license within the framework of an open source distribution model.
|
||||||
|
|
||||||
|
The exercising of this right is conditional upon certain obligations for
|
||||||
|
users so as to preserve this status for all subsequent redistributions.
|
||||||
|
|
||||||
|
In consideration of access to the source code and the rights to copy,
|
||||||
|
modify and redistribute granted by the license, users are provided only
|
||||||
|
with a limited warranty and the software's author, the holder of the
|
||||||
|
economic rights, and the successive licensors only have limited liability.
|
||||||
|
|
||||||
|
In this respect, the risks associated with loading, using, modifying
|
||||||
|
and/or developing or reproducing the software by the user are brought to
|
||||||
|
the user's attention, given its Free Software status, which may make it
|
||||||
|
complicated to use, with the result that its use is reserved for
|
||||||
|
developers and experienced professionals having in-depth computer
|
||||||
|
knowledge. Users are therefore encouraged to load and test the
|
||||||
|
suitability of the software as regards their requirements in conditions
|
||||||
|
enabling the security of their systems and/or data to be ensured and,
|
||||||
|
more generally, to use and operate it in the same conditions of
|
||||||
|
security. This Agreement may be freely reproduced and published,
|
||||||
|
provided it is not altered, and that no provisions are either added or
|
||||||
|
removed herefrom.
|
||||||
|
|
||||||
|
This Agreement may apply to any or all software for which the holder of
|
||||||
|
the economic rights decides to submit the use thereof to its provisions.
|
||||||
|
|
||||||
|
Frequently asked questions can be found on the official website of the
|
||||||
|
CeCILL licenses family (http://www.cecill.info/index.en.html) for any
|
||||||
|
necessary clarification.
|
||||||
|
|
||||||
|
|
||||||
|
Article 1 - DEFINITIONS
|
||||||
|
|
||||||
|
For the purpose of this Agreement, when the following expressions
|
||||||
|
commence with a capital letter, they shall have the following meaning:
|
||||||
|
|
||||||
|
Agreement: means this license agreement, and its possible subsequent
|
||||||
|
versions and annexes.
|
||||||
|
|
||||||
|
Software: means the software in its Object Code and/or Source Code form
|
||||||
|
and, where applicable, its documentation, "as is" when the Licensee
|
||||||
|
accepts the Agreement.
|
||||||
|
|
||||||
|
Initial Software: means the Software in its Source Code and possibly its
|
||||||
|
Object Code form and, where applicable, its documentation, "as is" when
|
||||||
|
it is first distributed under the terms and conditions of the Agreement.
|
||||||
|
|
||||||
|
Modified Software: means the Software modified by at least one
|
||||||
|
Contribution.
|
||||||
|
|
||||||
|
Source Code: means all the Software's instructions and program lines to
|
||||||
|
which access is required so as to modify the Software.
|
||||||
|
|
||||||
|
Object Code: means the binary files originating from the compilation of
|
||||||
|
the Source Code.
|
||||||
|
|
||||||
|
Holder: means the holder(s) of the economic rights over the Initial
|
||||||
|
Software.
|
||||||
|
|
||||||
|
Licensee: means the Software user(s) having accepted the Agreement.
|
||||||
|
|
||||||
|
Contributor: means a Licensee having made at least one Contribution.
|
||||||
|
|
||||||
|
Licensor: means the Holder, or any other individual or legal entity, who
|
||||||
|
distributes the Software under the Agreement.
|
||||||
|
|
||||||
|
Contribution: means any or all modifications, corrections, translations,
|
||||||
|
adaptations and/or new functions integrated into the Software by any or
|
||||||
|
all Contributors, as well as any or all Internal Modules.
|
||||||
|
|
||||||
|
Module: means a set of sources files including their documentation that
|
||||||
|
enables supplementary functions or services in addition to those offered
|
||||||
|
by the Software.
|
||||||
|
|
||||||
|
External Module: means any or all Modules, not derived from the
|
||||||
|
Software, so that this Module and the Software run in separate address
|
||||||
|
spaces, with one calling the other when they are run.
|
||||||
|
|
||||||
|
Internal Module: means any or all Module, connected to the Software so
|
||||||
|
that they both execute in the same address space.
|
||||||
|
|
||||||
|
GNU GPL: means the GNU General Public License version 2 or any
|
||||||
|
subsequent version, as published by the Free Software Foundation Inc.
|
||||||
|
|
||||||
|
GNU Affero GPL: means the GNU Affero General Public License version 3 or
|
||||||
|
any subsequent version, as published by the Free Software Foundation Inc.
|
||||||
|
|
||||||
|
EUPL: means the European Union Public License version 1.1 or any
|
||||||
|
subsequent version, as published by the European Commission.
|
||||||
|
|
||||||
|
Parties: mean both the Licensee and the Licensor.
|
||||||
|
|
||||||
|
These expressions may be used both in singular and plural form.
|
||||||
|
|
||||||
|
|
||||||
|
Article 2 - PURPOSE
|
||||||
|
|
||||||
|
The purpose of the Agreement is the grant by the Licensor to the
|
||||||
|
Licensee of a non-exclusive, transferable and worldwide license for the
|
||||||
|
Software as set forth in Article 5 <#scope> hereinafter for the whole
|
||||||
|
term of the protection granted by the rights over said Software.
|
||||||
|
|
||||||
|
|
||||||
|
Article 3 - ACCEPTANCE
|
||||||
|
|
||||||
|
3.1 The Licensee shall be deemed as having accepted the terms and
|
||||||
|
conditions of this Agreement upon the occurrence of the first of the
|
||||||
|
following events:
|
||||||
|
|
||||||
|
* (i) loading the Software by any or all means, notably, by
|
||||||
|
downloading from a remote server, or by loading from a physical medium;
|
||||||
|
* (ii) the first time the Licensee exercises any of the rights granted
|
||||||
|
hereunder.
|
||||||
|
|
||||||
|
3.2 One copy of the Agreement, containing a notice relating to the
|
||||||
|
characteristics of the Software, to the limited warranty, and to the
|
||||||
|
fact that its use is restricted to experienced users has been provided
|
||||||
|
to the Licensee prior to its acceptance as set forth in Article 3.1
|
||||||
|
<#accepting> hereinabove, and the Licensee hereby acknowledges that it
|
||||||
|
has read and understood it.
|
||||||
|
|
||||||
|
|
||||||
|
Article 4 - EFFECTIVE DATE AND TERM
|
||||||
|
|
||||||
|
|
||||||
|
4.1 EFFECTIVE DATE
|
||||||
|
|
||||||
|
The Agreement shall become effective on the date when it is accepted by
|
||||||
|
the Licensee as set forth in Article 3.1 <#accepting>.
|
||||||
|
|
||||||
|
|
||||||
|
4.2 TERM
|
||||||
|
|
||||||
|
The Agreement shall remain in force for the entire legal term of
|
||||||
|
protection of the economic rights over the Software.
|
||||||
|
|
||||||
|
|
||||||
|
Article 5 - SCOPE OF RIGHTS GRANTED
|
||||||
|
|
||||||
|
The Licensor hereby grants to the Licensee, who accepts, the following
|
||||||
|
rights over the Software for any or all use, and for the term of the
|
||||||
|
Agreement, on the basis of the terms and conditions set forth hereinafter.
|
||||||
|
|
||||||
|
Besides, if the Licensor owns or comes to own one or more patents
|
||||||
|
protecting all or part of the functions of the Software or of its
|
||||||
|
components, the Licensor undertakes not to enforce the rights granted by
|
||||||
|
these patents against successive Licensees using, exploiting or
|
||||||
|
modifying the Software. If these patents are transferred, the Licensor
|
||||||
|
undertakes to have the transferees subscribe to the obligations set
|
||||||
|
forth in this paragraph.
|
||||||
|
|
||||||
|
|
||||||
|
5.1 RIGHT OF USE
|
||||||
|
|
||||||
|
The Licensee is authorized to use the Software, without any limitation
|
||||||
|
as to its fields of application, with it being hereinafter specified
|
||||||
|
that this comprises:
|
||||||
|
|
||||||
|
1. permanent or temporary reproduction of all or part of the Software
|
||||||
|
by any or all means and in any or all form.
|
||||||
|
|
||||||
|
2. loading, displaying, running, or storing the Software on any or all
|
||||||
|
medium.
|
||||||
|
|
||||||
|
3. entitlement to observe, study or test its operation so as to
|
||||||
|
determine the ideas and principles behind any or all constituent
|
||||||
|
elements of said Software. This shall apply when the Licensee
|
||||||
|
carries out any or all loading, displaying, running, transmission or
|
||||||
|
storage operation as regards the Software, that it is entitled to
|
||||||
|
carry out hereunder.
|
||||||
|
|
||||||
|
|
||||||
|
5.2 ENTITLEMENT TO MAKE CONTRIBUTIONS
|
||||||
|
|
||||||
|
The right to make Contributions includes the right to translate, adapt,
|
||||||
|
arrange, or make any or all modifications to the Software, and the right
|
||||||
|
to reproduce the resulting software.
|
||||||
|
|
||||||
|
The Licensee is authorized to make any or all Contributions to the
|
||||||
|
Software provided that it includes an explicit notice that it is the
|
||||||
|
author of said Contribution and indicates the date of the creation thereof.
|
||||||
|
|
||||||
|
|
||||||
|
5.3 RIGHT OF DISTRIBUTION
|
||||||
|
|
||||||
|
In particular, the right of distribution includes the right to publish,
|
||||||
|
transmit and communicate the Software to the general public on any or
|
||||||
|
all medium, and by any or all means, and the right to market, either in
|
||||||
|
consideration of a fee, or free of charge, one or more copies of the
|
||||||
|
Software by any means.
|
||||||
|
|
||||||
|
The Licensee is further authorized to distribute copies of the modified
|
||||||
|
or unmodified Software to third parties according to the terms and
|
||||||
|
conditions set forth hereinafter.
|
||||||
|
|
||||||
|
|
||||||
|
5.3.1 DISTRIBUTION OF SOFTWARE WITHOUT MODIFICATION
|
||||||
|
|
||||||
|
The Licensee is authorized to distribute true copies of the Software in
|
||||||
|
Source Code or Object Code form, provided that said distribution
|
||||||
|
complies with all the provisions of the Agreement and is accompanied by:
|
||||||
|
|
||||||
|
1. a copy of the Agreement,
|
||||||
|
|
||||||
|
2. a notice relating to the limitation of both the Licensor's warranty
|
||||||
|
and liability as set forth in Articles 8 and 9,
|
||||||
|
|
||||||
|
and that, in the event that only the Object Code of the Software is
|
||||||
|
redistributed, the Licensee allows effective access to the full Source
|
||||||
|
Code of the Software for a period of at least three years from the
|
||||||
|
distribution of the Software, it being understood that the additional
|
||||||
|
acquisition cost of the Source Code shall not exceed the cost of the
|
||||||
|
data transfer.
|
||||||
|
|
||||||
|
|
||||||
|
5.3.2 DISTRIBUTION OF MODIFIED SOFTWARE
|
||||||
|
|
||||||
|
When the Licensee makes a Contribution to the Software, the terms and
|
||||||
|
conditions for the distribution of the resulting Modified Software
|
||||||
|
become subject to all the provisions of this Agreement.
|
||||||
|
|
||||||
|
The Licensee is authorized to distribute the Modified Software, in
|
||||||
|
source code or object code form, provided that said distribution
|
||||||
|
complies with all the provisions of the Agreement and is accompanied by:
|
||||||
|
|
||||||
|
1. a copy of the Agreement,
|
||||||
|
|
||||||
|
2. a notice relating to the limitation of both the Licensor's warranty
|
||||||
|
and liability as set forth in Articles 8 and 9,
|
||||||
|
|
||||||
|
and, in the event that only the object code of the Modified Software is
|
||||||
|
redistributed,
|
||||||
|
|
||||||
|
3. a note stating the conditions of effective access to the full source
|
||||||
|
code of the Modified Software for a period of at least three years
|
||||||
|
from the distribution of the Modified Software, it being understood
|
||||||
|
that the additional acquisition cost of the source code shall not
|
||||||
|
exceed the cost of the data transfer.
|
||||||
|
|
||||||
|
|
||||||
|
5.3.3 DISTRIBUTION OF EXTERNAL MODULES
|
||||||
|
|
||||||
|
When the Licensee has developed an External Module, the terms and
|
||||||
|
conditions of this Agreement do not apply to said External Module, that
|
||||||
|
may be distributed under a separate license agreement.
|
||||||
|
|
||||||
|
|
||||||
|
5.3.4 COMPATIBILITY WITH OTHER LICENSES
|
||||||
|
|
||||||
|
The Licensee can include a code that is subject to the provisions of one
|
||||||
|
of the versions of the GNU GPL, GNU Affero GPL and/or EUPL in the
|
||||||
|
Modified or unmodified Software, and distribute that entire code under
|
||||||
|
the terms of the same version of the GNU GPL, GNU Affero GPL and/or EUPL.
|
||||||
|
|
||||||
|
The Licensee can include the Modified or unmodified Software in a code
|
||||||
|
that is subject to the provisions of one of the versions of the GNU GPL,
|
||||||
|
GNU Affero GPL and/or EUPL and distribute that entire code under the
|
||||||
|
terms of the same version of the GNU GPL, GNU Affero GPL and/or EUPL.
|
||||||
|
|
||||||
|
|
||||||
|
Article 6 - INTELLECTUAL PROPERTY
|
||||||
|
|
||||||
|
|
||||||
|
6.1 OVER THE INITIAL SOFTWARE
|
||||||
|
|
||||||
|
The Holder owns the economic rights over the Initial Software. Any or
|
||||||
|
all use of the Initial Software is subject to compliance with the terms
|
||||||
|
and conditions under which the Holder has elected to distribute its work
|
||||||
|
and no one shall be entitled to modify the terms and conditions for the
|
||||||
|
distribution of said Initial Software.
|
||||||
|
|
||||||
|
The Holder undertakes that the Initial Software will remain ruled at
|
||||||
|
least by this Agreement, for the duration set forth in Article 4.2 <#term>.
|
||||||
|
|
||||||
|
|
||||||
|
6.2 OVER THE CONTRIBUTIONS
|
||||||
|
|
||||||
|
The Licensee who develops a Contribution is the owner of the
|
||||||
|
intellectual property rights over this Contribution as defined by
|
||||||
|
applicable law.
|
||||||
|
|
||||||
|
|
||||||
|
6.3 OVER THE EXTERNAL MODULES
|
||||||
|
|
||||||
|
The Licensee who develops an External Module is the owner of the
|
||||||
|
intellectual property rights over this External Module as defined by
|
||||||
|
applicable law and is free to choose the type of agreement that shall
|
||||||
|
govern its distribution.
|
||||||
|
|
||||||
|
|
||||||
|
6.4 JOINT PROVISIONS
|
||||||
|
|
||||||
|
The Licensee expressly undertakes:
|
||||||
|
|
||||||
|
1. not to remove, or modify, in any manner, the intellectual property
|
||||||
|
notices attached to the Software;
|
||||||
|
|
||||||
|
2. to reproduce said notices, in an identical manner, in the copies of
|
||||||
|
the Software modified or not.
|
||||||
|
|
||||||
|
The Licensee undertakes not to directly or indirectly infringe the
|
||||||
|
intellectual property rights on the Software of the Holder and/or
|
||||||
|
Contributors, and to take, where applicable, vis-à-vis its staff, any
|
||||||
|
and all measures required to ensure respect of said intellectual
|
||||||
|
property rights of the Holder and/or Contributors.
|
||||||
|
|
||||||
|
|
||||||
|
Article 7 - RELATED SERVICES
|
||||||
|
|
||||||
|
7.1 Under no circumstances shall the Agreement oblige the Licensor to
|
||||||
|
provide technical assistance or maintenance services for the Software.
|
||||||
|
|
||||||
|
However, the Licensor is entitled to offer this type of services. The
|
||||||
|
terms and conditions of such technical assistance, and/or such
|
||||||
|
maintenance, shall be set forth in a separate instrument. Only the
|
||||||
|
Licensor offering said maintenance and/or technical assistance services
|
||||||
|
shall incur liability therefor.
|
||||||
|
|
||||||
|
7.2 Similarly, any Licensor is entitled to offer to its licensees, under
|
||||||
|
its sole responsibility, a warranty, that shall only be binding upon
|
||||||
|
itself, for the redistribution of the Software and/or the Modified
|
||||||
|
Software, under terms and conditions that it is free to decide. Said
|
||||||
|
warranty, and the financial terms and conditions of its application,
|
||||||
|
shall be subject of a separate instrument executed between the Licensor
|
||||||
|
and the Licensee.
|
||||||
|
|
||||||
|
|
||||||
|
Article 8 - LIABILITY
|
||||||
|
|
||||||
|
8.1 Subject to the provisions of Article 8.2, the Licensee shall be
|
||||||
|
entitled to claim compensation for any direct loss it may have suffered
|
||||||
|
from the Software as a result of a fault on the part of the relevant
|
||||||
|
Licensor, subject to providing evidence thereof.
|
||||||
|
|
||||||
|
8.2 The Licensor's liability is limited to the commitments made under
|
||||||
|
this Agreement and shall not be incurred as a result of in particular:
|
||||||
|
(i) loss due the Licensee's total or partial failure to fulfill its
|
||||||
|
obligations, (ii) direct or consequential loss that is suffered by the
|
||||||
|
Licensee due to the use or performance of the Software, and (iii) more
|
||||||
|
generally, any consequential loss. In particular the Parties expressly
|
||||||
|
agree that any or all pecuniary or business loss (i.e. loss of data,
|
||||||
|
loss of profits, operating loss, loss of customers or orders,
|
||||||
|
opportunity cost, any disturbance to business activities) or any or all
|
||||||
|
legal proceedings instituted against the Licensee by a third party,
|
||||||
|
shall constitute consequential loss and shall not provide entitlement to
|
||||||
|
any or all compensation from the Licensor.
|
||||||
|
|
||||||
|
|
||||||
|
Article 9 - WARRANTY
|
||||||
|
|
||||||
|
9.1 The Licensee acknowledges that the scientific and technical
|
||||||
|
state-of-the-art when the Software was distributed did not enable all
|
||||||
|
possible uses to be tested and verified, nor for the presence of
|
||||||
|
possible defects to be detected. In this respect, the Licensee's
|
||||||
|
attention has been drawn to the risks associated with loading, using,
|
||||||
|
modifying and/or developing and reproducing the Software which are
|
||||||
|
reserved for experienced users.
|
||||||
|
|
||||||
|
The Licensee shall be responsible for verifying, by any or all means,
|
||||||
|
the suitability of the product for its requirements, its good working
|
||||||
|
order, and for ensuring that it shall not cause damage to either persons
|
||||||
|
or properties.
|
||||||
|
|
||||||
|
9.2 The Licensor hereby represents, in good faith, that it is entitled
|
||||||
|
to grant all the rights over the Software (including in particular the
|
||||||
|
rights set forth in Article 5 <#scope>).
|
||||||
|
|
||||||
|
9.3 The Licensee acknowledges that the Software is supplied "as is" by
|
||||||
|
the Licensor without any other express or tacit warranty, other than
|
||||||
|
that provided for in Article 9.2 <#good-faith> and, in particular,
|
||||||
|
without any warranty as to its commercial value, its secured, safe,
|
||||||
|
innovative or relevant nature.
|
||||||
|
|
||||||
|
Specifically, the Licensor does not warrant that the Software is free
|
||||||
|
from any error, that it will operate without interruption, that it will
|
||||||
|
be compatible with the Licensee's own equipment and software
|
||||||
|
configuration, nor that it will meet the Licensee's requirements.
|
||||||
|
|
||||||
|
9.4 The Licensor does not either expressly or tacitly warrant that the
|
||||||
|
Software does not infringe any third party intellectual property right
|
||||||
|
relating to a patent, software or any other property right. Therefore,
|
||||||
|
the Licensor disclaims any and all liability towards the Licensee
|
||||||
|
arising out of any or all proceedings for infringement that may be
|
||||||
|
instituted in respect of the use, modification and redistribution of the
|
||||||
|
Software. Nevertheless, should such proceedings be instituted against
|
||||||
|
the Licensee, the Licensor shall provide it with technical and legal
|
||||||
|
expertise for its defense. Such technical and legal expertise shall be
|
||||||
|
decided on a case-by-case basis between the relevant Licensor and the
|
||||||
|
Licensee pursuant to a memorandum of understanding. The Licensor
|
||||||
|
disclaims any and all liability as regards the Licensee's use of the
|
||||||
|
name of the Software. No warranty is given as regards the existence of
|
||||||
|
prior rights over the name of the Software or as regards the existence
|
||||||
|
of a trademark.
|
||||||
|
|
||||||
|
|
||||||
|
Article 10 - TERMINATION
|
||||||
|
|
||||||
|
10.1 In the event of a breach by the Licensee of its obligations
|
||||||
|
hereunder, the Licensor may automatically terminate this Agreement
|
||||||
|
thirty (30) days after notice has been sent to the Licensee and has
|
||||||
|
remained ineffective.
|
||||||
|
|
||||||
|
10.2 A Licensee whose Agreement is terminated shall no longer be
|
||||||
|
authorized to use, modify or distribute the Software. However, any
|
||||||
|
licenses that it may have granted prior to termination of the Agreement
|
||||||
|
shall remain valid subject to their having been granted in compliance
|
||||||
|
with the terms and conditions hereof.
|
||||||
|
|
||||||
|
|
||||||
|
Article 11 - MISCELLANEOUS
|
||||||
|
|
||||||
|
|
||||||
|
11.1 EXCUSABLE EVENTS
|
||||||
|
|
||||||
|
Neither Party shall be liable for any or all delay, or failure to
|
||||||
|
perform the Agreement, that may be attributable to an event of force
|
||||||
|
majeure, an act of God or an outside cause, such as defective
|
||||||
|
functioning or interruptions of the electricity or telecommunications
|
||||||
|
networks, network paralysis following a virus attack, intervention by
|
||||||
|
government authorities, natural disasters, water damage, earthquakes,
|
||||||
|
fire, explosions, strikes and labor unrest, war, etc.
|
||||||
|
|
||||||
|
11.2 Any failure by either Party, on one or more occasions, to invoke
|
||||||
|
one or more of the provisions hereof, shall under no circumstances be
|
||||||
|
interpreted as being a waiver by the interested Party of its right to
|
||||||
|
invoke said provision(s) subsequently.
|
||||||
|
|
||||||
|
11.3 The Agreement cancels and replaces any or all previous agreements,
|
||||||
|
whether written or oral, between the Parties and having the same
|
||||||
|
purpose, and constitutes the entirety of the agreement between said
|
||||||
|
Parties concerning said purpose. No supplement or modification to the
|
||||||
|
terms and conditions hereof shall be effective as between the Parties
|
||||||
|
unless it is made in writing and signed by their duly authorized
|
||||||
|
representatives.
|
||||||
|
|
||||||
|
11.4 In the event that one or more of the provisions hereof were to
|
||||||
|
conflict with a current or future applicable act or legislative text,
|
||||||
|
said act or legislative text shall prevail, and the Parties shall make
|
||||||
|
the necessary amendments so as to comply with said act or legislative
|
||||||
|
text. All other provisions shall remain effective. Similarly, invalidity
|
||||||
|
of a provision of the Agreement, for any reason whatsoever, shall not
|
||||||
|
cause the Agreement as a whole to be invalid.
|
||||||
|
|
||||||
|
|
||||||
|
11.5 LANGUAGE
|
||||||
|
|
||||||
|
The Agreement is drafted in both French and English and both versions
|
||||||
|
are deemed authentic.
|
||||||
|
|
||||||
|
|
||||||
|
Article 12 - NEW VERSIONS OF THE AGREEMENT
|
||||||
|
|
||||||
|
12.1 Any person is authorized to duplicate and distribute copies of this
|
||||||
|
Agreement.
|
||||||
|
|
||||||
|
12.2 So as to ensure coherence, the wording of this Agreement is
|
||||||
|
protected and may only be modified by the authors of the License, who
|
||||||
|
reserve the right to periodically publish updates or new versions of the
|
||||||
|
Agreement, each with a separate number. These subsequent versions may
|
||||||
|
address new issues encountered by Free Software.
|
||||||
|
|
||||||
|
12.3 Any Software distributed under a given version of the Agreement may
|
||||||
|
only be subsequently distributed under the same version of the Agreement
|
||||||
|
or a subsequent version, subject to the provisions of Article 5.3.4
|
||||||
|
<#compatibility>.
|
||||||
|
|
||||||
|
|
||||||
|
Article 13 - GOVERNING LAW AND JURISDICTION
|
||||||
|
|
||||||
|
13.1 The Agreement is governed by French law. The Parties agree to
|
||||||
|
endeavor to seek an amicable solution to any disagreements or disputes
|
||||||
|
that may arise during the performance of the Agreement.
|
||||||
|
|
||||||
|
13.2 Failing an amicable solution within two (2) months as from their
|
||||||
|
occurrence, and unless emergency proceedings are necessary, the
|
||||||
|
disagreements or disputes shall be referred to the Paris Courts having
|
||||||
|
jurisdiction, by the more diligent Party.
|
||||||
|
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
# Crate Makefile: all the targets come from the kit (.crate-kit/).
|
||||||
|
# See the crate-kit repository; `make help` lists the commands.
|
||||||
|
|
||||||
|
# Description used in the release notes (optional, default: crate name).
|
||||||
|
RELEASE_PROJECT_DESC = obipipeline (typed multi-threaded pipelines and memory-bounded throttling)
|
||||||
|
|
||||||
|
# Kit: .crate-kit/ is resynchronized at every make from KIT_SRC, the organization's extension kit
|
||||||
|
# (which includes crate-kit and adds registry, forge, kinds to it; adopt.sh --kit-src writes it),
|
||||||
|
# before the include that reads it. Ignored if crate-kit is absent (CI, repository cloned alone: the committed copy is used).
|
||||||
|
KIT_SRC ?= ../obi-kit
|
||||||
|
$(shell [ -x '$(KIT_SRC)/tools/kit-copy.sh' ] && '$(KIT_SRC)/tools/kit-copy.sh' .crate-kit)
|
||||||
|
|
||||||
|
include .crate-kit/crate.mk
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
# obipipeline
|
||||||
|
|
||||||
|
Typed, composable multi-threaded pipelines built on channels, and a memory-bounded `throttle()` for iterators.
|
||||||
|
|
||||||
|
## Features
|
||||||
|
|
||||||
|
- **`Pipe<D, In, Out>`**: a pure description of pipeline stages (no thread, no channel until `.apply()`), built with the `make_pipe!` macro and composed with `.then()`. `.apply(iter, n_workers, capacity)` runs it on a pool of worker threads and returns an iterator over the output (`PipeIter`).
|
||||||
|
- **Stages**: 1→1 transforms (`|`, `|?` when fallible) and 1→N flat transforms (`||`, `||?`).
|
||||||
|
- **`Pipeline` / `WorkerPool`**: the lower-level runtime (source, stages, sink), built with `make_pipeline!`.
|
||||||
|
- **`throttle(iter, max)`**: wraps an iterator so that at most `max` items are in flight; each item carries a `ThrottleGuard` that frees its slot when dropped. `Throttle::acquire_guard()` does the same for callers with no source iterator.
|
||||||
|
|
||||||
|
Items go through a single user-defined enum `D`; each stage names the variant it reads and the one it writes. The order of the output is **not** guaranteed when several workers run.
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
|
||||||
|
The crate is published on the private registry `obi`:
|
||||||
|
|
||||||
|
```toml
|
||||||
|
[dependencies]
|
||||||
|
obipipeline = { version = "0.1", registry = "obi" }
|
||||||
|
```
|
||||||
|
|
||||||
|
## Example
|
||||||
|
|
||||||
|
```rust
|
||||||
|
use obipipeline::make_pipe;
|
||||||
|
|
||||||
|
enum D {
|
||||||
|
Num(u64),
|
||||||
|
Text(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
fn double(x: u64) -> u64 { x * 2 }
|
||||||
|
fn to_text(x: u64) -> String { x.to_string() }
|
||||||
|
|
||||||
|
let pipe = make_pipe! {
|
||||||
|
D : u64 => String,
|
||||||
|
| double : Num => Num,
|
||||||
|
| to_text : Num => Text,
|
||||||
|
};
|
||||||
|
let out: Vec<String> = pipe.apply(1..=100u64, 4, 8).collect();
|
||||||
|
```
|
||||||
|
|
||||||
|
`examples/sandbox_pipeline.rs` shows the lower-level `make_pipeline!` / `WorkerPool` form.
|
||||||
|
|
||||||
|
## API
|
||||||
|
|
||||||
|
- Pipes: `Pipe`, `PipeIter`, macros `make_pipe!`, `make_transform!`, `make_transform_fallible!`, `make_flat_transform!`, `make_flat_transform_fallible!`.
|
||||||
|
- Runtime: `Pipeline`, `WorkerPool`, `Stage`, `SourceFn`, `SinkFn`, `SharedFn`, `SharedFlatFn`, `PipelineError`, `PipelineSender`; macros `make_pipeline!`, `make_source!`, `make_source_fallible!`, `make_sink!`, `make_sink_fallible!`.
|
||||||
|
- Throttling: `throttle()`, `Throttle`, `ThrottleGuard`, `Throttled`.
|
||||||
|
|
||||||
|
## Development
|
||||||
|
|
||||||
|
Development commands come from the obi kit (`.crate-kit/`, resynchronised at every `make`); `make help` lists them.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
make test # unit, integration and doc tests
|
||||||
|
make ci # checks before a release
|
||||||
|
```
|
||||||
|
|
||||||
|
The crate has no workspace: it builds and tests on its own. `.cargo/config.toml` is generated by `make` (registry definition, and patches to neighbouring crates for joint development): never edit or commit it.
|
||||||
|
|
||||||
|
## Dependencies
|
||||||
|
|
||||||
|
- `crossbeam-channel`: channels and `Select` used by the scheduler.
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
CeCILL-2.1, see [LICENSE](LICENSE) (French text) and [LICENSE.en](LICENSE.en) (English translation).
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
# Release Notes for obipipeline (typed multi-threaded pipelines and memory-bounded throttling), version 0.1.1
|
||||||
|
|
||||||
|
## Features
|
||||||
|
|
||||||
|
- Introduce the `obipipeline` crate providing typed, composable multi-threaded pipelines with memory-bounded throttling.
|
||||||
|
- Add `scheduler` module for managing pipeline stages, including:
|
||||||
|
- `Pipe` and `PipeIter` for data transformation steps.
|
||||||
|
- `Pipeline` and `WorkerPool` for concurrent execution.
|
||||||
|
- Macros `make_pipe!` and `make_pipeline!` for ergonomic construction.
|
||||||
|
- Thread runners and type definitions (`Stage`, `WorkerTask`).
|
||||||
|
- Add `throttle` module implementing memory-bounded concurrency control:
|
||||||
|
- `Throttle` and `ThrottleGuard` using semaphores.
|
||||||
|
- `throttle` function for limiting concurrent access.
|
||||||
|
- Add `examples/sandbox_pipeline.rs` demonstrating pipeline construction with `make_pipeline!` and `WorkerPool`.
|
||||||
|
|
||||||
|
## Fixes
|
||||||
|
|
||||||
|
- None.
|
||||||
|
|
||||||
|
## Internal
|
||||||
|
|
||||||
|
- Add `Cargo.toml`, `Cargo.lock`, and `Makefile` defining the package (v0.1.1) with `crossbeam-channel` dependency.
|
||||||
|
- Add `.crate-kit/` directory with build configuration and shell scripts for API tracking, dependency management, and release workflows.
|
||||||
|
- Add `.gitea/workflows/release.yaml` for automated releases on tag pushes.
|
||||||
|
- Add `api/` directory with public API snapshots for version tracking.
|
||||||
|
- Add `tests/pipe.rs` and `tests/throttle.rs` for verifying pipe composition, flat transforms, empty input handling, throttle ordering, concurrency bounds, and guard blocking behavior.
|
||||||
|
- Add `LICENSE` and `LICENSE.en` files (CeCILL license).
|
||||||
|
- Add `.gitignore` to exclude `target` and `/.cargo/config.toml`.
|
||||||
|
- Update `README.md` with documentation on core concepts, API details, and installation instructions.
|
||||||
Binary file not shown.
@@ -0,0 +1 @@
|
|||||||
|
rustc 1.100.0 (0ef1bc386 2026-11-09) | cargo-public-api 0.52.0
|
||||||
+186
@@ -0,0 +1,186 @@
|
|||||||
|
pub mod obipipeline
|
||||||
|
pub use obipipeline::PipelineSender
|
||||||
|
pub mod obipipeline::throttle
|
||||||
|
pub struct obipipeline::throttle::Throttle
|
||||||
|
impl obipipeline::throttle::Throttle
|
||||||
|
pub fn obipipeline::throttle::Throttle::acquire(&self)
|
||||||
|
pub fn obipipeline::throttle::Throttle::new(usize) -> Self
|
||||||
|
impl obipipeline::throttle::Throttle
|
||||||
|
pub fn obipipeline::throttle::Throttle::acquire_guard(&alloc::rcs::arc::Arc<Self>) -> obipipeline::throttle::ThrottleGuard
|
||||||
|
impl core::marker::Forget for obipipeline::throttle::Throttle
|
||||||
|
impl !core::marker::Freeze for obipipeline::throttle::Throttle
|
||||||
|
impl core::marker::Move for obipipeline::throttle::Throttle
|
||||||
|
impl core::marker::Send for obipipeline::throttle::Throttle
|
||||||
|
impl core::marker::Sync for obipipeline::throttle::Throttle
|
||||||
|
impl core::marker::Unpin for obipipeline::throttle::Throttle
|
||||||
|
impl core::marker::UnsafeUnpin for obipipeline::throttle::Throttle
|
||||||
|
impl core::panic::unwind_safe::RefUnwindSafe for obipipeline::throttle::Throttle
|
||||||
|
impl core::panic::unwind_safe::UnwindSafe for obipipeline::throttle::Throttle
|
||||||
|
pub struct obipipeline::throttle::ThrottleGuard(_)
|
||||||
|
impl core::ops::drop::Drop for obipipeline::throttle::ThrottleGuard
|
||||||
|
pub fn obipipeline::throttle::ThrottleGuard::drop(&mut self)
|
||||||
|
impl core::marker::Forget for obipipeline::throttle::ThrottleGuard
|
||||||
|
impl core::marker::Freeze for obipipeline::throttle::ThrottleGuard
|
||||||
|
impl core::marker::Move for obipipeline::throttle::ThrottleGuard
|
||||||
|
impl core::marker::Send for obipipeline::throttle::ThrottleGuard
|
||||||
|
impl core::marker::Sync for obipipeline::throttle::ThrottleGuard
|
||||||
|
impl core::marker::Unpin for obipipeline::throttle::ThrottleGuard
|
||||||
|
impl core::marker::UnsafeUnpin for obipipeline::throttle::ThrottleGuard
|
||||||
|
impl core::panic::unwind_safe::RefUnwindSafe for obipipeline::throttle::ThrottleGuard
|
||||||
|
impl core::panic::unwind_safe::UnwindSafe for obipipeline::throttle::ThrottleGuard
|
||||||
|
pub struct obipipeline::throttle::Throttled<T>
|
||||||
|
pub obipipeline::throttle::Throttled::guard: obipipeline::throttle::ThrottleGuard
|
||||||
|
pub obipipeline::throttle::Throttled::item: T
|
||||||
|
impl<T> core::marker::Forget for obipipeline::throttle::Throttled<T>
|
||||||
|
impl<T> core::marker::Freeze for obipipeline::throttle::Throttled<T> where T: core::marker::Freeze
|
||||||
|
impl<T> core::marker::Move for obipipeline::throttle::Throttled<T>
|
||||||
|
impl<T> core::marker::Send for obipipeline::throttle::Throttled<T> where T: core::marker::Send
|
||||||
|
impl<T> core::marker::Sync for obipipeline::throttle::Throttled<T> where T: core::marker::Sync
|
||||||
|
impl<T> core::marker::Unpin for obipipeline::throttle::Throttled<T> where T: core::marker::Unpin
|
||||||
|
impl<T> core::marker::UnsafeUnpin for obipipeline::throttle::Throttled<T> where T: core::marker::UnsafeUnpin
|
||||||
|
impl<T> core::panic::unwind_safe::RefUnwindSafe for obipipeline::throttle::Throttled<T> where T: core::panic::unwind_safe::RefUnwindSafe
|
||||||
|
impl<T> core::panic::unwind_safe::UnwindSafe for obipipeline::throttle::Throttled<T> where T: core::panic::unwind_safe::UnwindSafe
|
||||||
|
pub fn obipipeline::throttle::throttle<I>(I, usize) -> impl core::iter::traits::iterator::Iterator<Item = obipipeline::throttle::Throttled<<I as core::iter::traits::iterator::Iterator>::Item>> where I: core::iter::traits::iterator::Iterator, <I as core::iter::traits::iterator::Iterator>::Item: core::marker::Send + 'static
|
||||||
|
pub macro obipipeline::make_flat_transform!
|
||||||
|
pub macro obipipeline::make_flat_transform_fallible!
|
||||||
|
pub macro obipipeline::make_pipe!
|
||||||
|
pub macro obipipeline::make_pipeline!
|
||||||
|
pub macro obipipeline::make_sink!
|
||||||
|
pub macro obipipeline::make_sink_fallible!
|
||||||
|
pub macro obipipeline::make_source!
|
||||||
|
pub macro obipipeline::make_source_fallible!
|
||||||
|
pub macro obipipeline::make_transform!
|
||||||
|
pub macro obipipeline::make_transform_fallible!
|
||||||
|
pub enum obipipeline::PipelineError
|
||||||
|
pub obipipeline::PipelineError::EndOfStream
|
||||||
|
pub obipipeline::PipelineError::StepError(alloc::boxed::Box<(dyn core::error::Error + core::marker::Send + core::marker::Sync)>)
|
||||||
|
pub obipipeline::PipelineError::StepKindMismatch(&'static str)
|
||||||
|
pub obipipeline::PipelineError::TypeMismatch
|
||||||
|
impl core::error::Error for obipipeline::PipelineError
|
||||||
|
pub fn obipipeline::PipelineError::source(&self) -> core::option::Option<&(dyn core::error::Error + 'static)>
|
||||||
|
impl core::fmt::Debug for obipipeline::PipelineError
|
||||||
|
pub fn obipipeline::PipelineError::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
|
||||||
|
impl core::fmt::Display for obipipeline::PipelineError
|
||||||
|
pub fn obipipeline::PipelineError::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
|
||||||
|
impl core::marker::Forget for obipipeline::PipelineError
|
||||||
|
impl core::marker::Freeze for obipipeline::PipelineError
|
||||||
|
impl core::marker::Move for obipipeline::PipelineError
|
||||||
|
impl core::marker::Send for obipipeline::PipelineError
|
||||||
|
impl core::marker::Sync for obipipeline::PipelineError
|
||||||
|
impl core::marker::Unpin for obipipeline::PipelineError
|
||||||
|
impl core::marker::UnsafeUnpin for obipipeline::PipelineError
|
||||||
|
impl !core::panic::unwind_safe::RefUnwindSafe for obipipeline::PipelineError
|
||||||
|
impl !core::panic::unwind_safe::UnwindSafe for obipipeline::PipelineError
|
||||||
|
pub enum obipipeline::Stage<D>
|
||||||
|
pub obipipeline::Stage::Flat(obipipeline::SharedFlatFn<D>)
|
||||||
|
pub obipipeline::Stage::Transform(obipipeline::SharedFn<D>)
|
||||||
|
impl<D> core::clone::Clone for obipipeline::Stage<D>
|
||||||
|
pub fn obipipeline::Stage<D>::clone(&self) -> Self
|
||||||
|
impl<D> core::marker::Forget for obipipeline::Stage<D>
|
||||||
|
impl<D> core::marker::Freeze for obipipeline::Stage<D> where alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> core::result::Result<D, obipipeline::PipelineError> + core::marker::Send + core::marker::Sync)>: core::marker::Freeze, alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D, &crossbeam_channel::channel::Sender<core::result::Result<D, obipipeline::PipelineError>>, &crossbeam_channel::channel::Sender<isize>) + core::marker::Send + core::marker::Sync)>: core::marker::Freeze
|
||||||
|
impl<D> core::marker::Move for obipipeline::Stage<D>
|
||||||
|
impl<D> core::marker::Send for obipipeline::Stage<D> where alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> core::result::Result<D, obipipeline::PipelineError> + core::marker::Send + core::marker::Sync)>: core::marker::Send, alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D, &crossbeam_channel::channel::Sender<core::result::Result<D, obipipeline::PipelineError>>, &crossbeam_channel::channel::Sender<isize>) + core::marker::Send + core::marker::Sync)>: core::marker::Send
|
||||||
|
impl<D> core::marker::Sync for obipipeline::Stage<D> where alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> core::result::Result<D, obipipeline::PipelineError> + core::marker::Send + core::marker::Sync)>: core::marker::Sync, alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D, &crossbeam_channel::channel::Sender<core::result::Result<D, obipipeline::PipelineError>>, &crossbeam_channel::channel::Sender<isize>) + core::marker::Send + core::marker::Sync)>: core::marker::Sync
|
||||||
|
impl<D> core::marker::Unpin for obipipeline::Stage<D> where alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> core::result::Result<D, obipipeline::PipelineError> + core::marker::Send + core::marker::Sync)>: core::marker::Unpin, alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D, &crossbeam_channel::channel::Sender<core::result::Result<D, obipipeline::PipelineError>>, &crossbeam_channel::channel::Sender<isize>) + core::marker::Send + core::marker::Sync)>: core::marker::Unpin
|
||||||
|
impl<D> core::marker::UnsafeUnpin for obipipeline::Stage<D> where alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> core::result::Result<D, obipipeline::PipelineError> + core::marker::Send + core::marker::Sync)>: core::marker::UnsafeUnpin, alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D, &crossbeam_channel::channel::Sender<core::result::Result<D, obipipeline::PipelineError>>, &crossbeam_channel::channel::Sender<isize>) + core::marker::Send + core::marker::Sync)>: core::marker::UnsafeUnpin
|
||||||
|
impl<D> !core::panic::unwind_safe::RefUnwindSafe for obipipeline::Stage<D>
|
||||||
|
impl<D> !core::panic::unwind_safe::UnwindSafe for obipipeline::Stage<D>
|
||||||
|
pub struct obipipeline::Pipe<D, In, Out>
|
||||||
|
impl<D, In, Out> obipipeline::Pipe<D, In, Out> where D: core::marker::Send + core::marker::Sync + 'static, In: core::marker::Send + 'static, Out: core::marker::Send + 'static
|
||||||
|
pub fn obipipeline::Pipe<D, In, Out>::apply(self, impl core::iter::traits::iterator::Iterator<Item = In> + core::marker::Send + 'static, usize, usize) -> obipipeline::PipeIter<Out>
|
||||||
|
impl<D, In, Out> obipipeline::Pipe<D, In, Out>
|
||||||
|
pub fn obipipeline::Pipe<D, In, Out>::new(alloc::vec::Vec<obipipeline::Stage<D>>, alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(In) -> D + core::marker::Send + core::marker::Sync)>, alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> Out + core::marker::Send + core::marker::Sync)>) -> Self
|
||||||
|
pub fn obipipeline::Pipe<D, In, Out>::then<Next>(self, obipipeline::Pipe<D, Out, Next>) -> obipipeline::Pipe<D, In, Next>
|
||||||
|
impl<D, In, Out> core::marker::Forget for obipipeline::Pipe<D, In, Out>
|
||||||
|
impl<D, In, Out> core::marker::Freeze for obipipeline::Pipe<D, In, Out> where alloc::vec::Vec<obipipeline::Stage<D>>: core::marker::Freeze, alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(In) -> D + core::marker::Send + core::marker::Sync)>: core::marker::Freeze, alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> Out + core::marker::Send + core::marker::Sync)>: core::marker::Freeze, core::marker::PhantomData<(In, Out)>: core::marker::Freeze
|
||||||
|
impl<D, In, Out> core::marker::Move for obipipeline::Pipe<D, In, Out>
|
||||||
|
impl<D, In, Out> core::marker::Send for obipipeline::Pipe<D, In, Out> where alloc::vec::Vec<obipipeline::Stage<D>>: core::marker::Send, alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(In) -> D + core::marker::Send + core::marker::Sync)>: core::marker::Send, alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> Out + core::marker::Send + core::marker::Sync)>: core::marker::Send, core::marker::PhantomData<(In, Out)>: core::marker::Send
|
||||||
|
impl<D, In, Out> core::marker::Sync for obipipeline::Pipe<D, In, Out> where alloc::vec::Vec<obipipeline::Stage<D>>: core::marker::Sync, alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(In) -> D + core::marker::Send + core::marker::Sync)>: core::marker::Sync, alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> Out + core::marker::Send + core::marker::Sync)>: core::marker::Sync, core::marker::PhantomData<(In, Out)>: core::marker::Sync
|
||||||
|
impl<D, In, Out> core::marker::Unpin for obipipeline::Pipe<D, In, Out> where alloc::vec::Vec<obipipeline::Stage<D>>: core::marker::Unpin, alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(In) -> D + core::marker::Send + core::marker::Sync)>: core::marker::Unpin, alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> Out + core::marker::Send + core::marker::Sync)>: core::marker::Unpin, core::marker::PhantomData<(In, Out)>: core::marker::Unpin
|
||||||
|
impl<D, In, Out> core::marker::UnsafeUnpin for obipipeline::Pipe<D, In, Out> where alloc::vec::Vec<obipipeline::Stage<D>>: core::marker::UnsafeUnpin, alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(In) -> D + core::marker::Send + core::marker::Sync)>: core::marker::UnsafeUnpin, alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> Out + core::marker::Send + core::marker::Sync)>: core::marker::UnsafeUnpin, core::marker::PhantomData<(In, Out)>: core::marker::UnsafeUnpin
|
||||||
|
impl<D, In, Out> !core::panic::unwind_safe::RefUnwindSafe for obipipeline::Pipe<D, In, Out>
|
||||||
|
impl<D, In, Out> !core::panic::unwind_safe::UnwindSafe for obipipeline::Pipe<D, In, Out>
|
||||||
|
pub struct obipipeline::PipeIter<Out>
|
||||||
|
impl<Out> core::iter::traits::iterator::Iterator for obipipeline::PipeIter<Out>
|
||||||
|
pub type obipipeline::PipeIter<Out>::Item = Out
|
||||||
|
pub fn obipipeline::PipeIter<Out>::next(&mut self) -> core::option::Option<Out>
|
||||||
|
impl<Out> core::ops::drop::Drop for obipipeline::PipeIter<Out>
|
||||||
|
pub fn obipipeline::PipeIter<Out>::drop(&mut self)
|
||||||
|
impl<Out> core::marker::Forget for obipipeline::PipeIter<Out>
|
||||||
|
impl<Out> core::marker::Freeze for obipipeline::PipeIter<Out> where core::option::Option<crossbeam_channel::channel::Receiver<Out>>: core::marker::Freeze
|
||||||
|
impl<Out> core::marker::Move for obipipeline::PipeIter<Out>
|
||||||
|
impl<Out> core::marker::Send for obipipeline::PipeIter<Out> where core::option::Option<crossbeam_channel::channel::Receiver<Out>>: core::marker::Send
|
||||||
|
impl<Out> core::marker::Sync for obipipeline::PipeIter<Out> where core::option::Option<crossbeam_channel::channel::Receiver<Out>>: core::marker::Sync
|
||||||
|
impl<Out> core::marker::Unpin for obipipeline::PipeIter<Out> where core::option::Option<crossbeam_channel::channel::Receiver<Out>>: core::marker::Unpin
|
||||||
|
impl<Out> core::marker::UnsafeUnpin for obipipeline::PipeIter<Out> where core::option::Option<crossbeam_channel::channel::Receiver<Out>>: core::marker::UnsafeUnpin
|
||||||
|
impl<Out> !core::panic::unwind_safe::RefUnwindSafe for obipipeline::PipeIter<Out>
|
||||||
|
impl<Out> !core::panic::unwind_safe::UnwindSafe for obipipeline::PipeIter<Out>
|
||||||
|
pub struct obipipeline::Pipeline<DATA>
|
||||||
|
impl<DATA> obipipeline::Pipeline<DATA>
|
||||||
|
pub fn obipipeline::Pipeline<DATA>::new(obipipeline::SourceFn<DATA>, alloc::vec::Vec<obipipeline::Stage<DATA>>, obipipeline::SinkFn<DATA>) -> Self
|
||||||
|
impl<DATA> core::marker::Forget for obipipeline::Pipeline<DATA>
|
||||||
|
impl<DATA> core::marker::Freeze for obipipeline::Pipeline<DATA> where alloc::boxed::Box<(dyn core::ops::function::FnMut() -> core::result::Result<DATA, obipipeline::PipelineError> + core::marker::Send)>: core::marker::Freeze, alloc::vec::Vec<obipipeline::Stage<DATA>>: core::marker::Freeze, alloc::boxed::Box<(dyn core::ops::function::Fn(DATA) -> core::result::Result<(), obipipeline::PipelineError> + core::marker::Send)>: core::marker::Freeze
|
||||||
|
impl<DATA> core::marker::Move for obipipeline::Pipeline<DATA>
|
||||||
|
impl<DATA> core::marker::Send for obipipeline::Pipeline<DATA> where alloc::boxed::Box<(dyn core::ops::function::FnMut() -> core::result::Result<DATA, obipipeline::PipelineError> + core::marker::Send)>: core::marker::Send, alloc::vec::Vec<obipipeline::Stage<DATA>>: core::marker::Send, alloc::boxed::Box<(dyn core::ops::function::Fn(DATA) -> core::result::Result<(), obipipeline::PipelineError> + core::marker::Send)>: core::marker::Send
|
||||||
|
impl<DATA> !core::marker::Sync for obipipeline::Pipeline<DATA>
|
||||||
|
impl<DATA> core::marker::Unpin for obipipeline::Pipeline<DATA> where alloc::boxed::Box<(dyn core::ops::function::FnMut() -> core::result::Result<DATA, obipipeline::PipelineError> + core::marker::Send)>: core::marker::Unpin, alloc::vec::Vec<obipipeline::Stage<DATA>>: core::marker::Unpin, alloc::boxed::Box<(dyn core::ops::function::Fn(DATA) -> core::result::Result<(), obipipeline::PipelineError> + core::marker::Send)>: core::marker::Unpin
|
||||||
|
impl<DATA> core::marker::UnsafeUnpin for obipipeline::Pipeline<DATA> where alloc::boxed::Box<(dyn core::ops::function::FnMut() -> core::result::Result<DATA, obipipeline::PipelineError> + core::marker::Send)>: core::marker::UnsafeUnpin, alloc::vec::Vec<obipipeline::Stage<DATA>>: core::marker::UnsafeUnpin, alloc::boxed::Box<(dyn core::ops::function::Fn(DATA) -> core::result::Result<(), obipipeline::PipelineError> + core::marker::Send)>: core::marker::UnsafeUnpin
|
||||||
|
impl<DATA> !core::panic::unwind_safe::RefUnwindSafe for obipipeline::Pipeline<DATA>
|
||||||
|
impl<DATA> !core::panic::unwind_safe::UnwindSafe for obipipeline::Pipeline<DATA>
|
||||||
|
pub struct obipipeline::Throttle
|
||||||
|
impl obipipeline::throttle::Throttle
|
||||||
|
pub fn obipipeline::throttle::Throttle::acquire(&self)
|
||||||
|
pub fn obipipeline::throttle::Throttle::new(usize) -> Self
|
||||||
|
impl obipipeline::throttle::Throttle
|
||||||
|
pub fn obipipeline::throttle::Throttle::acquire_guard(&alloc::rcs::arc::Arc<Self>) -> obipipeline::throttle::ThrottleGuard
|
||||||
|
impl core::marker::Forget for obipipeline::throttle::Throttle
|
||||||
|
impl !core::marker::Freeze for obipipeline::throttle::Throttle
|
||||||
|
impl core::marker::Move for obipipeline::throttle::Throttle
|
||||||
|
impl core::marker::Send for obipipeline::throttle::Throttle
|
||||||
|
impl core::marker::Sync for obipipeline::throttle::Throttle
|
||||||
|
impl core::marker::Unpin for obipipeline::throttle::Throttle
|
||||||
|
impl core::marker::UnsafeUnpin for obipipeline::throttle::Throttle
|
||||||
|
impl core::panic::unwind_safe::RefUnwindSafe for obipipeline::throttle::Throttle
|
||||||
|
impl core::panic::unwind_safe::UnwindSafe for obipipeline::throttle::Throttle
|
||||||
|
pub struct obipipeline::ThrottleGuard(_)
|
||||||
|
impl core::ops::drop::Drop for obipipeline::throttle::ThrottleGuard
|
||||||
|
pub fn obipipeline::throttle::ThrottleGuard::drop(&mut self)
|
||||||
|
impl core::marker::Forget for obipipeline::throttle::ThrottleGuard
|
||||||
|
impl core::marker::Freeze for obipipeline::throttle::ThrottleGuard
|
||||||
|
impl core::marker::Move for obipipeline::throttle::ThrottleGuard
|
||||||
|
impl core::marker::Send for obipipeline::throttle::ThrottleGuard
|
||||||
|
impl core::marker::Sync for obipipeline::throttle::ThrottleGuard
|
||||||
|
impl core::marker::Unpin for obipipeline::throttle::ThrottleGuard
|
||||||
|
impl core::marker::UnsafeUnpin for obipipeline::throttle::ThrottleGuard
|
||||||
|
impl core::panic::unwind_safe::RefUnwindSafe for obipipeline::throttle::ThrottleGuard
|
||||||
|
impl core::panic::unwind_safe::UnwindSafe for obipipeline::throttle::ThrottleGuard
|
||||||
|
pub struct obipipeline::Throttled<T>
|
||||||
|
pub obipipeline::Throttled::guard: obipipeline::throttle::ThrottleGuard
|
||||||
|
pub obipipeline::Throttled::item: T
|
||||||
|
impl<T> core::marker::Forget for obipipeline::throttle::Throttled<T>
|
||||||
|
impl<T> core::marker::Freeze for obipipeline::throttle::Throttled<T> where T: core::marker::Freeze
|
||||||
|
impl<T> core::marker::Move for obipipeline::throttle::Throttled<T>
|
||||||
|
impl<T> core::marker::Send for obipipeline::throttle::Throttled<T> where T: core::marker::Send
|
||||||
|
impl<T> core::marker::Sync for obipipeline::throttle::Throttled<T> where T: core::marker::Sync
|
||||||
|
impl<T> core::marker::Unpin for obipipeline::throttle::Throttled<T> where T: core::marker::Unpin
|
||||||
|
impl<T> core::marker::UnsafeUnpin for obipipeline::throttle::Throttled<T> where T: core::marker::UnsafeUnpin
|
||||||
|
impl<T> core::panic::unwind_safe::RefUnwindSafe for obipipeline::throttle::Throttled<T> where T: core::panic::unwind_safe::RefUnwindSafe
|
||||||
|
impl<T> core::panic::unwind_safe::UnwindSafe for obipipeline::throttle::Throttled<T> where T: core::panic::unwind_safe::UnwindSafe
|
||||||
|
pub struct obipipeline::WorkerPool<DATA>
|
||||||
|
impl<DATA> obipipeline::WorkerPool<DATA> where DATA: core::marker::Send + core::marker::Sync + 'static
|
||||||
|
pub fn obipipeline::WorkerPool<DATA>::new(obipipeline::Pipeline<DATA>, usize, usize) -> Self
|
||||||
|
pub fn obipipeline::WorkerPool<DATA>::run(self)
|
||||||
|
impl<DATA> core::marker::Forget for obipipeline::WorkerPool<DATA>
|
||||||
|
impl<DATA> core::marker::Freeze for obipipeline::WorkerPool<DATA> where obipipeline::Pipeline<DATA>: core::marker::Freeze
|
||||||
|
impl<DATA> core::marker::Move for obipipeline::WorkerPool<DATA>
|
||||||
|
impl<DATA> core::marker::Send for obipipeline::WorkerPool<DATA> where obipipeline::Pipeline<DATA>: core::marker::Send
|
||||||
|
impl<DATA> !core::marker::Sync for obipipeline::WorkerPool<DATA>
|
||||||
|
impl<DATA> core::marker::Unpin for obipipeline::WorkerPool<DATA> where obipipeline::Pipeline<DATA>: core::marker::Unpin
|
||||||
|
impl<DATA> core::marker::UnsafeUnpin for obipipeline::WorkerPool<DATA> where obipipeline::Pipeline<DATA>: core::marker::UnsafeUnpin
|
||||||
|
impl<DATA> !core::panic::unwind_safe::RefUnwindSafe for obipipeline::WorkerPool<DATA>
|
||||||
|
impl<DATA> !core::panic::unwind_safe::UnwindSafe for obipipeline::WorkerPool<DATA>
|
||||||
|
pub fn obipipeline::throttle<I>(I, usize) -> impl core::iter::traits::iterator::Iterator<Item = obipipeline::throttle::Throttled<<I as core::iter::traits::iterator::Iterator>::Item>> where I: core::iter::traits::iterator::Iterator, <I as core::iter::traits::iterator::Iterator>::Item: core::marker::Send + 'static
|
||||||
|
pub type obipipeline::SharedFlatFn<D> = alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D, &crossbeam_channel::channel::Sender<core::result::Result<D, obipipeline::PipelineError>>, &crossbeam_channel::channel::Sender<isize>) + core::marker::Send + core::marker::Sync)>
|
||||||
|
pub type obipipeline::SharedFn<D> = alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> core::result::Result<D, obipipeline::PipelineError> + core::marker::Send + core::marker::Sync)>
|
||||||
|
pub type obipipeline::SinkFn<D> = alloc::boxed::Box<(dyn core::ops::function::Fn(D) -> core::result::Result<(), obipipeline::PipelineError> + core::marker::Send)>
|
||||||
|
pub type obipipeline::SourceFn<D> = alloc::boxed::Box<(dyn core::ops::function::FnMut() -> core::result::Result<D, obipipeline::PipelineError> + core::marker::Send)>
|
||||||
Binary file not shown.
@@ -0,0 +1 @@
|
|||||||
|
rustc 1.100.0 (0ef1bc386 2026-11-09) | cargo-public-api 0.52.0
|
||||||
+186
@@ -0,0 +1,186 @@
|
|||||||
|
pub mod obipipeline
|
||||||
|
pub use obipipeline::PipelineSender
|
||||||
|
pub mod obipipeline::throttle
|
||||||
|
pub struct obipipeline::throttle::Throttle
|
||||||
|
impl obipipeline::throttle::Throttle
|
||||||
|
pub fn obipipeline::throttle::Throttle::acquire(&self)
|
||||||
|
pub fn obipipeline::throttle::Throttle::new(usize) -> Self
|
||||||
|
impl obipipeline::throttle::Throttle
|
||||||
|
pub fn obipipeline::throttle::Throttle::acquire_guard(&alloc::rcs::arc::Arc<Self>) -> obipipeline::throttle::ThrottleGuard
|
||||||
|
impl core::marker::Forget for obipipeline::throttle::Throttle
|
||||||
|
impl !core::marker::Freeze for obipipeline::throttle::Throttle
|
||||||
|
impl core::marker::Move for obipipeline::throttle::Throttle
|
||||||
|
impl core::marker::Send for obipipeline::throttle::Throttle
|
||||||
|
impl core::marker::Sync for obipipeline::throttle::Throttle
|
||||||
|
impl core::marker::Unpin for obipipeline::throttle::Throttle
|
||||||
|
impl core::marker::UnsafeUnpin for obipipeline::throttle::Throttle
|
||||||
|
impl core::panic::unwind_safe::RefUnwindSafe for obipipeline::throttle::Throttle
|
||||||
|
impl core::panic::unwind_safe::UnwindSafe for obipipeline::throttle::Throttle
|
||||||
|
pub struct obipipeline::throttle::ThrottleGuard(_)
|
||||||
|
impl core::ops::drop::Drop for obipipeline::throttle::ThrottleGuard
|
||||||
|
pub fn obipipeline::throttle::ThrottleGuard::drop(&mut self)
|
||||||
|
impl core::marker::Forget for obipipeline::throttle::ThrottleGuard
|
||||||
|
impl core::marker::Freeze for obipipeline::throttle::ThrottleGuard
|
||||||
|
impl core::marker::Move for obipipeline::throttle::ThrottleGuard
|
||||||
|
impl core::marker::Send for obipipeline::throttle::ThrottleGuard
|
||||||
|
impl core::marker::Sync for obipipeline::throttle::ThrottleGuard
|
||||||
|
impl core::marker::Unpin for obipipeline::throttle::ThrottleGuard
|
||||||
|
impl core::marker::UnsafeUnpin for obipipeline::throttle::ThrottleGuard
|
||||||
|
impl core::panic::unwind_safe::RefUnwindSafe for obipipeline::throttle::ThrottleGuard
|
||||||
|
impl core::panic::unwind_safe::UnwindSafe for obipipeline::throttle::ThrottleGuard
|
||||||
|
pub struct obipipeline::throttle::Throttled<T>
|
||||||
|
pub obipipeline::throttle::Throttled::guard: obipipeline::throttle::ThrottleGuard
|
||||||
|
pub obipipeline::throttle::Throttled::item: T
|
||||||
|
impl<T> core::marker::Forget for obipipeline::throttle::Throttled<T>
|
||||||
|
impl<T> core::marker::Freeze for obipipeline::throttle::Throttled<T> where T: core::marker::Freeze
|
||||||
|
impl<T> core::marker::Move for obipipeline::throttle::Throttled<T>
|
||||||
|
impl<T> core::marker::Send for obipipeline::throttle::Throttled<T> where T: core::marker::Send
|
||||||
|
impl<T> core::marker::Sync for obipipeline::throttle::Throttled<T> where T: core::marker::Sync
|
||||||
|
impl<T> core::marker::Unpin for obipipeline::throttle::Throttled<T> where T: core::marker::Unpin
|
||||||
|
impl<T> core::marker::UnsafeUnpin for obipipeline::throttle::Throttled<T> where T: core::marker::UnsafeUnpin
|
||||||
|
impl<T> core::panic::unwind_safe::RefUnwindSafe for obipipeline::throttle::Throttled<T> where T: core::panic::unwind_safe::RefUnwindSafe
|
||||||
|
impl<T> core::panic::unwind_safe::UnwindSafe for obipipeline::throttle::Throttled<T> where T: core::panic::unwind_safe::UnwindSafe
|
||||||
|
pub fn obipipeline::throttle::throttle<I>(I, usize) -> impl core::iter::traits::iterator::Iterator<Item = obipipeline::throttle::Throttled<<I as core::iter::traits::iterator::Iterator>::Item>> where I: core::iter::traits::iterator::Iterator, <I as core::iter::traits::iterator::Iterator>::Item: core::marker::Send + 'static
|
||||||
|
pub macro obipipeline::make_flat_transform!
|
||||||
|
pub macro obipipeline::make_flat_transform_fallible!
|
||||||
|
pub macro obipipeline::make_pipe!
|
||||||
|
pub macro obipipeline::make_pipeline!
|
||||||
|
pub macro obipipeline::make_sink!
|
||||||
|
pub macro obipipeline::make_sink_fallible!
|
||||||
|
pub macro obipipeline::make_source!
|
||||||
|
pub macro obipipeline::make_source_fallible!
|
||||||
|
pub macro obipipeline::make_transform!
|
||||||
|
pub macro obipipeline::make_transform_fallible!
|
||||||
|
pub enum obipipeline::PipelineError
|
||||||
|
pub obipipeline::PipelineError::EndOfStream
|
||||||
|
pub obipipeline::PipelineError::StepError(alloc::boxed::Box<(dyn core::error::Error + core::marker::Send + core::marker::Sync)>)
|
||||||
|
pub obipipeline::PipelineError::StepKindMismatch(&'static str)
|
||||||
|
pub obipipeline::PipelineError::TypeMismatch
|
||||||
|
impl core::error::Error for obipipeline::PipelineError
|
||||||
|
pub fn obipipeline::PipelineError::source(&self) -> core::option::Option<&(dyn core::error::Error + 'static)>
|
||||||
|
impl core::fmt::Debug for obipipeline::PipelineError
|
||||||
|
pub fn obipipeline::PipelineError::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
|
||||||
|
impl core::fmt::Display for obipipeline::PipelineError
|
||||||
|
pub fn obipipeline::PipelineError::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
|
||||||
|
impl core::marker::Forget for obipipeline::PipelineError
|
||||||
|
impl core::marker::Freeze for obipipeline::PipelineError
|
||||||
|
impl core::marker::Move for obipipeline::PipelineError
|
||||||
|
impl core::marker::Send for obipipeline::PipelineError
|
||||||
|
impl core::marker::Sync for obipipeline::PipelineError
|
||||||
|
impl core::marker::Unpin for obipipeline::PipelineError
|
||||||
|
impl core::marker::UnsafeUnpin for obipipeline::PipelineError
|
||||||
|
impl !core::panic::unwind_safe::RefUnwindSafe for obipipeline::PipelineError
|
||||||
|
impl !core::panic::unwind_safe::UnwindSafe for obipipeline::PipelineError
|
||||||
|
pub enum obipipeline::Stage<D>
|
||||||
|
pub obipipeline::Stage::Flat(obipipeline::SharedFlatFn<D>)
|
||||||
|
pub obipipeline::Stage::Transform(obipipeline::SharedFn<D>)
|
||||||
|
impl<D> core::clone::Clone for obipipeline::Stage<D>
|
||||||
|
pub fn obipipeline::Stage<D>::clone(&self) -> Self
|
||||||
|
impl<D> core::marker::Forget for obipipeline::Stage<D>
|
||||||
|
impl<D> core::marker::Freeze for obipipeline::Stage<D> where alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> core::result::Result<D, obipipeline::PipelineError> + core::marker::Send + core::marker::Sync)>: core::marker::Freeze, alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D, &crossbeam_channel::channel::Sender<core::result::Result<D, obipipeline::PipelineError>>, &crossbeam_channel::channel::Sender<isize>) + core::marker::Send + core::marker::Sync)>: core::marker::Freeze
|
||||||
|
impl<D> core::marker::Move for obipipeline::Stage<D>
|
||||||
|
impl<D> core::marker::Send for obipipeline::Stage<D> where alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> core::result::Result<D, obipipeline::PipelineError> + core::marker::Send + core::marker::Sync)>: core::marker::Send, alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D, &crossbeam_channel::channel::Sender<core::result::Result<D, obipipeline::PipelineError>>, &crossbeam_channel::channel::Sender<isize>) + core::marker::Send + core::marker::Sync)>: core::marker::Send
|
||||||
|
impl<D> core::marker::Sync for obipipeline::Stage<D> where alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> core::result::Result<D, obipipeline::PipelineError> + core::marker::Send + core::marker::Sync)>: core::marker::Sync, alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D, &crossbeam_channel::channel::Sender<core::result::Result<D, obipipeline::PipelineError>>, &crossbeam_channel::channel::Sender<isize>) + core::marker::Send + core::marker::Sync)>: core::marker::Sync
|
||||||
|
impl<D> core::marker::Unpin for obipipeline::Stage<D> where alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> core::result::Result<D, obipipeline::PipelineError> + core::marker::Send + core::marker::Sync)>: core::marker::Unpin, alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D, &crossbeam_channel::channel::Sender<core::result::Result<D, obipipeline::PipelineError>>, &crossbeam_channel::channel::Sender<isize>) + core::marker::Send + core::marker::Sync)>: core::marker::Unpin
|
||||||
|
impl<D> core::marker::UnsafeUnpin for obipipeline::Stage<D> where alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> core::result::Result<D, obipipeline::PipelineError> + core::marker::Send + core::marker::Sync)>: core::marker::UnsafeUnpin, alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D, &crossbeam_channel::channel::Sender<core::result::Result<D, obipipeline::PipelineError>>, &crossbeam_channel::channel::Sender<isize>) + core::marker::Send + core::marker::Sync)>: core::marker::UnsafeUnpin
|
||||||
|
impl<D> !core::panic::unwind_safe::RefUnwindSafe for obipipeline::Stage<D>
|
||||||
|
impl<D> !core::panic::unwind_safe::UnwindSafe for obipipeline::Stage<D>
|
||||||
|
pub struct obipipeline::Pipe<D, In, Out>
|
||||||
|
impl<D, In, Out> obipipeline::Pipe<D, In, Out> where D: core::marker::Send + core::marker::Sync + 'static, In: core::marker::Send + 'static, Out: core::marker::Send + 'static
|
||||||
|
pub fn obipipeline::Pipe<D, In, Out>::apply(self, impl core::iter::traits::iterator::Iterator<Item = In> + core::marker::Send + 'static, usize, usize) -> obipipeline::PipeIter<Out>
|
||||||
|
impl<D, In, Out> obipipeline::Pipe<D, In, Out>
|
||||||
|
pub fn obipipeline::Pipe<D, In, Out>::new(alloc::vec::Vec<obipipeline::Stage<D>>, alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(In) -> D + core::marker::Send + core::marker::Sync)>, alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> Out + core::marker::Send + core::marker::Sync)>) -> Self
|
||||||
|
pub fn obipipeline::Pipe<D, In, Out>::then<Next>(self, obipipeline::Pipe<D, Out, Next>) -> obipipeline::Pipe<D, In, Next>
|
||||||
|
impl<D, In, Out> core::marker::Forget for obipipeline::Pipe<D, In, Out>
|
||||||
|
impl<D, In, Out> core::marker::Freeze for obipipeline::Pipe<D, In, Out> where alloc::vec::Vec<obipipeline::Stage<D>>: core::marker::Freeze, alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(In) -> D + core::marker::Send + core::marker::Sync)>: core::marker::Freeze, alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> Out + core::marker::Send + core::marker::Sync)>: core::marker::Freeze, core::marker::PhantomData<(In, Out)>: core::marker::Freeze
|
||||||
|
impl<D, In, Out> core::marker::Move for obipipeline::Pipe<D, In, Out>
|
||||||
|
impl<D, In, Out> core::marker::Send for obipipeline::Pipe<D, In, Out> where alloc::vec::Vec<obipipeline::Stage<D>>: core::marker::Send, alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(In) -> D + core::marker::Send + core::marker::Sync)>: core::marker::Send, alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> Out + core::marker::Send + core::marker::Sync)>: core::marker::Send, core::marker::PhantomData<(In, Out)>: core::marker::Send
|
||||||
|
impl<D, In, Out> core::marker::Sync for obipipeline::Pipe<D, In, Out> where alloc::vec::Vec<obipipeline::Stage<D>>: core::marker::Sync, alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(In) -> D + core::marker::Send + core::marker::Sync)>: core::marker::Sync, alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> Out + core::marker::Send + core::marker::Sync)>: core::marker::Sync, core::marker::PhantomData<(In, Out)>: core::marker::Sync
|
||||||
|
impl<D, In, Out> core::marker::Unpin for obipipeline::Pipe<D, In, Out> where alloc::vec::Vec<obipipeline::Stage<D>>: core::marker::Unpin, alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(In) -> D + core::marker::Send + core::marker::Sync)>: core::marker::Unpin, alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> Out + core::marker::Send + core::marker::Sync)>: core::marker::Unpin, core::marker::PhantomData<(In, Out)>: core::marker::Unpin
|
||||||
|
impl<D, In, Out> core::marker::UnsafeUnpin for obipipeline::Pipe<D, In, Out> where alloc::vec::Vec<obipipeline::Stage<D>>: core::marker::UnsafeUnpin, alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(In) -> D + core::marker::Send + core::marker::Sync)>: core::marker::UnsafeUnpin, alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> Out + core::marker::Send + core::marker::Sync)>: core::marker::UnsafeUnpin, core::marker::PhantomData<(In, Out)>: core::marker::UnsafeUnpin
|
||||||
|
impl<D, In, Out> !core::panic::unwind_safe::RefUnwindSafe for obipipeline::Pipe<D, In, Out>
|
||||||
|
impl<D, In, Out> !core::panic::unwind_safe::UnwindSafe for obipipeline::Pipe<D, In, Out>
|
||||||
|
pub struct obipipeline::PipeIter<Out>
|
||||||
|
impl<Out> core::iter::traits::iterator::Iterator for obipipeline::PipeIter<Out>
|
||||||
|
pub type obipipeline::PipeIter<Out>::Item = Out
|
||||||
|
pub fn obipipeline::PipeIter<Out>::next(&mut self) -> core::option::Option<Out>
|
||||||
|
impl<Out> core::ops::drop::Drop for obipipeline::PipeIter<Out>
|
||||||
|
pub fn obipipeline::PipeIter<Out>::drop(&mut self)
|
||||||
|
impl<Out> core::marker::Forget for obipipeline::PipeIter<Out>
|
||||||
|
impl<Out> core::marker::Freeze for obipipeline::PipeIter<Out> where core::option::Option<crossbeam_channel::channel::Receiver<Out>>: core::marker::Freeze
|
||||||
|
impl<Out> core::marker::Move for obipipeline::PipeIter<Out>
|
||||||
|
impl<Out> core::marker::Send for obipipeline::PipeIter<Out> where core::option::Option<crossbeam_channel::channel::Receiver<Out>>: core::marker::Send
|
||||||
|
impl<Out> core::marker::Sync for obipipeline::PipeIter<Out> where core::option::Option<crossbeam_channel::channel::Receiver<Out>>: core::marker::Sync
|
||||||
|
impl<Out> core::marker::Unpin for obipipeline::PipeIter<Out> where core::option::Option<crossbeam_channel::channel::Receiver<Out>>: core::marker::Unpin
|
||||||
|
impl<Out> core::marker::UnsafeUnpin for obipipeline::PipeIter<Out> where core::option::Option<crossbeam_channel::channel::Receiver<Out>>: core::marker::UnsafeUnpin
|
||||||
|
impl<Out> !core::panic::unwind_safe::RefUnwindSafe for obipipeline::PipeIter<Out>
|
||||||
|
impl<Out> !core::panic::unwind_safe::UnwindSafe for obipipeline::PipeIter<Out>
|
||||||
|
pub struct obipipeline::Pipeline<DATA>
|
||||||
|
impl<DATA> obipipeline::Pipeline<DATA>
|
||||||
|
pub fn obipipeline::Pipeline<DATA>::new(obipipeline::SourceFn<DATA>, alloc::vec::Vec<obipipeline::Stage<DATA>>, obipipeline::SinkFn<DATA>) -> Self
|
||||||
|
impl<DATA> core::marker::Forget for obipipeline::Pipeline<DATA>
|
||||||
|
impl<DATA> core::marker::Freeze for obipipeline::Pipeline<DATA> where alloc::boxed::Box<(dyn core::ops::function::FnMut() -> core::result::Result<DATA, obipipeline::PipelineError> + core::marker::Send)>: core::marker::Freeze, alloc::vec::Vec<obipipeline::Stage<DATA>>: core::marker::Freeze, alloc::boxed::Box<(dyn core::ops::function::Fn(DATA) -> core::result::Result<(), obipipeline::PipelineError> + core::marker::Send)>: core::marker::Freeze
|
||||||
|
impl<DATA> core::marker::Move for obipipeline::Pipeline<DATA>
|
||||||
|
impl<DATA> core::marker::Send for obipipeline::Pipeline<DATA> where alloc::boxed::Box<(dyn core::ops::function::FnMut() -> core::result::Result<DATA, obipipeline::PipelineError> + core::marker::Send)>: core::marker::Send, alloc::vec::Vec<obipipeline::Stage<DATA>>: core::marker::Send, alloc::boxed::Box<(dyn core::ops::function::Fn(DATA) -> core::result::Result<(), obipipeline::PipelineError> + core::marker::Send)>: core::marker::Send
|
||||||
|
impl<DATA> !core::marker::Sync for obipipeline::Pipeline<DATA>
|
||||||
|
impl<DATA> core::marker::Unpin for obipipeline::Pipeline<DATA> where alloc::boxed::Box<(dyn core::ops::function::FnMut() -> core::result::Result<DATA, obipipeline::PipelineError> + core::marker::Send)>: core::marker::Unpin, alloc::vec::Vec<obipipeline::Stage<DATA>>: core::marker::Unpin, alloc::boxed::Box<(dyn core::ops::function::Fn(DATA) -> core::result::Result<(), obipipeline::PipelineError> + core::marker::Send)>: core::marker::Unpin
|
||||||
|
impl<DATA> core::marker::UnsafeUnpin for obipipeline::Pipeline<DATA> where alloc::boxed::Box<(dyn core::ops::function::FnMut() -> core::result::Result<DATA, obipipeline::PipelineError> + core::marker::Send)>: core::marker::UnsafeUnpin, alloc::vec::Vec<obipipeline::Stage<DATA>>: core::marker::UnsafeUnpin, alloc::boxed::Box<(dyn core::ops::function::Fn(DATA) -> core::result::Result<(), obipipeline::PipelineError> + core::marker::Send)>: core::marker::UnsafeUnpin
|
||||||
|
impl<DATA> !core::panic::unwind_safe::RefUnwindSafe for obipipeline::Pipeline<DATA>
|
||||||
|
impl<DATA> !core::panic::unwind_safe::UnwindSafe for obipipeline::Pipeline<DATA>
|
||||||
|
pub struct obipipeline::Throttle
|
||||||
|
impl obipipeline::throttle::Throttle
|
||||||
|
pub fn obipipeline::throttle::Throttle::acquire(&self)
|
||||||
|
pub fn obipipeline::throttle::Throttle::new(usize) -> Self
|
||||||
|
impl obipipeline::throttle::Throttle
|
||||||
|
pub fn obipipeline::throttle::Throttle::acquire_guard(&alloc::rcs::arc::Arc<Self>) -> obipipeline::throttle::ThrottleGuard
|
||||||
|
impl core::marker::Forget for obipipeline::throttle::Throttle
|
||||||
|
impl !core::marker::Freeze for obipipeline::throttle::Throttle
|
||||||
|
impl core::marker::Move for obipipeline::throttle::Throttle
|
||||||
|
impl core::marker::Send for obipipeline::throttle::Throttle
|
||||||
|
impl core::marker::Sync for obipipeline::throttle::Throttle
|
||||||
|
impl core::marker::Unpin for obipipeline::throttle::Throttle
|
||||||
|
impl core::marker::UnsafeUnpin for obipipeline::throttle::Throttle
|
||||||
|
impl core::panic::unwind_safe::RefUnwindSafe for obipipeline::throttle::Throttle
|
||||||
|
impl core::panic::unwind_safe::UnwindSafe for obipipeline::throttle::Throttle
|
||||||
|
pub struct obipipeline::ThrottleGuard(_)
|
||||||
|
impl core::ops::drop::Drop for obipipeline::throttle::ThrottleGuard
|
||||||
|
pub fn obipipeline::throttle::ThrottleGuard::drop(&mut self)
|
||||||
|
impl core::marker::Forget for obipipeline::throttle::ThrottleGuard
|
||||||
|
impl core::marker::Freeze for obipipeline::throttle::ThrottleGuard
|
||||||
|
impl core::marker::Move for obipipeline::throttle::ThrottleGuard
|
||||||
|
impl core::marker::Send for obipipeline::throttle::ThrottleGuard
|
||||||
|
impl core::marker::Sync for obipipeline::throttle::ThrottleGuard
|
||||||
|
impl core::marker::Unpin for obipipeline::throttle::ThrottleGuard
|
||||||
|
impl core::marker::UnsafeUnpin for obipipeline::throttle::ThrottleGuard
|
||||||
|
impl core::panic::unwind_safe::RefUnwindSafe for obipipeline::throttle::ThrottleGuard
|
||||||
|
impl core::panic::unwind_safe::UnwindSafe for obipipeline::throttle::ThrottleGuard
|
||||||
|
pub struct obipipeline::Throttled<T>
|
||||||
|
pub obipipeline::Throttled::guard: obipipeline::throttle::ThrottleGuard
|
||||||
|
pub obipipeline::Throttled::item: T
|
||||||
|
impl<T> core::marker::Forget for obipipeline::throttle::Throttled<T>
|
||||||
|
impl<T> core::marker::Freeze for obipipeline::throttle::Throttled<T> where T: core::marker::Freeze
|
||||||
|
impl<T> core::marker::Move for obipipeline::throttle::Throttled<T>
|
||||||
|
impl<T> core::marker::Send for obipipeline::throttle::Throttled<T> where T: core::marker::Send
|
||||||
|
impl<T> core::marker::Sync for obipipeline::throttle::Throttled<T> where T: core::marker::Sync
|
||||||
|
impl<T> core::marker::Unpin for obipipeline::throttle::Throttled<T> where T: core::marker::Unpin
|
||||||
|
impl<T> core::marker::UnsafeUnpin for obipipeline::throttle::Throttled<T> where T: core::marker::UnsafeUnpin
|
||||||
|
impl<T> core::panic::unwind_safe::RefUnwindSafe for obipipeline::throttle::Throttled<T> where T: core::panic::unwind_safe::RefUnwindSafe
|
||||||
|
impl<T> core::panic::unwind_safe::UnwindSafe for obipipeline::throttle::Throttled<T> where T: core::panic::unwind_safe::UnwindSafe
|
||||||
|
pub struct obipipeline::WorkerPool<DATA>
|
||||||
|
impl<DATA> obipipeline::WorkerPool<DATA> where DATA: core::marker::Send + core::marker::Sync + 'static
|
||||||
|
pub fn obipipeline::WorkerPool<DATA>::new(obipipeline::Pipeline<DATA>, usize, usize) -> Self
|
||||||
|
pub fn obipipeline::WorkerPool<DATA>::run(self)
|
||||||
|
impl<DATA> core::marker::Forget for obipipeline::WorkerPool<DATA>
|
||||||
|
impl<DATA> core::marker::Freeze for obipipeline::WorkerPool<DATA> where obipipeline::Pipeline<DATA>: core::marker::Freeze
|
||||||
|
impl<DATA> core::marker::Move for obipipeline::WorkerPool<DATA>
|
||||||
|
impl<DATA> core::marker::Send for obipipeline::WorkerPool<DATA> where obipipeline::Pipeline<DATA>: core::marker::Send
|
||||||
|
impl<DATA> !core::marker::Sync for obipipeline::WorkerPool<DATA>
|
||||||
|
impl<DATA> core::marker::Unpin for obipipeline::WorkerPool<DATA> where obipipeline::Pipeline<DATA>: core::marker::Unpin
|
||||||
|
impl<DATA> core::marker::UnsafeUnpin for obipipeline::WorkerPool<DATA> where obipipeline::Pipeline<DATA>: core::marker::UnsafeUnpin
|
||||||
|
impl<DATA> !core::panic::unwind_safe::RefUnwindSafe for obipipeline::WorkerPool<DATA>
|
||||||
|
impl<DATA> !core::panic::unwind_safe::UnwindSafe for obipipeline::WorkerPool<DATA>
|
||||||
|
pub fn obipipeline::throttle<I>(I, usize) -> impl core::iter::traits::iterator::Iterator<Item = obipipeline::throttle::Throttled<<I as core::iter::traits::iterator::Iterator>::Item>> where I: core::iter::traits::iterator::Iterator, <I as core::iter::traits::iterator::Iterator>::Item: core::marker::Send + 'static
|
||||||
|
pub type obipipeline::SharedFlatFn<D> = alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D, &crossbeam_channel::channel::Sender<core::result::Result<D, obipipeline::PipelineError>>, &crossbeam_channel::channel::Sender<isize>) + core::marker::Send + core::marker::Sync)>
|
||||||
|
pub type obipipeline::SharedFn<D> = alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> core::result::Result<D, obipipeline::PipelineError> + core::marker::Send + core::marker::Sync)>
|
||||||
|
pub type obipipeline::SinkFn<D> = alloc::boxed::Box<(dyn core::ops::function::Fn(D) -> core::result::Result<(), obipipeline::PipelineError> + core::marker::Send)>
|
||||||
|
pub type obipipeline::SourceFn<D> = alloc::boxed::Box<(dyn core::ops::function::FnMut() -> core::result::Result<D, obipipeline::PipelineError> + core::marker::Send)>
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
use obipipeline::{WorkerPool, make_pipeline};
|
||||||
|
use std::io::Error;
|
||||||
|
|
||||||
|
// ── Source iterator ───────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
struct Counter {
|
||||||
|
count: u64,
|
||||||
|
stop: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Counter {
|
||||||
|
fn new(start: u64, stop: u64) -> Self {
|
||||||
|
Self { count: start, stop }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Iterator for Counter {
|
||||||
|
type Item = u64;
|
||||||
|
|
||||||
|
fn next(&mut self) -> Option<Self::Item> {
|
||||||
|
if self.count > self.stop {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let result = self.count;
|
||||||
|
self.count += 1;
|
||||||
|
Some(result)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Transform functions ───────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
fn to_f64(x: u64) -> f64 {
|
||||||
|
x as f64
|
||||||
|
}
|
||||||
|
|
||||||
|
fn step_1(number: f64) -> String {
|
||||||
|
format!("{}", number)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn step_2(text: String) -> String {
|
||||||
|
text.chars().rev().collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn step_3(text: String) -> u64 {
|
||||||
|
let mut hash: u64 = 5381;
|
||||||
|
for byte in text.bytes() {
|
||||||
|
hash = hash.wrapping_mul(33).wrapping_add(byte as u64);
|
||||||
|
}
|
||||||
|
hash
|
||||||
|
}
|
||||||
|
|
||||||
|
fn step_4(hash: u64) -> Result<(), Error> {
|
||||||
|
println!("{}", hash);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Pipeline data type ────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
enum PipelineData {
|
||||||
|
Unsigned(u64),
|
||||||
|
Number(f64),
|
||||||
|
Text(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Main ──────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
let pipeline = make_pipeline! {
|
||||||
|
PipelineData,
|
||||||
|
source Counter::new(1000, 1010) => Unsigned,
|
||||||
|
| to_f64: Unsigned => Number,
|
||||||
|
| step_1: Number => Text,
|
||||||
|
| step_2: Text => Text,
|
||||||
|
| step_3: Text => Unsigned,
|
||||||
|
sink? step_4 @ Unsigned,
|
||||||
|
};
|
||||||
|
|
||||||
|
WorkerPool::new(pipeline, 4, 64).run();
|
||||||
|
}
|
||||||
+27
@@ -0,0 +1,27 @@
|
|||||||
|
mod scheduler;
|
||||||
|
pub mod throttle;
|
||||||
|
|
||||||
|
pub use scheduler::Pipe;
|
||||||
|
pub use scheduler::PipeIter;
|
||||||
|
pub use scheduler::Pipeline;
|
||||||
|
pub use scheduler::PipelineError;
|
||||||
|
pub use scheduler::SharedFlatFn;
|
||||||
|
pub use scheduler::SharedFn;
|
||||||
|
pub use scheduler::SinkFn;
|
||||||
|
pub use scheduler::SourceFn;
|
||||||
|
pub use scheduler::Stage;
|
||||||
|
pub use scheduler::WorkerPool;
|
||||||
|
pub use throttle::Throttle;
|
||||||
|
pub use throttle::ThrottleGuard;
|
||||||
|
pub use throttle::Throttled;
|
||||||
|
pub use throttle::throttle;
|
||||||
|
|
||||||
|
/// Re-export of `crossbeam_channel::Sender`, used by the flat transform macros.
|
||||||
|
/// It lets the `make_flat_transform!` / `make_flat_transform_fallible!` macros use
|
||||||
|
/// `$crate::PipelineSender` without the calling crate having to depend
|
||||||
|
/// on `crossbeam_channel` directly.
|
||||||
|
pub use crossbeam_channel::Sender as PipelineSender;
|
||||||
|
|
||||||
|
// make_sink, make_sink_fallible, make_source, make_source_fallible,
|
||||||
|
// make_transform, make_transform_fallible, make_flat_transform,
|
||||||
|
// make_flat_transform_fallible are exported at the crate root through #[macro_export]
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
use std::error::Error;
|
||||||
|
use std::fmt;
|
||||||
|
|
||||||
|
/// Error type for pipeline operations.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum PipelineError {
|
||||||
|
/// A stage received a `PipelineData` variant it did not expect.
|
||||||
|
TypeMismatch,
|
||||||
|
/// The step kind is not compatible with the data type.
|
||||||
|
StepKindMismatch(&'static str),
|
||||||
|
/// The source has no more data to produce.
|
||||||
|
EndOfStream,
|
||||||
|
/// An error occurred inside a stage (e.g., I/O, parsing, custom logic).
|
||||||
|
StepError(Box<dyn Error + Send + Sync>),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Display for PipelineError {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
match self {
|
||||||
|
PipelineError::TypeMismatch => write!(f, "data type mismatch in pipeline stage"),
|
||||||
|
PipelineError::StepKindMismatch(s) => write!(f, "step kind mismatch: {}", s),
|
||||||
|
PipelineError::EndOfStream => write!(f, "end of input stream"),
|
||||||
|
PipelineError::StepError(e) => write!(f, "stage error: {}", e),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Error for PipelineError {
|
||||||
|
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
||||||
|
match self {
|
||||||
|
PipelineError::StepError(e) => Some(e.as_ref()),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,357 @@
|
|||||||
|
// ── Macros ────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/// Creates a `SourceFn` from an iterator of plain values.
|
||||||
|
#[macro_export]
|
||||||
|
macro_rules! make_source {
|
||||||
|
($enum:ident, $iterator:expr, $output:ident) => {{
|
||||||
|
let mut iter = $iterator.into_iter();
|
||||||
|
Box::new(
|
||||||
|
move || -> ::std::result::Result<$enum, $crate::PipelineError> {
|
||||||
|
match iter.next() {
|
||||||
|
Some(x) => Ok($enum::$output(x)),
|
||||||
|
None => Err($crate::PipelineError::EndOfStream),
|
||||||
|
}
|
||||||
|
},
|
||||||
|
) as Box<dyn FnMut() -> ::std::result::Result<$enum, $crate::PipelineError> + Send>
|
||||||
|
}};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Creates a `SourceFn` from an iterator of `Result<T, E>`.
|
||||||
|
#[macro_export]
|
||||||
|
macro_rules! make_source_fallible {
|
||||||
|
($enum:ident, $iterator:expr, $output:ident) => {{
|
||||||
|
let mut iter = $iterator.into_iter();
|
||||||
|
Box::new(
|
||||||
|
move || -> ::std::result::Result<$enum, $crate::PipelineError> {
|
||||||
|
match iter.next() {
|
||||||
|
Some(Ok(x)) => Ok($enum::$output(x)),
|
||||||
|
Some(Err(e)) => Err($crate::PipelineError::StepError(Box::new(e))),
|
||||||
|
None => Err($crate::PipelineError::EndOfStream),
|
||||||
|
}
|
||||||
|
},
|
||||||
|
) as Box<dyn FnMut() -> ::std::result::Result<$enum, $crate::PipelineError> + Send>
|
||||||
|
}};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Creates a `Stage::Transform` from a pure (non-fallible) function `Fn(T) -> U`.
|
||||||
|
#[macro_export]
|
||||||
|
macro_rules! make_transform {
|
||||||
|
($enum:ident, $func:tt, $input:ident, $output:ident) => {{
|
||||||
|
let __f = $func;
|
||||||
|
$crate::Stage::Transform(::std::sync::Arc::from(Box::new(
|
||||||
|
move |data: $enum| -> ::std::result::Result<$enum, $crate::PipelineError> {
|
||||||
|
match data {
|
||||||
|
$enum::$input(x) => Ok($enum::$output(__f(x))),
|
||||||
|
_ => Err($crate::PipelineError::TypeMismatch),
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
as Box<
|
||||||
|
dyn Fn($enum) -> ::std::result::Result<$enum, $crate::PipelineError> + Send + Sync,
|
||||||
|
>))
|
||||||
|
}};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Creates a `Stage::Transform` from a fallible function `Fn(T) -> Result<U, E>`.
|
||||||
|
#[macro_export]
|
||||||
|
macro_rules! make_transform_fallible {
|
||||||
|
($enum:ident, $func:tt, $input:ident, $output:ident) => {{
|
||||||
|
let __f = $func;
|
||||||
|
$crate::Stage::Transform(::std::sync::Arc::from(Box::new(
|
||||||
|
move |data: $enum| -> ::std::result::Result<$enum, $crate::PipelineError> {
|
||||||
|
match data {
|
||||||
|
$enum::$input(inner) => {
|
||||||
|
let result = __f(inner)
|
||||||
|
.map_err(|e| $crate::PipelineError::StepError(Box::new(e)))?;
|
||||||
|
Ok($enum::$output(result))
|
||||||
|
}
|
||||||
|
_ => Err($crate::PipelineError::TypeMismatch),
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
as Box<
|
||||||
|
dyn Fn($enum) -> ::std::result::Result<$enum, $crate::PipelineError> + Send + Sync,
|
||||||
|
>))
|
||||||
|
}};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Creates a `Stage::Flat` from a function `Fn(T) -> impl IntoIterator<Item = U>`.
|
||||||
|
///
|
||||||
|
/// Each item produced by the iterator is pushed individually to
|
||||||
|
/// the output channel, so that the scheduler can dispatch the items in parallel
|
||||||
|
/// as soon as a worker is available.
|
||||||
|
#[macro_export]
|
||||||
|
macro_rules! make_flat_transform {
|
||||||
|
($enum:ident, $func:tt, $input:ident, $output:ident) => {{
|
||||||
|
let __f = $func;
|
||||||
|
$crate::Stage::Flat(::std::sync::Arc::new(
|
||||||
|
move |data: $enum,
|
||||||
|
push: &$crate::PipelineSender<
|
||||||
|
::std::result::Result<$enum, $crate::PipelineError>,
|
||||||
|
>,
|
||||||
|
delta: &$crate::PipelineSender<isize>| {
|
||||||
|
match data {
|
||||||
|
$enum::$input(inner) => {
|
||||||
|
let mut count: isize = 0;
|
||||||
|
for item in __f(inner) {
|
||||||
|
push.send(Ok($enum::$output(item))).ok();
|
||||||
|
count += 1;
|
||||||
|
}
|
||||||
|
delta.send(count - 1).ok();
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
push.send(Err($crate::PipelineError::TypeMismatch)).ok();
|
||||||
|
delta.send(0).ok();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
) as $crate::SharedFlatFn<$enum>)
|
||||||
|
}};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Creates a `Stage::Flat` from a fallible function
|
||||||
|
/// `Fn(T) -> Result<impl IntoIterator<Item = U>, E>`.
|
||||||
|
///
|
||||||
|
/// If the function returns `Err`, an error is pushed to the channel and no
|
||||||
|
/// regular item is produced.
|
||||||
|
#[macro_export]
|
||||||
|
macro_rules! make_flat_transform_fallible {
|
||||||
|
($enum:ident, $func:tt, $input:ident, $output:ident) => {{
|
||||||
|
let __f = $func;
|
||||||
|
$crate::Stage::Flat(::std::sync::Arc::new(
|
||||||
|
move |data: $enum,
|
||||||
|
push: &$crate::PipelineSender<
|
||||||
|
::std::result::Result<$enum, $crate::PipelineError>,
|
||||||
|
>,
|
||||||
|
delta: &$crate::PipelineSender<isize>| {
|
||||||
|
match data {
|
||||||
|
$enum::$input(inner) => match __f(inner) {
|
||||||
|
Ok(iter) => {
|
||||||
|
let mut count: isize = 0;
|
||||||
|
for item in iter {
|
||||||
|
push.send(Ok($enum::$output(item))).ok();
|
||||||
|
count += 1;
|
||||||
|
}
|
||||||
|
delta.send(count - 1).ok();
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
push.send(Err($crate::PipelineError::StepError(Box::new(e))))
|
||||||
|
.ok();
|
||||||
|
delta.send(0).ok();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
_ => {
|
||||||
|
push.send(Err($crate::PipelineError::TypeMismatch)).ok();
|
||||||
|
delta.send(0).ok();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
) as $crate::SharedFlatFn<$enum>)
|
||||||
|
}};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Creates a `SinkFn` from a function that consumes a concrete value and returns `()`.
|
||||||
|
#[macro_export]
|
||||||
|
macro_rules! make_sink {
|
||||||
|
($enum:ident, $func:tt, $input:ident) => {{
|
||||||
|
let __f = $func;
|
||||||
|
Box::new(
|
||||||
|
move |data: $enum| -> ::std::result::Result<(), $crate::PipelineError> {
|
||||||
|
match data {
|
||||||
|
$enum::$input(x) => {
|
||||||
|
__f(x);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
_ => Err($crate::PipelineError::TypeMismatch),
|
||||||
|
}
|
||||||
|
},
|
||||||
|
) as Box<dyn Fn($enum) -> ::std::result::Result<(), $crate::PipelineError> + Send>
|
||||||
|
}};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Creates a `SinkFn` from a fallible function that returns `Result<(), E>`.
|
||||||
|
#[macro_export]
|
||||||
|
macro_rules! make_sink_fallible {
|
||||||
|
($enum:ident, $func:tt, $input:ident) => {{
|
||||||
|
let __f = $func;
|
||||||
|
Box::new(
|
||||||
|
move |data: $enum| -> ::std::result::Result<(), $crate::PipelineError> {
|
||||||
|
match data {
|
||||||
|
$enum::$input(inner) => {
|
||||||
|
__f(inner).map_err(|e| $crate::PipelineError::StepError(Box::new(e)))
|
||||||
|
}
|
||||||
|
_ => Err($crate::PipelineError::TypeMismatch),
|
||||||
|
}
|
||||||
|
},
|
||||||
|
) as Box<dyn Fn($enum) -> ::std::result::Result<(), $crate::PipelineError> + Send>
|
||||||
|
}};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Builds a `Pipeline` from a source, a list of stages and a sink.
|
||||||
|
///
|
||||||
|
/// Syntax:
|
||||||
|
/// ```ignore
|
||||||
|
/// make_pipeline! {
|
||||||
|
/// MyData,
|
||||||
|
/// source my_iter => Variant, // infallible source
|
||||||
|
/// source? my_iter => Variant, // fallible source (Result<T, E>)
|
||||||
|
/// | func: In => Out, // 1→1 transform, infallible
|
||||||
|
/// |? func: In => Out, // 1→1 transform, fallible
|
||||||
|
/// || func: In => Out, // 1→N flat transform, infallible
|
||||||
|
/// ||? func: In => Out, // 1→N flat transform, fallible
|
||||||
|
/// sink my_func @ Variant, // infallible sink
|
||||||
|
/// sink? my_func @ Variant, // fallible sink
|
||||||
|
/// }
|
||||||
|
/// ```
|
||||||
|
#[macro_export]
|
||||||
|
macro_rules! make_pipeline {
|
||||||
|
// ── Entry points ─────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
($enum:ident, source $src:expr => $src_out:ident, $($rest:tt)*) => {
|
||||||
|
$crate::make_pipeline!(@build $enum,
|
||||||
|
{ $crate::make_source!($enum, $src, $src_out) },
|
||||||
|
[],
|
||||||
|
$($rest)*)
|
||||||
|
};
|
||||||
|
($enum:ident, source? $src:expr => $src_out:ident, $($rest:tt)*) => {
|
||||||
|
$crate::make_pipeline!(@build $enum,
|
||||||
|
{ $crate::make_source_fallible!($enum, $src, $src_out) },
|
||||||
|
[],
|
||||||
|
$($rest)*)
|
||||||
|
};
|
||||||
|
|
||||||
|
// ── Stage accumulation ───────────────────────────────────────────────
|
||||||
|
|
||||||
|
// 1→1 transform, infallible
|
||||||
|
(@build $enum:ident, $source:tt, [$($acc:tt)*],
|
||||||
|
| $tf:tt : $t_in:ident => $t_out:ident, $($rest:tt)*) => {
|
||||||
|
$crate::make_pipeline!(@build $enum, $source,
|
||||||
|
[$($acc)* $crate::make_transform!($enum, $tf, $t_in, $t_out),],
|
||||||
|
$($rest)*)
|
||||||
|
};
|
||||||
|
|
||||||
|
// 1→1 transform, fallible
|
||||||
|
(@build $enum:ident, $source:tt, [$($acc:tt)*],
|
||||||
|
|? $tf:tt : $t_in:ident => $t_out:ident, $($rest:tt)*) => {
|
||||||
|
$crate::make_pipeline!(@build $enum, $source,
|
||||||
|
[$($acc)* $crate::make_transform_fallible!($enum, $tf, $t_in, $t_out),],
|
||||||
|
$($rest)*)
|
||||||
|
};
|
||||||
|
|
||||||
|
// 1→N flat transform, infallible
|
||||||
|
(@build $enum:ident, $source:tt, [$($acc:tt)*],
|
||||||
|
|| $tf:tt : $t_in:ident => $t_out:ident, $($rest:tt)*) => {
|
||||||
|
$crate::make_pipeline!(@build $enum, $source,
|
||||||
|
[$($acc)* $crate::make_flat_transform!($enum, $tf, $t_in, $t_out),],
|
||||||
|
$($rest)*)
|
||||||
|
};
|
||||||
|
|
||||||
|
// 1→N flat transform, fallible
|
||||||
|
(@build $enum:ident, $source:tt, [$($acc:tt)*],
|
||||||
|
||? $tf:tt : $t_in:ident => $t_out:ident, $($rest:tt)*) => {
|
||||||
|
$crate::make_pipeline!(@build $enum, $source,
|
||||||
|
[$($acc)* $crate::make_flat_transform_fallible!($enum, $tf, $t_in, $t_out),],
|
||||||
|
$($rest)*)
|
||||||
|
};
|
||||||
|
|
||||||
|
// ── Termination: sink ────────────────────────────────────────────────
|
||||||
|
|
||||||
|
(@build $enum:ident, $source:tt, [$($acc:tt)*],
|
||||||
|
sink $sink_fn:tt @ $sink_in:ident $(,)?) => {
|
||||||
|
$crate::Pipeline::new(
|
||||||
|
$source,
|
||||||
|
vec![$($acc)*],
|
||||||
|
$crate::make_sink!($enum, $sink_fn, $sink_in),
|
||||||
|
)
|
||||||
|
};
|
||||||
|
(@build $enum:ident, $source:tt, [$($acc:tt)*],
|
||||||
|
sink? $sink_fn:tt @ $sink_in:ident $(,)?) => {
|
||||||
|
$crate::Pipeline::new(
|
||||||
|
$source,
|
||||||
|
vec![$($acc)*],
|
||||||
|
$crate::make_sink_fallible!($enum, $sink_fn, $sink_in),
|
||||||
|
)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Builds a typed `Pipe<D, In, Out>` — sourceless and sinkless.
|
||||||
|
///
|
||||||
|
/// Syntax:
|
||||||
|
/// ```ignore
|
||||||
|
/// make_pipe! {
|
||||||
|
/// MyData : InType => OutType,
|
||||||
|
/// | func : InVariant => OutVariant, // transform 1→1
|
||||||
|
/// |? func : InVariant => OutVariant, // transform 1→1 fallible
|
||||||
|
/// || func : InVariant => OutVariant, // flat transform 1→N
|
||||||
|
/// ||? func : InVariant => OutVariant, // flat transform 1→N fallible
|
||||||
|
/// }
|
||||||
|
/// ```
|
||||||
|
#[macro_export]
|
||||||
|
macro_rules! make_pipe {
|
||||||
|
// ── Entry: first stage | ─────────────────────────────────────────────
|
||||||
|
($enum:ident : $in_ty:ty => $out_ty:ty,
|
||||||
|
| $tf:tt : $fi:ident => $fo:ident, $($rest:tt)*) => {
|
||||||
|
$crate::make_pipe!(@build $enum : $in_ty => $out_ty, $fi,
|
||||||
|
[$crate::make_transform!($enum, $tf, $fi, $fo),], $fo, $($rest)*)
|
||||||
|
};
|
||||||
|
// ── Entry: first stage |? ────────────────────────────────────────────
|
||||||
|
($enum:ident : $in_ty:ty => $out_ty:ty,
|
||||||
|
|? $tf:tt : $fi:ident => $fo:ident, $($rest:tt)*) => {
|
||||||
|
$crate::make_pipe!(@build $enum : $in_ty => $out_ty, $fi,
|
||||||
|
[$crate::make_transform_fallible!($enum, $tf, $fi, $fo),], $fo, $($rest)*)
|
||||||
|
};
|
||||||
|
// ── Entry: first stage || ────────────────────────────────────────────
|
||||||
|
($enum:ident : $in_ty:ty => $out_ty:ty,
|
||||||
|
|| $tf:tt : $fi:ident => $fo:ident, $($rest:tt)*) => {
|
||||||
|
$crate::make_pipe!(@build $enum : $in_ty => $out_ty, $fi,
|
||||||
|
[$crate::make_flat_transform!($enum, $tf, $fi, $fo),], $fo, $($rest)*)
|
||||||
|
};
|
||||||
|
// ── Entry: first stage ||? ───────────────────────────────────────────
|
||||||
|
($enum:ident : $in_ty:ty => $out_ty:ty,
|
||||||
|
||? $tf:tt : $fi:ident => $fo:ident, $($rest:tt)*) => {
|
||||||
|
$crate::make_pipe!(@build $enum : $in_ty => $out_ty, $fi,
|
||||||
|
[$crate::make_flat_transform_fallible!($enum, $tf, $fi, $fo),], $fo, $($rest)*)
|
||||||
|
};
|
||||||
|
|
||||||
|
// ── Accumulation: | ──────────────────────────────────────────────────
|
||||||
|
(@build $enum:ident : $in_ty:ty => $out_ty:ty, $fi:ident,
|
||||||
|
[$($acc:tt)*], $lo:ident,
|
||||||
|
| $tf:tt : $ti:ident => $to:ident, $($rest:tt)*) => {
|
||||||
|
$crate::make_pipe!(@build $enum : $in_ty => $out_ty, $fi,
|
||||||
|
[$($acc)* $crate::make_transform!($enum, $tf, $ti, $to),], $to, $($rest)*)
|
||||||
|
};
|
||||||
|
// ── Accumulation: |? ─────────────────────────────────────────────────
|
||||||
|
(@build $enum:ident : $in_ty:ty => $out_ty:ty, $fi:ident,
|
||||||
|
[$($acc:tt)*], $lo:ident,
|
||||||
|
|? $tf:tt : $ti:ident => $to:ident, $($rest:tt)*) => {
|
||||||
|
$crate::make_pipe!(@build $enum : $in_ty => $out_ty, $fi,
|
||||||
|
[$($acc)* $crate::make_transform_fallible!($enum, $tf, $ti, $to),], $to, $($rest)*)
|
||||||
|
};
|
||||||
|
// ── Accumulation: || ─────────────────────────────────────────────────
|
||||||
|
(@build $enum:ident : $in_ty:ty => $out_ty:ty, $fi:ident,
|
||||||
|
[$($acc:tt)*], $lo:ident,
|
||||||
|
|| $tf:tt : $ti:ident => $to:ident, $($rest:tt)*) => {
|
||||||
|
$crate::make_pipe!(@build $enum : $in_ty => $out_ty, $fi,
|
||||||
|
[$($acc)* $crate::make_flat_transform!($enum, $tf, $ti, $to),], $to, $($rest)*)
|
||||||
|
};
|
||||||
|
// ── Accumulation: ||? ────────────────────────────────────────────────
|
||||||
|
(@build $enum:ident : $in_ty:ty => $out_ty:ty, $fi:ident,
|
||||||
|
[$($acc:tt)*], $lo:ident,
|
||||||
|
||? $tf:tt : $ti:ident => $to:ident, $($rest:tt)*) => {
|
||||||
|
$crate::make_pipe!(@build $enum : $in_ty => $out_ty, $fi,
|
||||||
|
[$($acc)* $crate::make_flat_transform_fallible!($enum, $tf, $ti, $to),], $to, $($rest)*)
|
||||||
|
};
|
||||||
|
|
||||||
|
// ── Termination ───────────────────────────────────────────────────────
|
||||||
|
(@build $enum:ident : $in_ty:ty => $out_ty:ty, $fi:ident,
|
||||||
|
[$($acc:tt)*], $lo:ident $(,)?) => {
|
||||||
|
$crate::Pipe::new(
|
||||||
|
vec![$($acc)*],
|
||||||
|
::std::sync::Arc::new(|x: $in_ty| $enum::$fi(x)),
|
||||||
|
::std::sync::Arc::new(|d: $enum| -> $out_ty {
|
||||||
|
if let $enum::$lo(x) = d { x }
|
||||||
|
else { ::std::unreachable!("unexpected pipeline data variant in make_pipe!") }
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
//! Scheduler: a channel/thread-based pipeline runtime with typed, composable
|
||||||
|
//! stages (`Pipe`), plus the macro-based `PipelineData`-enum runtime it grew
|
||||||
|
//! out of (`Pipeline`/`WorkerPool`).
|
||||||
|
//!
|
||||||
|
//! Submodules: [`error`] (`PipelineError`), [`types`] (function types, `Stage`),
|
||||||
|
//! [`runner`] (thread bodies), [`pool`] (`Pipeline`/`WorkerPool` scheduler
|
||||||
|
//! loop), [`pipe`] (`Pipe`/`PipeIter`), [`macros`] (`make_pipe!` and friends).
|
||||||
|
|
||||||
|
mod error;
|
||||||
|
mod macros;
|
||||||
|
mod pipe;
|
||||||
|
mod pool;
|
||||||
|
mod runner;
|
||||||
|
mod types;
|
||||||
|
|
||||||
|
pub use error::PipelineError;
|
||||||
|
pub use pipe::{Pipe, PipeIter};
|
||||||
|
pub use pool::{Pipeline, WorkerPool};
|
||||||
|
pub use types::{SharedFlatFn, SharedFn, SinkFn, SourceFn, Stage};
|
||||||
@@ -0,0 +1,126 @@
|
|||||||
|
use crossbeam_channel::{Receiver, bounded};
|
||||||
|
use std::marker::PhantomData;
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::thread;
|
||||||
|
|
||||||
|
use super::error::PipelineError;
|
||||||
|
use super::pool::{Pipeline, WorkerPool};
|
||||||
|
use super::types::{SinkFn, SourceFn, Stage};
|
||||||
|
|
||||||
|
// ── Pipe ──────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/// Typed, composable iterator transformer.
|
||||||
|
///
|
||||||
|
/// A `Pipe<D, In, Out>` is a pure description of pipeline stages — no threads,
|
||||||
|
/// no channels, no scheduler. Call `.apply(iter, n_workers, capacity)` to start
|
||||||
|
/// execution and get back a `PipeIter<Out>`.
|
||||||
|
///
|
||||||
|
/// Compose two pipes with `.then()`: the resulting `Pipe` holds the concatenated
|
||||||
|
/// stage list, so a single scheduler is created when `.apply()` is eventually called.
|
||||||
|
pub struct Pipe<D, In, Out> {
|
||||||
|
stages: Vec<Stage<D>>,
|
||||||
|
wrap: Arc<dyn Fn(In) -> D + Send + Sync>,
|
||||||
|
unwrap: Arc<dyn Fn(D) -> Out + Send + Sync>,
|
||||||
|
_phantom: PhantomData<(In, Out)>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<D, In, Out> Pipe<D, In, Out> {
|
||||||
|
/// Build a `Pipe` from stages and wrap/unwrap converters.
|
||||||
|
/// Prefer the `make_pipe!` macro.
|
||||||
|
pub fn new(
|
||||||
|
stages: Vec<Stage<D>>,
|
||||||
|
wrap: Arc<dyn Fn(In) -> D + Send + Sync>,
|
||||||
|
unwrap: Arc<dyn Fn(D) -> Out + Send + Sync>,
|
||||||
|
) -> Self {
|
||||||
|
Self {
|
||||||
|
stages,
|
||||||
|
wrap,
|
||||||
|
unwrap,
|
||||||
|
_phantom: PhantomData,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Concatenate stages from two pipes into one.
|
||||||
|
///
|
||||||
|
/// Requires `Out` of `self` == `In` of `other`. The single scheduler
|
||||||
|
/// created at `.apply()` time sees the full combined stage list.
|
||||||
|
pub fn then<Next>(self, other: Pipe<D, Out, Next>) -> Pipe<D, In, Next> {
|
||||||
|
Pipe {
|
||||||
|
stages: self.stages.into_iter().chain(other.stages).collect(),
|
||||||
|
wrap: self.wrap,
|
||||||
|
unwrap: other.unwrap,
|
||||||
|
_phantom: PhantomData,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<D, In, Out> Pipe<D, In, Out>
|
||||||
|
where
|
||||||
|
D: Send + Sync + 'static,
|
||||||
|
In: Send + 'static,
|
||||||
|
Out: Send + 'static,
|
||||||
|
{
|
||||||
|
/// Run the pipeline in a background thread; returns an iterator over the output.
|
||||||
|
pub fn apply(
|
||||||
|
self,
|
||||||
|
input: impl Iterator<Item = In> + Send + 'static,
|
||||||
|
n_workers: usize,
|
||||||
|
capacity: usize,
|
||||||
|
) -> PipeIter<Out> {
|
||||||
|
let wrap = Arc::clone(&self.wrap);
|
||||||
|
let unwrap = Arc::clone(&self.unwrap);
|
||||||
|
|
||||||
|
let mut iter = input;
|
||||||
|
let source: SourceFn<D> = Box::new(move || match iter.next() {
|
||||||
|
Some(x) => Ok(wrap(x)),
|
||||||
|
None => Err(PipelineError::EndOfStream),
|
||||||
|
});
|
||||||
|
|
||||||
|
let (out_tx, out_rx) = bounded::<Out>(capacity);
|
||||||
|
let sink: SinkFn<D> = Box::new(move |data: D| {
|
||||||
|
out_tx.send(unwrap(data)).map_err(|_| {
|
||||||
|
PipelineError::StepError(Box::new(std::io::Error::new(
|
||||||
|
std::io::ErrorKind::BrokenPipe,
|
||||||
|
"output channel closed",
|
||||||
|
)))
|
||||||
|
})
|
||||||
|
});
|
||||||
|
|
||||||
|
let pipeline = Pipeline::new(source, self.stages, sink);
|
||||||
|
let handle = thread::spawn(move || {
|
||||||
|
WorkerPool::new(pipeline, n_workers, capacity).run();
|
||||||
|
});
|
||||||
|
|
||||||
|
PipeIter {
|
||||||
|
rx: Some(out_rx),
|
||||||
|
handle: Some(handle),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── PipeIter ──────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/// Iterator over the output of `Pipe::apply()`.
|
||||||
|
pub struct PipeIter<Out> {
|
||||||
|
rx: Option<Receiver<Out>>,
|
||||||
|
handle: Option<thread::JoinHandle<()>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<Out> Iterator for PipeIter<Out> {
|
||||||
|
type Item = Out;
|
||||||
|
|
||||||
|
fn next(&mut self) -> Option<Out> {
|
||||||
|
self.rx.as_ref()?.recv().ok()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<Out> Drop for PipeIter<Out> {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
// Drop the receiver *before* joining: the sink then fails on its next send, which stops the
|
||||||
|
// scheduler. Joining while the receiver is alive blocks forever if the bounded output channel is full.
|
||||||
|
drop(self.rx.take());
|
||||||
|
if let Some(h) = self.handle.take() {
|
||||||
|
let _ = h.join();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,208 @@
|
|||||||
|
use crossbeam_channel::{Receiver, Select, Sender, bounded};
|
||||||
|
|
||||||
|
use super::error::PipelineError;
|
||||||
|
use super::runner::{dispatch, sink_runner, source_runner, transform_runner};
|
||||||
|
use super::types::{SinkFn, SourceFn, Stage, WorkerTask};
|
||||||
|
|
||||||
|
// ── Pipeline ──────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
pub struct Pipeline<DATA> {
|
||||||
|
source: SourceFn<DATA>,
|
||||||
|
stages: Vec<Stage<DATA>>,
|
||||||
|
sink: SinkFn<DATA>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<DATA> Pipeline<DATA> {
|
||||||
|
pub fn new(source: SourceFn<DATA>, stages: Vec<Stage<DATA>>, sink: SinkFn<DATA>) -> Self {
|
||||||
|
Self {
|
||||||
|
source,
|
||||||
|
stages,
|
||||||
|
sink,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── WorkerPool ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
pub struct WorkerPool<DATA> {
|
||||||
|
pipeline: Pipeline<DATA>,
|
||||||
|
handles: Vec<std::thread::JoinHandle<()>>,
|
||||||
|
n_workers: usize,
|
||||||
|
capacity: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<DATA> WorkerPool<DATA>
|
||||||
|
where
|
||||||
|
DATA: Send + Sync + 'static,
|
||||||
|
{
|
||||||
|
pub fn new(pipeline: Pipeline<DATA>, n_workers: usize, capacity: usize) -> Self {
|
||||||
|
Self {
|
||||||
|
pipeline,
|
||||||
|
handles: Vec::new(),
|
||||||
|
n_workers,
|
||||||
|
capacity,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn run(mut self) {
|
||||||
|
let n = self.pipeline.stages.len();
|
||||||
|
|
||||||
|
// ── Inter-stage channels ───────────────────────────────────────────
|
||||||
|
// stage_txs[i] / stage_rxs[i]: output of stage i
|
||||||
|
let mut stage_txs: Vec<Sender<Result<DATA, PipelineError>>> = Vec::new();
|
||||||
|
let mut stage_rxs: Vec<Receiver<Result<DATA, PipelineError>>> = Vec::new();
|
||||||
|
for _ in 0..n {
|
||||||
|
let (tx, rx) = bounded(self.capacity);
|
||||||
|
stage_txs.push(tx);
|
||||||
|
stage_rxs.push(rx);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Source thread ──────────────────────────────────────────────────
|
||||||
|
let (source_rx, src_handle) = source_runner(self.pipeline.source, self.capacity);
|
||||||
|
self.handles.push(src_handle);
|
||||||
|
|
||||||
|
let stages = self.pipeline.stages;
|
||||||
|
|
||||||
|
// ── Delta channel for the flat stages ──────────────────────────────
|
||||||
|
// Each flat worker sends `N-1` here after pushing N items.
|
||||||
|
// The scheduler adjusts `in_flight` accordingly.
|
||||||
|
let (flat_delta_tx, flat_delta_rx) = bounded::<isize>(self.capacity);
|
||||||
|
|
||||||
|
// ── Worker pool ────────────────────────────────────────────────────
|
||||||
|
let (worker_tx, worker_rx): (Sender<WorkerTask<DATA>>, Receiver<WorkerTask<DATA>>) =
|
||||||
|
bounded(self.capacity);
|
||||||
|
|
||||||
|
for _ in 0..self.n_workers {
|
||||||
|
self.handles.push(transform_runner(
|
||||||
|
worker_rx.clone(),
|
||||||
|
stages.iter().map(Stage::clone).collect(),
|
||||||
|
stage_txs.clone(),
|
||||||
|
flat_delta_tx.clone(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
// The scheduler no longer holds flat_delta_tx: the workers own it.
|
||||||
|
// It is dropped here so that the channel closes when the workers finish.
|
||||||
|
drop(flat_delta_tx);
|
||||||
|
|
||||||
|
// ── Sink thread ────────────────────────────────────────────────────
|
||||||
|
let (sink_tx, sink_err_rx, sink_handle) = sink_runner(self.pipeline.sink, self.capacity);
|
||||||
|
self.handles.push(sink_handle);
|
||||||
|
|
||||||
|
// ── Main loop ──────────────────────────────────────────────────────
|
||||||
|
//
|
||||||
|
// `in_flight` (isize) = number of items that still have to reach the sink.
|
||||||
|
// May be temporarily negative if a flat worker has pushed its items
|
||||||
|
// before the scheduler has received the matching delta.
|
||||||
|
//
|
||||||
|
// `flat_workers_active` = number of flat workers currently running.
|
||||||
|
// Prevents a premature termination when in_flight is 0 but a
|
||||||
|
// flat worker has not sent its delta yet.
|
||||||
|
//
|
||||||
|
// Priorities of the biased Select (lowest index = highest priority):
|
||||||
|
// 0 → sink_err_rx (immediate stop on a sink error)
|
||||||
|
// 1 → flat_delta_rx (update in_flight before dispatching)
|
||||||
|
// 2..=n+1 → stage_rxs[n-1..0] (drain the pipeline first)
|
||||||
|
// n+2 → source_rx (last resort: new data)
|
||||||
|
//
|
||||||
|
// When k = 0 : sink error
|
||||||
|
// When k = 1 : delta of a flat worker
|
||||||
|
// When 2 ≤ k ≤ n+1 : result of stage n+1-k
|
||||||
|
// When k = n+2 : source item
|
||||||
|
//
|
||||||
|
// Termination: source exhausted AND in_flight == 0 AND no active flat worker.
|
||||||
|
{
|
||||||
|
let mut source_done = false;
|
||||||
|
let mut in_flight: isize = 0;
|
||||||
|
let mut flat_workers_active: usize = 0;
|
||||||
|
|
||||||
|
loop {
|
||||||
|
if source_done && in_flight == 0 && flat_workers_active == 0 {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut sel = Select::new_biased();
|
||||||
|
sel.recv(&sink_err_rx); // index 0
|
||||||
|
sel.recv(&flat_delta_rx); // index 1
|
||||||
|
for rx in stage_rxs.iter().rev() {
|
||||||
|
sel.recv(rx); // indices 2..=n+1
|
||||||
|
}
|
||||||
|
let src_idx = if !source_done {
|
||||||
|
Some(sel.recv(&source_rx)) // index n+2
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
|
||||||
|
let oper = sel.select();
|
||||||
|
let k = oper.index();
|
||||||
|
|
||||||
|
if k == 0 {
|
||||||
|
// ── Sink error ────────────────────────────────────────
|
||||||
|
match oper.recv(&sink_err_rx) {
|
||||||
|
Ok(e) => {
|
||||||
|
eprintln!("Sink error: {:?}", e);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
Err(_) => break,
|
||||||
|
}
|
||||||
|
} else if k == 1 {
|
||||||
|
// ── Delta of a flat worker ────────────────────────────
|
||||||
|
// delta = N - 1 (N items pushed, 1 item consumed)
|
||||||
|
if let Ok(delta) = oper.recv(&flat_delta_rx) {
|
||||||
|
in_flight += delta;
|
||||||
|
flat_workers_active -= 1;
|
||||||
|
}
|
||||||
|
} else if src_idx == Some(k) {
|
||||||
|
// ── New item from the source ──────────────────────────
|
||||||
|
match oper.recv(&source_rx) {
|
||||||
|
Ok(Ok(data)) => {
|
||||||
|
if n == 0 {
|
||||||
|
let _ = sink_tx.send(data);
|
||||||
|
} else {
|
||||||
|
in_flight += 1;
|
||||||
|
dispatch(data, 0, &stages, &worker_tx, &mut flat_workers_active);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(Err(e)) => eprintln!("Source error: {:?}", e),
|
||||||
|
Err(_) => source_done = true,
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// ── Result of an intermediate stage ───────────────────
|
||||||
|
// k ∈ [2, n+1] → stage = n+1 - k
|
||||||
|
let stage = n + 1 - k;
|
||||||
|
match oper.recv(&stage_rxs[stage]) {
|
||||||
|
Ok(Ok(data)) => {
|
||||||
|
if stage == n - 1 {
|
||||||
|
in_flight -= 1;
|
||||||
|
let _ = sink_tx.send(data);
|
||||||
|
} else {
|
||||||
|
dispatch(
|
||||||
|
data,
|
||||||
|
stage + 1,
|
||||||
|
&stages,
|
||||||
|
&worker_tx,
|
||||||
|
&mut flat_workers_active,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(Err(e)) => eprintln!("Stage {} error: {:?}", stage, e),
|
||||||
|
Err(_) => break,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
drop(worker_tx);
|
||||||
|
drop(sink_tx);
|
||||||
|
// Close the receiving ends before joining. When the loop above stopped early (sink error, for example
|
||||||
|
// an output iterator dropped before exhaustion), the source thread and the workers may be blocked
|
||||||
|
// sending to a full bounded channel nobody drains any more: a failed send lets them exit.
|
||||||
|
drop(source_rx);
|
||||||
|
drop(stage_rxs);
|
||||||
|
drop(flat_delta_rx);
|
||||||
|
drop(sink_err_rx);
|
||||||
|
|
||||||
|
for h in self.handles {
|
||||||
|
let _ = h.join();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,118 @@
|
|||||||
|
use crossbeam_channel::{Receiver, Sender, bounded};
|
||||||
|
use std::thread;
|
||||||
|
|
||||||
|
use super::error::PipelineError;
|
||||||
|
use super::types::{SinkFn, SourceFn, Stage, WorkerTask};
|
||||||
|
|
||||||
|
// ── Thread runners ────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
pub(super) fn source_runner<DATA>(
|
||||||
|
mut source: SourceFn<DATA>,
|
||||||
|
capacity: usize,
|
||||||
|
) -> (
|
||||||
|
Receiver<Result<DATA, PipelineError>>,
|
||||||
|
thread::JoinHandle<()>,
|
||||||
|
)
|
||||||
|
where
|
||||||
|
DATA: Send + Sync + 'static,
|
||||||
|
{
|
||||||
|
let (tx, rx) = bounded(capacity);
|
||||||
|
let handle = thread::spawn(move || {
|
||||||
|
loop {
|
||||||
|
match source() {
|
||||||
|
Ok(data) => {
|
||||||
|
if tx.send(Ok(data)).is_err() {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(PipelineError::EndOfStream) => break,
|
||||||
|
Err(e) => {
|
||||||
|
eprintln!("Source error: {:?}", e);
|
||||||
|
let _ = tx.send(Err(e));
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
(rx, handle)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Spawns a worker thread of the pool.
|
||||||
|
///
|
||||||
|
/// Handles two kinds of tasks:
|
||||||
|
/// - `Transform`: applies `f(data)` and sends the result to `result_tx`.
|
||||||
|
/// - `Flat`: calls `f(data, &push_tx, &delta_tx)`; the function itself
|
||||||
|
/// pushes its items to `push_tx` and sends `N-1` to `delta_tx`.
|
||||||
|
pub(super) fn transform_runner<DATA>(
|
||||||
|
task_rx: Receiver<WorkerTask<DATA>>,
|
||||||
|
stages: Vec<Stage<DATA>>,
|
||||||
|
stage_txs: Vec<Sender<Result<DATA, PipelineError>>>,
|
||||||
|
flat_delta_tx: Sender<isize>,
|
||||||
|
) -> thread::JoinHandle<()>
|
||||||
|
where
|
||||||
|
DATA: Send + Sync + 'static,
|
||||||
|
{
|
||||||
|
thread::spawn(move || {
|
||||||
|
while let Ok(task) = task_rx.recv() {
|
||||||
|
match task {
|
||||||
|
WorkerTask::Transform(data, idx) => {
|
||||||
|
if let Stage::Transform(f) = &stages[idx] {
|
||||||
|
let _ = stage_txs[idx].send(f(data));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
WorkerTask::Flat(data, idx) => {
|
||||||
|
if let Stage::Flat(f) = &stages[idx] {
|
||||||
|
f(data, &stage_txs[idx], &flat_delta_tx);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Spawns the sink thread.
|
||||||
|
pub(super) fn sink_runner<DATA>(
|
||||||
|
sink: SinkFn<DATA>,
|
||||||
|
capacity: usize,
|
||||||
|
) -> (
|
||||||
|
Sender<DATA>,
|
||||||
|
Receiver<PipelineError>,
|
||||||
|
thread::JoinHandle<()>,
|
||||||
|
)
|
||||||
|
where
|
||||||
|
DATA: Send + Sync + 'static,
|
||||||
|
{
|
||||||
|
let (data_tx, data_rx) = bounded(capacity);
|
||||||
|
let (err_tx, err_rx) = bounded(capacity);
|
||||||
|
let handle = thread::spawn(move || {
|
||||||
|
for data in data_rx {
|
||||||
|
if let Err(e) = sink(data) {
|
||||||
|
let _ = err_tx.send(e);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
(data_tx, err_rx, handle)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Envoie `data` au stage `stage_idx`.
|
||||||
|
/// For a `Transform`, queues a `WorkerTask::Transform`.
|
||||||
|
/// For a `Flat`, increments `flat_workers_active` and queues a `WorkerTask::Flat`.
|
||||||
|
#[inline]
|
||||||
|
pub(super) fn dispatch<DATA>(
|
||||||
|
data: DATA,
|
||||||
|
stage_idx: usize,
|
||||||
|
stages: &[Stage<DATA>],
|
||||||
|
worker_tx: &Sender<WorkerTask<DATA>>,
|
||||||
|
flat_workers_active: &mut usize,
|
||||||
|
) {
|
||||||
|
match &stages[stage_idx] {
|
||||||
|
Stage::Transform(_) => {
|
||||||
|
let _ = worker_tx.send(WorkerTask::Transform(data, stage_idx));
|
||||||
|
}
|
||||||
|
Stage::Flat(_) => {
|
||||||
|
*flat_workers_active += 1;
|
||||||
|
let _ = worker_tx.send(WorkerTask::Flat(data, stage_idx));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
use crossbeam_channel::Sender;
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use super::error::PipelineError;
|
||||||
|
|
||||||
|
// ── Function types ────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/// Source function: called repeatedly, returns the next item or `EndOfStream`.
|
||||||
|
/// `FnMut` because it keeps an internal state (position in the iterator).
|
||||||
|
pub type SourceFn<D> = Box<dyn FnMut() -> Result<D, PipelineError> + Send>;
|
||||||
|
|
||||||
|
/// Sink function: consumes a final item, may fail (I/O error, etc.).
|
||||||
|
pub type SinkFn<D> = Box<dyn Fn(D) -> Result<(), PipelineError> + Send>;
|
||||||
|
|
||||||
|
/// Transform function shared between workers through an `Arc`.
|
||||||
|
pub type SharedFn<D> = Arc<dyn Fn(D) -> Result<D, PipelineError> + Send + Sync>;
|
||||||
|
|
||||||
|
/// 1→N transform function (flat map) shared between workers through an `Arc`.
|
||||||
|
///
|
||||||
|
/// The function receives the input item, a `push` channel to send each produced
|
||||||
|
/// item, and a `delta` channel to tell the scheduler how many additional items
|
||||||
|
/// entered the pipeline (N-1 if N items are produced).
|
||||||
|
/// It must call `delta.send(N - 1)` **after** pushing all the items.
|
||||||
|
pub type SharedFlatFn<D> =
|
||||||
|
Arc<dyn Fn(D, &Sender<Result<D, PipelineError>>, &Sender<isize>) + Send + Sync>;
|
||||||
|
|
||||||
|
// ── Stage enum ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/// A pipeline stage: plain transform (1→1) or flat transform (1→N).
|
||||||
|
pub enum Stage<D> {
|
||||||
|
Transform(SharedFn<D>),
|
||||||
|
Flat(SharedFlatFn<D>),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<D> Clone for Stage<D> {
|
||||||
|
fn clone(&self) -> Self {
|
||||||
|
match self {
|
||||||
|
Stage::Transform(f) => Stage::Transform(Arc::clone(f)),
|
||||||
|
Stage::Flat(f) => Stage::Flat(Arc::clone(f)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Worker task ───────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
pub(super) enum WorkerTask<D> {
|
||||||
|
Transform(D, usize),
|
||||||
|
Flat(D, usize),
|
||||||
|
}
|
||||||
+106
@@ -0,0 +1,106 @@
|
|||||||
|
use std::sync::{Arc, Condvar, Mutex};
|
||||||
|
|
||||||
|
// ── Throttle ──────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/// Counting semaphore: limits how many items from a source are in-flight
|
||||||
|
/// simultaneously through the Flat stage of a pipeline.
|
||||||
|
///
|
||||||
|
/// Slots are acquired in the source thread before an item is emitted, and
|
||||||
|
/// released when the corresponding `ThrottleGuard` is dropped (i.e. when the
|
||||||
|
/// Flat worker finishes processing the item). Acquisition must never happen
|
||||||
|
/// inside a worker — only in the source thread — to prevent deadlocks.
|
||||||
|
pub struct Throttle {
|
||||||
|
count: Mutex<usize>,
|
||||||
|
condvar: Condvar,
|
||||||
|
max: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Throttle {
|
||||||
|
pub fn new(max: usize) -> Self {
|
||||||
|
Self {
|
||||||
|
count: Mutex::new(0),
|
||||||
|
condvar: Condvar::new(),
|
||||||
|
max,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn acquire(&self) {
|
||||||
|
let mut count = self.count.lock().unwrap();
|
||||||
|
while *count >= self.max {
|
||||||
|
count = self.condvar.wait(count).unwrap();
|
||||||
|
}
|
||||||
|
*count += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn release(&self) {
|
||||||
|
let mut count = self.count.lock().unwrap();
|
||||||
|
*count -= 1;
|
||||||
|
self.condvar.notify_one();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Throttle {
|
||||||
|
/// Acquire one slot and return a guard that releases it on drop —
|
||||||
|
/// for callers with no natural "source iterator" to wrap via
|
||||||
|
/// [`throttle`] (e.g. bounding concurrency inside a `rayon` parallel
|
||||||
|
/// iterator's own closure, one call per item, rather than up front in
|
||||||
|
/// a single source thread). Blocks the calling thread until a slot is
|
||||||
|
/// free, same as [`throttle`]'s own per-item acquisition.
|
||||||
|
pub fn acquire_guard(self: &Arc<Self>) -> ThrottleGuard {
|
||||||
|
self.acquire();
|
||||||
|
ThrottleGuard(Arc::clone(self))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── ThrottleGuard ─────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/// RAII guard: releases one slot in the `Throttle` when dropped.
|
||||||
|
pub struct ThrottleGuard(Arc<Throttle>);
|
||||||
|
|
||||||
|
impl Drop for ThrottleGuard {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
self.0.release();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Throttled<T> ──────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/// An item paired with its throttle guard.
|
||||||
|
///
|
||||||
|
/// The guard keeps a slot acquired until this value is dropped. In a Flat
|
||||||
|
/// pipeline stage, carry the guard inside the worker closure until the item
|
||||||
|
/// is fully processed, then let it drop.
|
||||||
|
pub struct Throttled<T> {
|
||||||
|
pub item: T,
|
||||||
|
pub guard: ThrottleGuard,
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── throttle() ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/// Wrap `source` so that at most `max_concurrent` items are emitted before
|
||||||
|
/// earlier ones have been fully processed (i.e. their `ThrottleGuard` dropped).
|
||||||
|
///
|
||||||
|
/// Acquisition blocks the source thread until a slot is available. This must
|
||||||
|
/// be called in the source thread, never inside a pipeline worker.
|
||||||
|
///
|
||||||
|
/// # Example
|
||||||
|
///
|
||||||
|
/// ```ignore
|
||||||
|
/// let throttled = obipipeline::throttle(file_paths, n_workers - 1);
|
||||||
|
/// // Use `throttled` as the pipeline source; carry `item.guard` through the
|
||||||
|
/// // Flat stage and let it drop when the file is fully read.
|
||||||
|
/// ```
|
||||||
|
pub fn throttle<I>(source: I, max_concurrent: usize) -> impl Iterator<Item = Throttled<I::Item>>
|
||||||
|
where
|
||||||
|
I: Iterator,
|
||||||
|
I::Item: Send + 'static,
|
||||||
|
{
|
||||||
|
let t = Arc::new(Throttle::new(max_concurrent));
|
||||||
|
source.map(move |item| {
|
||||||
|
t.acquire();
|
||||||
|
Throttled {
|
||||||
|
item,
|
||||||
|
guard: ThrottleGuard(Arc::clone(&t)),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
//! Behaviour of `Pipe` / `make_pipe!`: transforms, flat transforms, composition.
|
||||||
|
|
||||||
|
use obipipeline::make_pipe;
|
||||||
|
|
||||||
|
enum D {
|
||||||
|
Num(u64),
|
||||||
|
Text(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
fn double(x: u64) -> u64 {
|
||||||
|
x * 2
|
||||||
|
}
|
||||||
|
|
||||||
|
fn to_text(x: u64) -> String {
|
||||||
|
x.to_string()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn digits(s: String) -> Vec<String> {
|
||||||
|
s.chars().map(|c| c.to_string()).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn transform_chain_preserves_the_item_set() {
|
||||||
|
let pipe = make_pipe! {
|
||||||
|
D : u64 => String,
|
||||||
|
| double : Num => Num,
|
||||||
|
| to_text : Num => Text,
|
||||||
|
};
|
||||||
|
let mut out: Vec<String> = pipe.apply(1..=100u64, 4, 8).collect();
|
||||||
|
// Workers run in parallel: the order is not guaranteed, the set is.
|
||||||
|
out.sort_by_key(|s| s.parse::<u64>().unwrap());
|
||||||
|
let expected: Vec<String> = (1..=100u64).map(|x| (x * 2).to_string()).collect();
|
||||||
|
assert_eq!(out, expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn empty_input_yields_an_empty_output() {
|
||||||
|
let pipe = make_pipe! { D : u64 => u64, | double : Num => Num, };
|
||||||
|
assert_eq!(pipe.apply(std::iter::empty(), 2, 4).count(), 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn flat_transform_emits_every_produced_item() {
|
||||||
|
let pipe = make_pipe! {
|
||||||
|
D : u64 => String,
|
||||||
|
| to_text : Num => Text,
|
||||||
|
|| digits : Text => Text,
|
||||||
|
};
|
||||||
|
// 10..=99: two digits each.
|
||||||
|
let n = pipe.apply(10..=99u64, 3, 8).count();
|
||||||
|
assert_eq!(n, 90 * 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn flat_transform_may_produce_no_item() {
|
||||||
|
fn none(_: u64) -> Vec<u64> {
|
||||||
|
Vec::new()
|
||||||
|
}
|
||||||
|
let pipe = make_pipe! { D : u64 => u64, || none : Num => Num, };
|
||||||
|
assert_eq!(pipe.apply(0..50u64, 2, 4).count(), 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn composed_pipes_run_as_a_single_pipeline() {
|
||||||
|
let first = make_pipe! { D : u64 => u64, | double : Num => Num, };
|
||||||
|
let second = make_pipe! { D : u64 => String, | to_text : Num => Text, };
|
||||||
|
let mut out: Vec<String> = first.then(second).apply(1..=20u64, 2, 4).collect();
|
||||||
|
out.sort_by_key(|s| s.parse::<u64>().unwrap());
|
||||||
|
let expected: Vec<String> = (1..=20u64).map(|x| (x * 2).to_string()).collect();
|
||||||
|
assert_eq!(out, expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn dropping_the_output_early_does_not_hang() {
|
||||||
|
let pipe = make_pipe! { D : u64 => u64, | double : Num => Num, };
|
||||||
|
let mut it = pipe.apply(0..1_000_000u64, 4, 2);
|
||||||
|
assert!(it.next().is_some());
|
||||||
|
drop(it); // Drop drains the channel and joins the scheduler thread.
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
//! Behaviour of `Throttle` / `throttle()`: bounded number of in-flight items.
|
||||||
|
|
||||||
|
use obipipeline::{Throttle, throttle};
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||||
|
use std::thread;
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn throttle_yields_every_item_in_order() {
|
||||||
|
let items: Vec<u32> = throttle(0..10u32, 100).map(|t| t.item).collect();
|
||||||
|
assert_eq!(items, (0..10).collect::<Vec<_>>());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn in_flight_items_never_exceed_the_bound() {
|
||||||
|
const MAX: usize = 3;
|
||||||
|
let in_flight = Arc::new(AtomicUsize::new(0));
|
||||||
|
let peak = Arc::new(AtomicUsize::new(0));
|
||||||
|
let mut handles = Vec::new();
|
||||||
|
for t in throttle(0..40u32, MAX) {
|
||||||
|
let now = in_flight.fetch_add(1, Ordering::SeqCst) + 1;
|
||||||
|
peak.fetch_max(now, Ordering::SeqCst);
|
||||||
|
let in_flight = Arc::clone(&in_flight);
|
||||||
|
handles.push(thread::spawn(move || {
|
||||||
|
thread::sleep(Duration::from_millis(2));
|
||||||
|
in_flight.fetch_sub(1, Ordering::SeqCst);
|
||||||
|
drop(t); // releases the slot
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
for h in handles {
|
||||||
|
h.join().unwrap();
|
||||||
|
}
|
||||||
|
assert!(
|
||||||
|
peak.load(Ordering::SeqCst) <= MAX,
|
||||||
|
"peak {}",
|
||||||
|
peak.load(Ordering::SeqCst)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn acquire_guard_blocks_until_a_slot_is_released() {
|
||||||
|
let t = Arc::new(Throttle::new(1));
|
||||||
|
let g1 = t.acquire_guard();
|
||||||
|
let acquired = Arc::new(AtomicUsize::new(0));
|
||||||
|
let (t2, a2) = (Arc::clone(&t), Arc::clone(&acquired));
|
||||||
|
let h = thread::spawn(move || {
|
||||||
|
let _g = t2.acquire_guard();
|
||||||
|
a2.store(1, Ordering::SeqCst);
|
||||||
|
});
|
||||||
|
thread::sleep(Duration::from_millis(50));
|
||||||
|
assert_eq!(
|
||||||
|
acquired.load(Ordering::SeqCst),
|
||||||
|
0,
|
||||||
|
"second acquire must block"
|
||||||
|
);
|
||||||
|
drop(g1);
|
||||||
|
h.join().unwrap();
|
||||||
|
assert_eq!(acquired.load(Ordering::SeqCst), 1);
|
||||||
|
}
|
||||||
Reference in new issue
Block a user