From 7e521edfde549db9434d19632370df17fdf84911 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Tue, 1 Dec 2026 17:43:27 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=94=A5=20remove:=20every=20code=20comment?= =?UTF-8?q?=20and=20doc=20comment=20in=20the=20Rust=20sources=20(12k=20lin?= =?UTF-8?q?es),=20per=20the=20no-comments=20rule;=20docs/=20holds=20the=20?= =?UTF-8?q?rationale?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/forge-ci/build_identity.rs | 9 - crates/forge-ci/src/build.rs | 16 - crates/forge-ci/src/config.rs | 138 +------- crates/forge-ci/src/cron.rs | 14 - crates/forge-ci/src/error.rs | 3 - crates/forge-ci/src/lib.rs | 3 - crates/forge-ci/src/mask.rs | 18 -- crates/forge-ci/src/proto.rs | 98 ------ crates/forge-ci/src/size.rs | 6 - crates/forge-ci/src/steps.rs | 13 - crates/forge-core/src/advisories.rs | 36 --- crates/forge-core/src/alerts.rs | 22 -- crates/forge-core/src/audit.rs | 15 - crates/forge-core/src/authz.rs | 24 -- crates/forge-core/src/avatar.rs | 18 -- crates/forge-core/src/cargo.rs | 27 -- crates/forge-core/src/ci.rs | 98 ------ crates/forge-core/src/config.rs | 145 --------- crates/forge-core/src/discussions.rs | 23 -- crates/forge-core/src/error.rs | 2 - crates/forge-core/src/issue_refs.rs | 20 -- crates/forge-core/src/issues.rs | 32 -- crates/forge-core/src/lfs_token.rs | 17 - crates/forge-core/src/lib.rs | 2 - crates/forge-core/src/mail.rs | 33 -- crates/forge-core/src/merge_queue.rs | 14 - crates/forge-core/src/mirrors.rs | 18 -- crates/forge-core/src/model.rs | 24 -- crates/forge-core/src/names.rs | 18 -- crates/forge-core/src/notifications.rs | 14 - crates/forge-core/src/oci.rs | 29 -- crates/forge-core/src/packages.rs | 18 -- crates/forge-core/src/password.rs | 5 - crates/forge-core/src/protection.rs | 37 --- crates/forge-core/src/pulls.rs | 15 - crates/forge-core/src/raw_token.rs | 11 - crates/forge-core/src/reactions.rs | 16 - crates/forge-core/src/releases.rs | 20 -- crates/forge-core/src/reviews.rs | 11 - crates/forge-core/src/secret.rs | 8 - crates/forge-core/src/store/account_tokens.rs | 45 --- crates/forge-core/src/store/admin_alerts.rs | 25 -- crates/forge-core/src/store/advisories.rs | 44 --- crates/forge-core/src/store/attachments.rs | 7 - crates/forge-core/src/store/audit.rs | 12 - crates/forge-core/src/store/backup_runs.rs | 17 - crates/forge-core/src/store/ci.rs | 144 --------- crates/forge-core/src/store/commit_status.rs | 32 -- crates/forge-core/src/store/contributions.rs | 27 -- crates/forge-core/src/store/discussions.rs | 57 ---- .../forge-core/src/store/edit_history_read.rs | 13 - crates/forge-core/src/store/exports.rs | 8 - crates/forge-core/src/store/health.rs | 7 - crates/forge-core/src/store/imports.rs | 16 - crates/forge-core/src/store/labels.rs | 68 ---- crates/forge-core/src/store/lfs.rs | 8 - crates/forge-core/src/store/mail.rs | 36 --- crates/forge-core/src/store/merge_queue.rs | 18 -- crates/forge-core/src/store/migrate.rs | 6 - crates/forge-core/src/store/mirrors.rs | 35 -- crates/forge-core/src/store/mod.rs | 128 -------- crates/forge-core/src/store/needs.rs | 52 --- crates/forge-core/src/store/notifications.rs | 41 --- .../src/store/notifications_extra.rs | 5 - crates/forge-core/src/store/oci.rs | 31 -- crates/forge-core/src/store/orgs.rs | 74 ----- crates/forge-core/src/store/packages.rs | 22 -- crates/forge-core/src/store/passkeys.rs | 24 -- crates/forge-core/src/store/pinned.rs | 15 - crates/forge-core/src/store/profile_pins.rs | 19 -- crates/forge-core/src/store/pull_viewed.rs | 8 - .../forge-core/src/store/pulls_list_extra.rs | 5 - crates/forge-core/src/store/push_recent.rs | 17 - crates/forge-core/src/store/reactions.rs | 17 - crates/forge-core/src/store/releases.rs | 39 --- crates/forge-core/src/store/replication.rs | 14 - crates/forge-core/src/store/repo_listing.rs | 39 --- .../forge-core/src/store/review_requests.rs | 11 - crates/forge-core/src/store/reviews.rs | 52 --- .../forge-core/src/store/server_settings.rs | 8 - crates/forge-core/src/store/shell_activity.rs | 46 --- crates/forge-core/src/store/signatures.rs | 18 -- crates/forge-core/src/store/snapshot.rs | 26 -- crates/forge-core/src/store/snippets.rs | 34 -- crates/forge-core/src/store/suggest.rs | 10 - crates/forge-core/src/store/suspension.rs | 20 -- crates/forge-core/src/store/transfers.rs | 39 --- crates/forge-core/src/store/ui_prefs.rs | 37 --- crates/forge-core/src/store/user_delete.rs | 33 -- crates/forge-core/src/store/user_prefs.rs | 9 - crates/forge-core/src/store/web_push.rs | 23 -- crates/forge-core/src/store/webhooks.rs | 70 ---- crates/forge-core/src/store/wiki.rs | 6 - crates/forge-core/src/suggestions.rs | 19 -- crates/forge-core/src/time.rs | 14 - crates/forge-core/src/token.rs | 11 - crates/forge-core/src/totp.rs | 25 -- crates/forge-core/src/tz.rs | 13 - crates/forge-core/src/webhooks.rs | 31 -- .../tests/integration/audit_store.rs | 5 +- crates/forge-core/tests/integration/common.rs | 2 - crates/forge-core/tests/integration/main.rs | 2 - .../tests/integration/store_basic.rs | 9 - crates/forge-e2e/src/lib.rs | 2 +- .../forge-e2e/tests/e2e/account_mail_e2e.rs | 15 - crates/forge-e2e/tests/e2e/advisories_e2e.rs | 22 -- .../tests/e2e/branch_protection_e2e.rs | 20 -- crates/forge-e2e/tests/e2e/browse_e2e.rs | 28 -- crates/forge-e2e/tests/e2e/ci_e2e.rs | 57 ---- crates/forge-e2e/tests/e2e/common/http.rs | 17 - crates/forge-e2e/tests/e2e/common/mod.rs | 42 --- .../forge-e2e/tests/e2e/community_i18n_e2e.rs | 4 - crates/forge-e2e/tests/e2e/discussions_e2e.rs | 15 - crates/forge-e2e/tests/e2e/git_e2e.rs | 33 -- crates/forge-e2e/tests/e2e/i18n_e2e.rs | 9 - crates/forge-e2e/tests/e2e/issue_close_e2e.rs | 23 -- crates/forge-e2e/tests/e2e/lfs_e2e.rs | 16 - crates/forge-e2e/tests/e2e/main.rs | 4 - crates/forge-e2e/tests/e2e/mirrors_e2e.rs | 41 --- crates/forge-e2e/tests/e2e/oci_e2e.rs | 21 -- crates/forge-e2e/tests/e2e/orgs_core_e2e.rs | 13 - crates/forge-e2e/tests/e2e/orgs_live_e2e.rs | 28 -- crates/forge-e2e/tests/e2e/orgs_ui_e2e.rs | 37 --- crates/forge-e2e/tests/e2e/packages_e2e.rs | 16 - crates/forge-e2e/tests/e2e/pulls_e2e.rs | 41 --- .../tests/e2e/repo_collaborators_e2e.rs | 24 -- crates/forge-e2e/tests/e2e/repo_rename_e2e.rs | 31 -- .../forge-e2e/tests/e2e/repo_transfer_e2e.rs | 19 -- .../forge-e2e/tests/e2e/runner_subcommand.rs | 11 - crates/forge-e2e/tests/e2e/snippets_e2e.rs | 18 -- crates/forge-e2e/tests/e2e/stars_e2e.rs | 17 - crates/forge-e2e/tests/e2e/ui_prefs_e2e.rs | 24 -- crates/forge-e2e/tests/e2e/user_delete_e2e.rs | 12 - crates/forge-e2e/tests/e2e/wiki_e2e.rs | 31 -- crates/forge-git/src/backup.rs | 26 -- crates/forge-git/src/blame.rs | 14 - crates/forge-git/src/branches.rs | 5 - crates/forge-git/src/browse.rs | 51 +-- crates/forge-git/src/churn.rs | 16 - crates/forge-git/src/command.rs | 38 --- crates/forge-git/src/error.rs | 3 - crates/forge-git/src/fsck.rs | 12 - crates/forge-git/src/lib.rs | 2 - crates/forge-git/src/maintenance.rs | 29 -- crates/forge-git/src/mirror.rs | 49 --- crates/forge-git/src/pktline.rs | 6 - crates/forge-git/src/repo.rs | 40 --- crates/forge-git/src/search.rs | 29 -- crates/forge-git/src/seed.rs | 9 - crates/forge-git/src/service.rs | 11 - crates/forge-git/src/setup.rs | 10 - crates/forge-git/src/tags.rs | 12 - crates/forge-git/src/trailers.rs | 9 - crates/forge-git/src/verify.rs | 41 --- crates/forge-git/src/version.rs | 6 - crates/forge-git/src/wiki.rs | 28 -- .../tests/integration/browse_tools.rs | 3 - crates/forge-git/tests/integration/common.rs | 2 - crates/forge-git/tests/integration/history.rs | 1 - crates/forge-git/tests/integration/main.rs | 2 - crates/forge-runner/build.rs | 3 - crates/forge-runner/src/artifacts.rs | 18 -- crates/forge-runner/src/cache.rs | 99 ------ crates/forge-runner/src/check.rs | 30 -- crates/forge-runner/src/cli.rs | 40 --- crates/forge-runner/src/client.rs | 52 --- crates/forge-runner/src/config.rs | 52 --- crates/forge-runner/src/disk.rs | 13 - crates/forge-runner/src/lib.rs | 5 - crates/forge-runner/src/limiter.rs | 21 -- crates/forge-runner/src/logs.rs | 53 --- crates/forge-runner/src/main.rs | 5 - crates/forge-runner/src/memory.rs | 41 --- crates/forge-runner/src/metrics.rs | 23 -- crates/forge-runner/src/oci/helper.rs | 12 - crates/forge-runner/src/oci/mod.rs | 15 - crates/forge-runner/src/oci/pull.rs | 23 -- crates/forge-runner/src/oci/store.rs | 43 --- crates/forge-runner/src/oci/unpack.rs | 69 ---- crates/forge-runner/src/oom.rs | 28 -- crates/forge-runner/src/pressure.rs | 143 --------- crates/forge-runner/src/restart.rs | 19 -- crates/forge-runner/src/sandbox/exec.rs | 12 - crates/forge-runner/src/sandbox/helper.rs | 88 ----- crates/forge-runner/src/sandbox/idmap.rs | 78 ----- crates/forge-runner/src/sandbox/mod.rs | 24 -- crates/forge-runner/src/sandbox/net.rs | 37 --- crates/forge-runner/src/sandbox/seccomp.rs | 18 -- crates/forge-runner/src/sandbox/spec.rs | 26 -- crates/forge-runner/src/selflog.rs | 28 -- crates/forge-runner/src/update.rs | 37 --- crates/forge-runner/src/workspace.rs | 18 -- .../forge-runner/tests/integration/builtin.rs | 22 -- .../tests/integration/common/mod.rs | 3 - crates/forge-runner/tests/integration/flow.rs | 26 -- .../forge-runner/tests/integration/idmap.rs | 4 - crates/forge-runner/tests/integration/main.rs | 2 - .../tests/integration/unpack_subuid.rs | 9 - crates/forge-ssh/src/backend.rs | 8 - crates/forge-ssh/src/error.rs | 2 - crates/forge-ssh/src/lib.rs | 2 - crates/forge-ssh/src/parse.rs | 34 -- crates/forge-ssh/tests/ssh_e2e.rs | 17 - crates/forge-web-account/src/lib.rs | 2 - .../src/pages/account_tools_tests.rs | 9 - .../forge-web-account/src/pages/activity.rs | 19 -- .../src/pages/admin_backups.rs | 26 -- .../src/pages/admin_health.rs | 47 --- .../src/pages/admin_live_tests.rs | 18 -- .../src/pages/admin_replication.rs | 35 -- .../src/pages/admin_user_detail.rs | 20 -- crates/forge-web-account/src/pages/assets.rs | 30 -- .../forge-web-account/src/pages/audit_log.rs | 63 ---- crates/forge-web-account/src/pages/avatars.rs | 7 - crates/forge-web-account/src/pages/banner.rs | 6 - crates/forge-web-account/src/pages/explore.rs | 21 -- crates/forge-web-account/src/pages/forgot.rs | 22 -- crates/forge-web-account/src/pages/home.rs | 16 - .../src/pages/import_tests.rs | 11 - crates/forge-web-account/src/pages/invites.rs | 4 - crates/forge-web-account/src/pages/login.rs | 47 --- crates/forge-web-account/src/pages/mod.rs | 2 - .../forge-web-account/src/pages/needs_you.rs | 30 -- .../src/pages/not_found_page.rs | 5 - crates/forge-web-account/src/pages/org_ctx.rs | 33 -- .../forge-web-account/src/pages/org_live.rs | 26 -- .../src/pages/org_members.rs | 14 - crates/forge-web-account/src/pages/org_new.rs | 8 - .../src/pages/org_settings.rs | 20 -- .../forge-web-account/src/pages/org_teams.rs | 30 -- crates/forge-web-account/src/pages/palette.rs | 38 --- .../forge-web-account/src/pages/passkeys.rs | 49 --- .../src/pages/passkeys_tests.rs | 24 -- .../src/pages/profile_calendar.rs | 11 - .../src/pages/profile_pins.rs | 25 -- .../forge-web-account/src/pages/register.rs | 39 --- .../src/pages/settings_export.rs | 17 - .../src/pages/settings_gpg.rs | 4 - .../src/pages/settings_gpg_tests.rs | 13 - .../src/pages/settings_keys.rs | 21 -- .../src/pages/settings_notifications.rs | 20 -- .../src/pages/settings_profile.rs | 58 ---- .../src/pages/settings_security.rs | 78 ----- .../src/pages/settings_sessions.rs | 6 - .../src/pages/settings_tokens.rs | 9 - crates/forge-web-account/src/pages/setup.rs | 18 -- .../src/pages/shell_events.rs | 15 - .../src/pages/snippets_live.rs | 19 -- .../src/pages/theme_cookie.rs | 8 - .../forge-web-account/src/pages/user_prefs.rs | 6 - crates/forge-web-app/build.rs | 29 -- crates/forge-web-app/src/access.rs | 22 -- crates/forge-web-app/src/admin_client.rs | 25 -- crates/forge-web-app/src/advisories/mod.rs | 4 - crates/forge-web-app/src/advisories/scan.rs | 13 - crates/forge-web-app/src/advisories/worker.rs | 29 -- crates/forge-web-app/src/alerts.rs | 51 --- crates/forge-web-app/src/api/gitea.rs | 46 --- crates/forge-web-app/src/api/mod.rs | 33 -- crates/forge-web-app/src/api/packages.rs | 28 -- crates/forge-web-app/src/api/releases.rs | 32 -- crates/forge-web-app/src/api/statuses.rs | 14 - crates/forge-web-app/src/audit.rs | 9 - crates/forge-web-app/src/automerge.rs | 19 -- crates/forge-web-app/src/backup/create.rs | 16 - crates/forge-web-app/src/backup/fsck.rs | 11 - .../forge-web-app/src/backup/healthcheck.rs | 11 - crates/forge-web-app/src/backup/mod.rs | 32 -- crates/forge-web-app/src/backup/restore.rs | 23 -- crates/forge-web-app/src/backup/retention.rs | 13 - crates/forge-web-app/src/backup/scheduler.rs | 50 --- crates/forge-web-app/src/backup/tests.rs | 18 -- crates/forge-web-app/src/backup/verify.rs | 17 - crates/forge-web-app/src/ci/api.rs | 107 ------- crates/forge-web-app/src/ci/api_tests.rs | 94 ------ crates/forge-web-app/src/ci/live.rs | 45 --- crates/forge-web-app/src/ci/metrics_chart.rs | 37 --- crates/forge-web-app/src/ci/mod.rs | 24 -- crates/forge-web-app/src/ci/reaper.rs | 23 -- crates/forge-web-app/src/ci/runner_log.rs | 35 -- crates/forge-web-app/src/ci/runner_metrics.rs | 13 - crates/forge-web-app/src/ci/schedule.rs | 80 +---- crates/forge-web-app/src/ci/scheduled.rs | 28 -- crates/forge-web-app/src/client_ip.rs | 15 - crates/forge-web-app/src/exporter.rs | 28 -- crates/forge-web-app/src/exporter/tests.rs | 4 - crates/forge-web-app/src/git_auth.rs | 17 - crates/forge-web-app/src/git_http.rs | 33 -- crates/forge-web-app/src/hook_cmd.rs | 13 - crates/forge-web-app/src/importer/mod.rs | 50 --- crates/forge-web-app/src/importer/remote.rs | 10 - crates/forge-web-app/src/internal.rs | 60 ---- crates/forge-web-app/src/layers.rs | 83 +---- crates/forge-web-app/src/lfs/gc.rs | 22 -- crates/forge-web-app/src/lfs/mod.rs | 14 - crates/forge-web-app/src/lfs/route_tests.rs | 6 - crates/forge-web-app/src/lfs/routes.rs | 33 -- crates/forge-web-app/src/lfs_pointer.rs | 16 - crates/forge-web-app/src/lib.rs | 2 - crates/forge-web-app/src/live.rs | 157 --------- crates/forge-web-app/src/mail/account.rs | 19 -- crates/forge-web-app/src/mail/live.rs | 8 - crates/forge-web-app/src/mail/log.rs | 5 - crates/forge-web-app/src/mail/mod.rs | 15 - crates/forge-web-app/src/mail/smtp.rs | 7 - crates/forge-web-app/src/mail/templates.rs | 24 -- crates/forge-web-app/src/mail/worker.rs | 22 -- crates/forge-web-app/src/merge_queue.rs | 43 --- crates/forge-web-app/src/mirrors/mod.rs | 37 --- crates/forge-web-app/src/mirrors/worker.rs | 19 -- crates/forge-web-app/src/notify.rs | 66 +--- crates/forge-web-app/src/notify_hub.rs | 24 -- crates/forge-web-app/src/oci/auth.rs | 25 -- crates/forge-web-app/src/oci/blobs.rs | 41 --- crates/forge-web-app/src/oci/gc.rs | 17 - crates/forge-web-app/src/oci/manifests.rs | 17 - crates/forge-web-app/src/oci/mod.rs | 31 -- crates/forge-web-app/src/package_ops.rs | 37 --- crates/forge-web-app/src/packages_live.rs | 14 - crates/forge-web-app/src/post_update.rs | 32 -- crates/forge-web-app/src/prune.rs | 8 - crates/forge-web-app/src/pulls_sync.rs | 50 --- crates/forge-web-app/src/release_ops.rs | 46 +-- .../forge-web-app/src/replication/worker.rs | 44 --- crates/forge-web-app/src/signatures.rs | 61 ---- crates/forge-web-app/src/ssh_backend.rs | 10 - crates/forge-web-app/src/state.rs | 30 -- .../forge-web-app/src/test_support/fixture.rs | 9 - crates/forge-web-app/src/test_support/mod.rs | 14 - crates/forge-web-app/src/views/commit_line.rs | 6 - .../forge-web-app/src/views/commit_status.rs | 19 -- crates/forge-web-app/src/views/diff.rs | 70 ---- crates/forge-web-app/src/views/find.rs | 24 -- crates/forge-web-app/src/views/heatmap.rs | 67 ---- crates/forge-web-app/src/views/mod.rs | 145 --------- crates/forge-web-app/src/views/parts.rs | 36 --- crates/forge-web-app/src/views/repo_list.rs | 19 -- .../forge-web-app/src/views/review_thread.rs | 41 --- crates/forge-web-app/src/views/timeline.rs | 14 - crates/forge-web-app/src/webhooks/client.rs | 31 -- crates/forge-web-app/src/webhooks/emit.rs | 53 --- crates/forge-web-app/src/webhooks/mod.rs | 1 - crates/forge-web-app/src/webhooks/payload.rs | 23 -- crates/forge-web-app/src/webhooks/worker.rs | 55 ---- crates/forge-web-base/src/accent.rs | 41 +-- crates/forge-web-base/src/accent_palette.rs | 38 --- crates/forge-web-base/src/blobs.rs | 43 --- crates/forge-web-base/src/compression.rs | 27 -- crates/forge-web-base/src/custom_colour.rs | 22 -- crates/forge-web-base/src/i18n/accents.rs | 7 - crates/forge-web-base/src/i18n/accounts.rs | 8 - crates/forge-web-base/src/i18n/admin.rs | 15 - crates/forge-web-base/src/i18n/alerts.rs | 14 - crates/forge-web-base/src/i18n/audit_names.rs | 7 - crates/forge-web-base/src/i18n/authoring.rs | 5 - crates/forge-web-base/src/i18n/browse.rs | 6 - crates/forge-web-base/src/i18n/code.rs | 20 -- .../forge-web-base/src/i18n/integrations.rs | 10 - crates/forge-web-base/src/i18n/issues.rs | 47 --- crates/forge-web-base/src/i18n/link.rs | 10 - crates/forge-web-base/src/i18n/merge_queue.rs | 5 - crates/forge-web-base/src/i18n/migrate.rs | 12 - crates/forge-web-base/src/i18n/misc.rs | 52 --- crates/forge-web-base/src/i18n/mod.rs | 65 ---- crates/forge-web-base/src/i18n/needs.rs | 3 - crates/forge-web-base/src/i18n/orgs.rs | 26 -- crates/forge-web-base/src/i18n/packages.rs | 3 - crates/forge-web-base/src/i18n/pulls.rs | 14 - .../forge-web-base/src/i18n/pulls_review.rs | 12 - crates/forge-web-base/src/i18n/push.rs | 11 - crates/forge-web-base/src/i18n/releases_ci.rs | 26 -- crates/forge-web-base/src/i18n/repo_admin.rs | 14 - .../src/i18n/server_settings.rs | 8 - crates/forge-web-base/src/i18n/timeline.rs | 5 - crates/forge-web-base/src/lib.rs | 3 - .../src/render/commit_message.rs | 17 - crates/forge-web-base/src/render/emoji.rs | 15 - crates/forge-web-base/src/render/highlight.rs | 33 -- crates/forge-web-base/src/render/markdown.rs | 83 ----- crates/forge-web-base/src/render/mod.rs | 2 - crates/forge-web-base/src/templates.rs | 29 -- crates/forge-web-base/src/theme.rs | 5 - crates/forge-web-base/src/throttle.rs | 28 -- crates/forge-web-pages/src/lib.rs | 2 - .../src/pages/admin_runners.rs | 118 ------- .../forge-web-pages/src/pages/admin_users.rs | 28 -- .../forge-web-pages/src/pages/ci_estimate.rs | 39 --- crates/forge-web-pages/src/pages/ci_fail.rs | 19 -- crates/forge-web-pages/src/pages/ci_job.rs | 84 ----- crates/forge-web-pages/src/pages/ci_runs.rs | 301 ------------------ crates/forge-web-pages/src/pages/code_live.rs | 28 -- .../src/pages/discussion_settings.rs | 7 - .../forge-web-pages/src/pages/edit_history.rs | 22 -- crates/forge-web-pages/src/pages/finder.rs | 7 - .../forge-web-pages/src/pages/issue_meta.rs | 35 -- .../forge-web-pages/src/pages/issue_parts.rs | 89 ------ .../forge-web-pages/src/pages/issues_list.rs | 71 ----- .../forge-web-pages/src/pages/issues_live.rs | 11 - crates/forge-web-pages/src/pages/mod.rs | 2 - .../src/pages/notifications.rs | 76 ----- crates/forge-web-pages/src/pages/packages.rs | 27 -- .../forge-web-pages/src/pages/packages_oci.rs | 10 - crates/forge-web-pages/src/pages/pull_live.rs | 31 -- .../forge-web-pages/src/pages/pull_reviews.rs | 76 ----- crates/forge-web-pages/src/pages/ref_live.rs | 16 - crates/forge-web-pages/src/pages/refs.rs | 9 - crates/forge-web-pages/src/pages/releases.rs | 62 ---- .../src/pages/releases_live.rs | 21 -- crates/forge-web-pages/src/pages/repo_ctx.rs | 61 ---- .../forge-web-pages/src/pages/repo_mirrors.rs | 81 ----- .../forge-web-pages/src/pages/repo_rename.rs | 17 - .../src/pages/repo_security.rs | 12 - .../src/pages/repo_settings_live.rs | 24 -- crates/forge-web-pages/src/pages/repo_side.rs | 36 +-- .../src/pages/repo_transfer.rs | 28 -- crates/forge-web-pages/src/pages/star.rs | 9 - crates/forge-web-pages/src/pages/tree.rs | 39 --- crates/forge-web-pages/src/pages/wiki.rs | 33 -- crates/forge-web-pages/src/pages/wiki_live.rs | 19 -- crates/forge-web-repo/src/lib.rs | 2 - crates/forge-web-repo/src/pages/archive.rs | 12 - crates/forge-web-repo/src/pages/authoring.rs | 27 -- .../src/pages/authoring_tests.rs | 21 -- crates/forge-web-repo/src/pages/blame.rs | 14 - crates/forge-web-repo/src/pages/blob.rs | 10 - crates/forge-web-repo/src/pages/branches.rs | 17 - crates/forge-web-repo/src/pages/ci_badge.rs | 29 -- .../forge-web-repo/src/pages/code_search.rs | 24 -- crates/forge-web-repo/src/pages/commit.rs | 21 -- crates/forge-web-repo/src/pages/commits.rs | 28 -- crates/forge-web-repo/src/pages/compare.rs | 56 ---- .../src/pages/discussion_actions.rs | 18 -- .../src/pages/discussion_live.rs | 18 -- .../src/pages/discussion_live_tests.rs | 13 - .../src/pages/discussion_view.rs | 23 -- .../forge-web-repo/src/pages/discussions.rs | 24 -- crates/forge-web-repo/src/pages/fork.rs | 24 -- .../src/pages/issue_meta_tests.rs | 31 -- crates/forge-web-repo/src/pages/issue_pin.rs | 7 - .../src/pages/issue_pin_tests.rs | 18 -- crates/forge-web-repo/src/pages/issue_view.rs | 47 --- crates/forge-web-repo/src/pages/labels_css.rs | 11 - .../forge-web-repo/src/pages/labels_page.rs | 26 -- .../forge-web-repo/src/pages/merge_queue.rs | 17 - .../src/pages/milestones_page.rs | 22 -- crates/forge-web-repo/src/pages/mod.rs | 2 - .../forge-web-repo/src/pages/pull_branch.rs | 44 --- crates/forge-web-repo/src/pages/pull_flow.rs | 14 - crates/forge-web-repo/src/pages/pull_view.rs | 109 ------- crates/forge-web-repo/src/pages/pulls_list.rs | 14 - .../forge-web-repo/src/pages/pulls_merge.rs | 55 ---- crates/forge-web-repo/src/pages/push.rs | 38 --- crates/forge-web-repo/src/pages/reactions.rs | 6 - .../src/pages/reactions_tests.rs | 21 -- .../src/pages/repo_collaborators.rs | 31 -- crates/forge-web-repo/src/pages/repo_scrub.rs | 18 -- .../forge-web-repo/src/pages/repo_secrets.rs | 34 -- .../src/pages/repo_settings_live_tests.rs | 10 - .../forge-web-repo/src/pages/repo_webhooks.rs | 72 ----- .../src/pages/review_requests.rs | 15 - .../src/pages/security_tab_tests.rs | 9 - crates/forge-web/src/admin_cli.rs | 56 ---- crates/forge-web/src/boot.rs | 28 -- .../forge-web/src/compression_route_tests.rs | 3 - crates/forge-web/src/forgejo_tests.rs | 6 - crates/forge-web/src/gitea_route_tests.rs | 24 -- crates/forge-web/src/importer_route_tests.rs | 12 - crates/forge-web/src/main.rs | 24 -- crates/forge-web/src/page_route_tests/mod.rs | 2 - 469 files changed, 27 insertions(+), 12828 deletions(-) diff --git a/crates/forge-ci/build_identity.rs b/crates/forge-ci/build_identity.rs index 9495351..44edceb 100644 --- a/crates/forge-ci/build_identity.rs +++ b/crates/forge-ci/build_identity.rs @@ -1,12 +1,3 @@ -// Build identity for the binary crates. Not a build script of its own: each binary's build.rs pulls -// this file in with `include!("../forge-ci/build_identity.rs");` and calls `emit_identity()`. It -// emits FORGE_GIT_SHA, FORGE_GIT_DATE and FORGE_GIT_DIRTY for that crate. -// -// Only release builds read git: the commit, its date and the dirty flag, with a rerun when HEAD -// moves. Any other profile emits "unknown" and no per-commit input, so a new commit does not -// rebuild debug or test binaries. Release falls back to the FORGE_BUILD_COMMIT and FORGE_BUILD_DATE -// environment variables when there is no git (a source tarball, a sandbox without the binary). - fn git(args: &[&str]) -> Option { use std::process::Command; let out = Command::new("git").args(args).output().ok()?; diff --git a/crates/forge-ci/src/build.rs b/crates/forge-ci/src/build.rs index a7cd83a..2250ba4 100644 --- a/crates/forge-ci/src/build.rs +++ b/crates/forge-ci/src/build.rs @@ -1,9 +1,5 @@ -//! The build identity of this binary: version, git commit, commit date. Shared by the server and -//! the runner, which are the same binary, so a runner can be compared to the server it talks to. - use std::sync::OnceLock; -/// The crate version. pub const VERSION: &str = env!("CARGO_PKG_VERSION"); struct Identity { @@ -14,9 +10,6 @@ struct Identity { static IDENTITY: OnceLock = OnceLock::new(); -/// Sets the commit, commit date and dirty flag of the running binary. Each binary sets this first -/// thing in main, so this crate has no per-commit input and a new commit does not rebuild -/// everything that depends on it. A second call is ignored. pub fn set_identity(commit: &'static str, date: &'static str, dirty: bool) { let _ = IDENTITY.set(Identity { commit, @@ -25,22 +18,18 @@ pub fn set_identity(commit: &'static str, date: &'static str, dirty: bool) { }); } -/// Short git sha of the commit built, or "unknown" before [`set_identity`]. pub fn commit() -> &'static str { IDENTITY.get().map_or("unknown", |i| i.commit) } -/// Commit date (YYYY-MM-DD), or "unknown" before [`set_identity`]. pub fn date() -> &'static str { IDENTITY.get().map_or("unknown", |i| i.date) } -/// True when the tree had uncommitted changes to tracked files at build time. pub fn dirty() -> bool { IDENTITY.get().is_some_and(|i| i.dirty) } -/// `0.1.0 (cf8e648, 2026-10-20)`, with `cf8e648-dirty` for a dirty tree. pub fn display() -> String { format_build(VERSION, commit(), date(), dirty()) } @@ -50,8 +39,6 @@ pub fn format_build(version: &str, commit: &str, date: &str, dirty: bool) -> Str format!("{version} ({commit}{dirty}, {date})") } -/// The commit sha out of a build string made by [`display`], `None` when it is unknown or the -/// string is not in that shape. pub fn commit_of(build: &str) -> Option<&str> { let inner = build.split_once('(')?.1; let commit = inner.split([',', ')']).next()?.trim(); @@ -59,16 +46,13 @@ pub fn commit_of(build: &str) -> Option<&str> { (!commit.is_empty() && commit != "unknown").then_some(commit) } -/// How a runner's build compares with the server's. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Freshness { UpToDate, Outdated, - /// The runner reported nothing usable (an old runner), or this server's own commit is unknown. Unknown, } -/// Compares by commit, ignoring the dirty marker. pub fn compare(runner: Option<&str>, server: &str) -> Freshness { match (runner.and_then(commit_of), commit_of(server)) { (Some(r), Some(s)) if r == s => Freshness::UpToDate, diff --git a/crates/forge-ci/src/config.rs b/crates/forge-ci/src/config.rs index c3186fc..fe0255f 100644 --- a/crates/forge-ci/src/config.rs +++ b/crates/forge-ci/src/config.rs @@ -1,17 +1,3 @@ -//! Parser and validator for `.forge/ci.toml`. -//! -//! ```toml -//! [on] -//! push = ["main"] -//! pull_request = true -//! -//! [jobs.test] -//! image = "docker.io/rust:1" -//! run = "cargo test --workspace" -//! ``` -//! -//! Globs (`push`, `tags`, `artifacts`) use git-like semantics: `*` does not match `/`, `**` does. - use std::collections::{BTreeMap, BTreeSet}; use globset::{Glob, GlobBuilder}; @@ -19,62 +5,40 @@ use serde::{Deserialize, Serialize}; use crate::error::ConfigError; -/// Largest accepted `ci.toml`, in bytes. const MAX_CONFIG_BYTES: usize = 64 * 1024; -/// Largest number of jobs in one workflow. const MAX_JOBS: usize = 20; -/// Default job timeout. const DEFAULT_TIMEOUT_MINUTES: u32 = 60; -/// Smallest and largest allowed job timeout. const TIMEOUT_RANGE_MINUTES: std::ops::RangeInclusive = 1..=360; -/// Longest workflow `name`, in characters, after trimming. const MAX_WORKFLOW_NAME_CHARS: usize = 40; -/// Largest number of `cache` entries in one job. const MAX_CACHE_ENTRIES: usize = 8; -/// Longest `cache` entry, in characters. const MAX_CACHE_PATH_CHARS: usize = 200; -/// Largest number of `[release] assets` entries. const MAX_RELEASE_ASSETS: usize = 32; -/// Longest `[release] title` template, in characters, after trimming. const MAX_RELEASE_TITLE_CHARS: usize = 200; -/// Most `[on] schedule` entries. const MAX_SCHEDULES: usize = 8; -/// Longest matrix axis value, in characters. const MAX_MATRIX_VALUE_CHARS: usize = 64; -/// A parsed and validated workflow. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct CiConfig { - /// Optional display name, e.g. `"build"`. The CI badge uses it as its label. #[serde(default)] pub name: Option, - /// The `[on]` table. Optional; defaults to manual runs only. #[serde(rename = "on", default)] pub on: Triggers, - /// The `[jobs.]` tables, keyed by job name. #[serde(default)] pub jobs: BTreeMap, - /// The `[release]` table. Optional; when set, a tag run that fully succeeds publishes a release. #[serde(default)] pub release: Option, - /// Keys this forge does not know, as dotted paths, e.g. `release` or `jobs.build.foo`. They are - /// ignored, not rejected, so a newer `ci.toml` still runs on an older forge. Filled by - /// [`parse_config`]; never read from the file. #[serde(skip)] pub warnings: Vec, } -/// The `[release]` table. Requires `on.tags`. See docs/ci.md, Releases. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(default)] pub struct ReleaseSpec { - /// `":"` entries. The glob matches the job's flattened artifact names. pub assets: Vec, pub prerelease: Prerelease, pub draft: bool, pub notes: ReleaseNotes, - /// Template with the placeholder `{tag}`, e.g. `"Release {tag}"`. pub title: String, } @@ -90,10 +54,8 @@ impl Default for ReleaseSpec { } } -/// The `prerelease` key: `"auto"`, `true` or `false`. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Prerelease { - /// A release is a prerelease when its tag contains `-`, e.g. `v1.2.0-rc1`. Auto, Always, Never, @@ -128,36 +90,23 @@ impl<'de> Deserialize<'de> for Prerelease { } } -/// The `notes` key. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum ReleaseNotes { - /// One line per commit since the previous release tag. Commits, - /// No notes. #[serde(rename = "none")] Off, } -/// The `[on]` table. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(default)] pub struct Triggers { - /// Branch globs, e.g. `"main"`, `"release/*"`. pub push: Vec, - /// Tag globs, e.g. `"v*"`. pub tags: Vec, pub pull_request: bool, - /// Defaults to `true`. pub manual: bool, - /// Defaults to `true`. A push to a branch cancels the queued and running runs of - /// older commits on that branch. pub cancel_superseded: bool, - /// Runs the workflow on each merge queue candidate. Without it, a candidate runs the `push` - /// jobs of its target branch (see `docs/merge-queue.md`). pub merge_queue: bool, - /// 5-field cron expressions in UTC, e.g. `"0 3 * * *"`. The server queues a run of the default - /// branch head at each match. pub schedule: Vec, } @@ -175,47 +124,36 @@ impl Default for Triggers { } } -/// One `[jobs.]` table. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct JobSpec { pub image: String, pub run: String, #[serde(default)] pub needs: Vec, - /// Secret names (`^[A-Z_][A-Z0-9_]{0,63}$`) the job receives. #[serde(default)] pub secrets: Vec, #[serde(default)] pub env: BTreeMap, - /// Relative globs of files to keep after a successful run. #[serde(default)] pub artifacts: Vec, - /// Runner labels; every label must be present on the runner. #[serde(default)] pub runs_on: Vec, - /// Workspace-relative directories to keep between runs, e.g. `"target"`. See docs/ci.md, Cache. #[serde(default)] pub cache: Vec, #[serde(default = "default_timeout_minutes")] pub timeout_minutes: u32, #[serde(default = "default_network")] pub network: bool, - /// The job's expected peak memory, as `4g` or `512m` in ci.toml. Stored as bytes. The runner - /// admits the job only when this much is free, and caps the job's cgroup near it. Absent - /// means the runner's default reservation. See docs/ci.md, Memory. #[serde( default, deserialize_with = "deserialize_memory", skip_serializing_if = "Option::is_none" )] pub memory: Option, - /// The `matrix` table. Only present before expansion: [`parse_config`] replaces a matrix job - /// with one job per combination, and those have no matrix. #[serde(default, skip_serializing_if = "Option::is_none")] pub matrix: Option, } -/// A matrix axis value. TOML strings, integers and booleans are all read as text. #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] pub struct MatrixValue(pub String); @@ -242,24 +180,18 @@ impl<'de> Deserialize<'de> for MatrixValue { } } -/// A job's `matrix` table: every key but `exclude` and `include` is an axis with its values. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct MatrixSpec { - /// Combinations to drop. An entry matches a combination that agrees on every key it names. #[serde(default)] pub exclude: Vec>, - /// Extra combinations. Each names a value for every axis, and may add more keys, which are - /// exposed like the axes but are not part of the job name. #[serde(default)] pub include: Vec>, #[serde(flatten)] pub axes: BTreeMap>, } -/// Smallest and largest `memory` a job may declare, in bytes. const MEMORY_RANGE_BYTES: std::ops::RangeInclusive = (64 << 20)..=(1024 << 30); -/// Reads `memory` as a size string (`"4g"`) or as a byte count (what the stored spec holds). fn deserialize_memory<'de, D: serde::Deserializer<'de>>(d: D) -> Result, D::Error> { #[derive(Deserialize)] #[serde(untagged)] @@ -286,26 +218,16 @@ fn default_network() -> bool { true } -/// Something that can start a workflow run. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Event<'a> { - Push { - branch: &'a str, - }, - Tag { - tag: &'a str, - }, + Push { branch: &'a str }, + Tag { tag: &'a str }, PullRequest, Manual, - /// A `[on] schedule` tick. Schedule, - /// A merge queue candidate for `branch`, the target branch. - MergeQueue { - branch: &'a str, - }, + MergeQueue { branch: &'a str }, } -/// Parses and validates a `ci.toml` document. pub fn parse_config(text: &str) -> Result { if text.len() > MAX_CONFIG_BYTES { return Err(ConfigError::TooLarge { @@ -316,7 +238,6 @@ pub fn parse_config(text: &str) -> Result { let de = toml::Deserializer::parse(text).map_err(|e| ConfigError::Toml(e.to_string()))?; let mut warnings = Vec::new(); let mut config: CiConfig = serde_ignored::deserialize(de, |path| { - // serde_ignored marks `Option` wrappers with `?`; they are not part of the key path. let path = path.to_string().replace("?.", ""); warnings.push(format!( "unknown key `{path}` ignored: this forge may be older than your ci.toml" @@ -330,7 +251,6 @@ pub fn parse_config(text: &str) -> Result { } impl CiConfig { - /// Whether an event starts this workflow. pub fn triggered_by(&self, ev: &Event) -> bool { match ev { Event::Push { branch } => matches_any(&self.on.push, branch), @@ -344,14 +264,10 @@ impl CiConfig { } } - /// Whether a run for this event should publish a release when every job succeeds: a - /// `[release]` table is set and the event is a tag that matches `on.tags`. pub fn wants_release(&self, ev: &Event) -> bool { self.release.is_some() && matches!(ev, Event::Tag { .. }) && self.triggered_by(ev) } - /// Job names in dependency order. Ties are broken by name, so the order is stable. - /// Jobs in a cycle, or with unknown needs, are left out. [`parse_config`] rejects both. pub fn job_order(&self) -> Vec<&str> { let mut remaining: BTreeMap<&str, BTreeSet<&str>> = self .jobs @@ -378,10 +294,6 @@ impl CiConfig { order } - /// Checks every job key, then replaces each matrix job with one job per combination, named - /// `base (v1, v2)` with the axis values in axis-name order. Expanded jobs get `MATRIX_` - /// env entries and `${{ matrix.key }}` (or `${matrix.key}`) filled in `image`, `runs_on` and - /// `run`. A `needs` on a matrix job becomes a `needs` on all its combinations. fn expand_matrices(&mut self) -> Result<(), ConfigError> { for name in self.jobs.keys() { if !is_job_name(name) { @@ -481,7 +393,6 @@ impl CiConfig { } impl ReleaseSpec { - /// Whether the release for `tag` is a prerelease. pub fn is_prerelease(&self, tag: &str) -> bool { match self.prerelease { Prerelease::Auto => tag.contains('-'), @@ -490,13 +401,10 @@ impl ReleaseSpec { } } - /// The release title for `tag`: the template with `{tag}` replaced. pub fn title_for(&self, tag: &str) -> String { self.title.trim().replace("{tag}", tag) } - /// Whether an artifact of `job`, under its flattened `artifact_name`, is selected by an - /// `assets` entry. Entries that do not name `job` never match. pub fn asset_matches(&self, job: &str, artifact_name: &str) -> bool { self.assets.iter().any(|asset| { asset_selector(asset).is_some_and(|(selected_job, glob)| { @@ -506,7 +414,6 @@ impl ReleaseSpec { } } -/// Splits an `assets` entry into its job and glob. Validation guarantees the `:`. fn asset_selector(asset: &str) -> Option<(&str, &str)> { asset.split_once(':') } @@ -535,8 +442,6 @@ fn validate_trigger_glob(kind: &'static str, pattern: &str) -> Result<(), Config .map_err(|e| invalid(e.to_string())) } -/// A workflow name: non-empty after trimming, at most [`MAX_WORKFLOW_NAME_CHARS`] characters, and -/// no control characters. fn validate_workflow_name(name: &str) -> Result<(), ConfigError> { let invalid = |reason: &str| ConfigError::InvalidWorkflowName { name: name.to_string(), @@ -557,7 +462,6 @@ fn validate_workflow_name(name: &str) -> Result<(), ConfigError> { Ok(()) } -/// `^[a-z0-9][a-z0-9_-]{0,39}$` fn is_job_name(name: &str) -> bool { let Some((first, rest)) = name.as_bytes().split_first() else { return false; @@ -569,7 +473,6 @@ fn is_job_name(name: &str) -> bool { .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || *b == b'_' || *b == b'-') } -/// `^[A-Z_][A-Z0-9_]{0,63}$`, used for secret and env names. fn is_env_name(name: &str) -> bool { let Some((first, rest)) = name.as_bytes().split_first() else { return false; @@ -608,8 +511,6 @@ fn validate_artifact(job: &str, pattern: &str) -> Result<(), ConfigError> { .map_err(|e| invalid(&e.to_string())) } -/// Checks the `cache` entries of one job: at most [`MAX_CACHE_ENTRIES`], each a valid -/// [`validate_cache_path`], and no duplicates. fn validate_cache(job: &str, entries: &[String]) -> Result<(), ConfigError> { if entries.len() > MAX_CACHE_ENTRIES { return Err(ConfigError::TooManyCacheEntries { @@ -631,9 +532,6 @@ fn validate_cache(job: &str, entries: &[String]) -> Result<(), ConfigError> { Ok(()) } -/// A cache path is a workspace-relative directory: non-empty, at most [`MAX_CACHE_PATH_CHARS`] -/// characters, no leading `/`, no `\`, no empty, `.` or `..` components, no `.git` component, no -/// glob characters and no control characters. fn validate_cache_path(job: &str, path: &str) -> Result<(), ConfigError> { let invalid = |reason: &str| ConfigError::InvalidCachePath { job: job.to_string(), @@ -673,9 +571,6 @@ fn validate_cache_path(job: &str, path: &str) -> Result<(), ConfigError> { Ok(()) } -/// Checks the `[release]` table against the triggers and jobs: tags must be configured, there -/// are at most [`MAX_RELEASE_ASSETS`] assets, each one is valid for [`validate_release_asset`], -/// and the title is valid for [`validate_release_title`]. fn validate_release( release: &ReleaseSpec, on: &Triggers, @@ -696,8 +591,6 @@ fn validate_release( validate_release_title(&release.title) } -/// An asset is `job:glob`. The job must exist and declare artifacts. The glob is matched against -/// flattened artifact names, which never contain `/`, so a glob with `/` is rejected. fn validate_release_asset( asset: &str, jobs: &BTreeMap, @@ -728,8 +621,6 @@ fn validate_release_asset( .map_err(|e| invalid(e.to_string())) } -/// A title template: non-blank after trimming, at most [`MAX_RELEASE_TITLE_CHARS`] characters, -/// and no control characters. fn validate_release_title(title: &str) -> Result<(), ConfigError> { let invalid = |reason: String| ConfigError::InvalidReleaseTitle(reason); if title.trim().is_empty() { @@ -746,8 +637,6 @@ fn validate_release_title(title: &str) -> Result<(), ConfigError> { Ok(()) } -/// Whether `selected` (a job name from the config) names `job`: the job itself, or any -/// combination of the matrix job `selected`. fn names_job(selected: &str, job: &str) -> bool { selected == job || job @@ -766,10 +655,8 @@ fn is_matrix_key(key: &str) -> bool { .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || *b == b'_') } -/// One matrix combination: the job name suffix and its variables. type Combination = (String, BTreeMap); -/// The combinations of a matrix as `(name suffix, variables)`, in a stable order. fn combinations(job: &str, matrix: &MatrixSpec) -> Result, ConfigError> { let bad = |reason: String| ConfigError::InvalidMatrix { job: job.to_string(), @@ -871,8 +758,6 @@ fn combinations(job: &str, matrix: &MatrixSpec) -> Result, Conf .collect()) } -/// A matrix value: non-empty, at most [`MAX_MATRIX_VALUE_CHARS`] characters, no control -/// characters, and none of `,`, `(` and `)`, which would make job names ambiguous. fn validate_matrix_value(value: &str) -> Result<(), String> { if value.is_empty() { return Err("values must not be empty".into()); @@ -893,9 +778,6 @@ fn validate_matrix_value(value: &str) -> Result<(), String> { Ok(()) } -/// Replaces `${{ matrix.key }}` and `${matrix.key}` in `text`. A key that is not in `vars` is an -/// error, so a typo fails at parse time instead of reaching the shell. Anything else that starts -/// with `${` is left alone. fn interpolate( job: &str, text: &str, @@ -1056,7 +938,6 @@ artifacts = ["target/release/forge"] assert!(lint.env.is_empty()); } - /// Every key with a serde default, in the one place a user would see it. #[test] fn defaults_apply_when_keys_are_absent() { let cfg = parse_config(&job_toml("")).unwrap(); @@ -1151,13 +1032,11 @@ artifacts = ["target/release/forge"] parse_config(&job_toml("")).unwrap().jobs["build"].memory, None ); - // The stored spec holds bytes and reads back the same. let job = &parse_config(&job_toml("memory = \"4g\"")).unwrap().jobs["build"]; let json = serde_json::to_string(job).unwrap(); assert!(json.contains("\"memory\":4294967296"), "{json}"); let back: JobSpec = serde_json::from_str(&json).unwrap(); assert_eq!(back.memory, Some(4 << 30)); - // A spec stored before the field existed has none. let old = json.replace(",\"memory\":4294967296", ""); assert_eq!(serde_json::from_str::(&old).unwrap().memory, None); } @@ -1217,7 +1096,6 @@ artifacts = ["target/release/forge"] err_of(&text), ConfigError::TooLarge { max, .. } if max == MAX_CONFIG_BYTES )); - // Exactly at the limit is accepted. let mut at_limit = job_toml(""); let pad = MAX_CONFIG_BYTES - at_limit.len(); at_limit.push_str(&"#".repeat(pad)); @@ -1375,7 +1253,6 @@ artifacts = ["target/release/forge"] "{a,b}".to_string(), long, ]; - // A control character, written as a TOML escape. let text = job_toml(r#"cache = ["a\u0007b"]"#); assert!(matches!( err_of(&text), @@ -1480,7 +1357,6 @@ artifacts = ["target/release/forge"] [jobs.deploy]\nimage = \"i\"\nrun = \"r\"\nneeds = [\"lint\", \"docs\"]\n"; let cfg = parse_config(text).unwrap(); assert_eq!(cfg.job_order(), vec!["docs", "test", "lint", "deploy"]); - // Independent jobs come out in name order. let flat = parse_config( "[jobs.c]\nimage = \"i\"\nrun = \"r\"\n[jobs.a]\nimage = \"i\"\nrun = \"r\"\n[jobs.b]\nimage = \"i\"\nrun = \"r\"\n", ) @@ -1535,7 +1411,6 @@ artifacts = ["target/release/forge"] )); } - /// A tag-triggered workflow with a `build` job that has artifacts, plus `[release]` body. fn release_toml(release: &str) -> String { format!( "[on]\ntags = [\"v*\"]\n{}\n[release]\n{release}\n", @@ -1699,7 +1574,6 @@ artifacts = ["target/release/forge"] assert!(release.asset_matches("build", "SHA256SUMS")); assert!(!release.asset_matches("build", "forge-1.2.0-darwin-arm64")); assert!(!release.asset_matches("build", "SHA256SUMS.sig")); - // The same glob under another job name does not match. assert!(!release.asset_matches("lint", "SHA256SUMS")); assert!(!ReleaseSpec::default().asset_matches("build", "SHA256SUMS")); } @@ -1784,7 +1658,6 @@ artifacts = ["target/release/forge"] assert!(!cfg.jobs.contains_key("test (1.85, aarch64)")); let extra = &cfg.jobs["test (nightly, x86_64)"]; assert_eq!(extra.env["MATRIX_FLAG"], "-Z"); - // A partial exclude drops every combination that agrees on the named keys. let m = r#"{ rust = ["stable", "1.85"], target = ["x86_64"], exclude = [{ rust = "1.85" }] }"#; let cfg = parse_config(&matrix_toml(m, "")).unwrap(); @@ -1792,7 +1665,6 @@ artifacts = ["target/release/forge"] cfg.jobs.keys().collect::>(), ["test (stable, x86_64)"] ); - // An include that repeats an existing combination adds nothing. let m = r#"{ rust = ["stable"], target = ["x86_64"], include = [{ rust = "stable", target = "x86_64" }] }"#; assert_eq!(parse_config(&matrix_toml(m, "")).unwrap().jobs.len(), 1); } @@ -1807,7 +1679,6 @@ artifacts = ["target/release/forge"] assert_eq!(cfg.jobs["ship"].needs.len(), 4); let order = cfg.job_order(); assert_eq!(order.last(), Some(&"ship")); - // The matrix job's own needs apply to each combination. let text = format!( "[jobs.setup]\nimage = \"img\"\nrun = \"true\"\n{}", matrix_toml(GRID, "needs = [\"setup\"]") @@ -1830,7 +1701,6 @@ artifacts = ["target/release/forge"] } ); assert!(e.to_string().contains("limit is 20")); - // Expansion that fits one job but not the workflow hits the job cap. let mut text = String::new(); for i in 0..MAX_JOBS - 1 { text.push_str(&format!("[jobs.j{i}]\nimage = \"img\"\nrun = \"true\"\n")); @@ -1853,11 +1723,9 @@ artifacts = ["target/release/forge"] "{bad}" ); } - // A typo in an interpolation fails at parse time. let text = "[jobs.t]\nimage = \"i\"\nrun = \"echo ${matrix.nope}\"\nmatrix = { a = [\"x\"] }\n"; assert!(matches!(err_of(text), ConfigError::InvalidMatrix { .. })); - // Plain job keys cannot smuggle a suffix. let text = "[jobs.\"t (x)\"]\nimage = \"i\"\nrun = \"x\"\n"; assert!(matches!(err_of(text), ConfigError::InvalidJobName(_))); } diff --git a/crates/forge-ci/src/cron.rs b/crates/forge-ci/src/cron.rs index 8967e92..680adb5 100644 --- a/crates/forge-ci/src/cron.rs +++ b/crates/forge-ci/src/cron.rs @@ -1,12 +1,6 @@ -//! Standard 5-field cron expressions in UTC, for `[on] schedule`. -//! -//! Times are Unix seconds. The functions are pure, so the scheduler's tick logic can be tested -//! with a fake clock. - use chrono::DateTime; use croner::Cron; -/// Parses a 5-field cron expression (`minute hour day-of-month month day-of-week`). pub fn parse(expr: &str) -> Result { let trimmed = expr.trim(); if trimmed.split_whitespace().count() != 5 { @@ -17,15 +11,12 @@ pub fn parse(expr: &str) -> Result { trimmed.parse::().map_err(|e| e.to_string()) } -/// The first time strictly after `after` that `cron` matches. fn next_one(cron: &Cron, after: i64) -> Option { let start = DateTime::from_timestamp(after, 0)?.naive_utc(); let next = cron.find_next_occurrence(&start, false).ok()?; Some(next.and_utc().timestamp()) } -/// The first time strictly after `after` that any of `exprs` matches. Expressions that do not -/// parse are ignored. pub fn next_after>(exprs: &[S], after: i64) -> Option { exprs .iter() @@ -34,8 +25,6 @@ pub fn next_after>(exprs: &[S], after: i64) -> Option { .min() } -/// Whether any of `exprs` matched a time `t` with `last < t <= now`. However many ticks fell in -/// that window, the answer is one yes: a scheduler that was down catches up once. pub fn fired_between>(exprs: &[S], last: i64, now: i64) -> bool { next_after(exprs, last).is_some_and(|t| t <= now) } @@ -44,16 +33,13 @@ pub fn fired_between>(exprs: &[S], last: i64, now: i64) -> bool { mod tests { use super::*; - // 2026-10-15 12:00:00 UTC const NOON: i64 = 1_791_979_200; #[test] fn fires_inside_the_window_only() { assert!(fired_between(&["30 12 * * *"], NOON, NOON + 1800)); assert!(!fired_between(&["30 12 * * *"], NOON, NOON + 1799)); - // The window is open at `last`: a tick already handled does not fire again. assert!(!fired_between(&["0 12 * * *"], NOON, NOON + 60)); - // A week of downtime is still one yes. assert!(fired_between(&["* * * * *"], NOON, NOON + 7 * 86_400)); } } diff --git a/crates/forge-ci/src/error.rs b/crates/forge-ci/src/error.rs index 35682b1..9334579 100644 --- a/crates/forge-ci/src/error.rs +++ b/crates/forge-ci/src/error.rs @@ -1,8 +1,5 @@ -//! Errors returned by [`crate::config::parse_config`]. - use thiserror::Error; -/// Why a `.forge/ci.toml` file was rejected. #[derive(Debug, Clone, PartialEq, Eq, Error)] pub enum ConfigError { #[error("ci config is {size} bytes, the limit is {max} bytes")] diff --git a/crates/forge-ci/src/lib.rs b/crates/forge-ci/src/lib.rs index 6d6791b..fb0ecd2 100644 --- a/crates/forge-ci/src/lib.rs +++ b/crates/forge-ci/src/lib.rs @@ -1,6 +1,3 @@ -//! CI workflow config (`.forge/ci.toml`), the runner protocol, and log masking. Shared by -//! forge-web and forge-runner. - pub mod build; pub mod config; pub mod cron; diff --git a/crates/forge-ci/src/mask.rs b/crates/forge-ci/src/mask.rs index 8ee022d..a7c45ff 100644 --- a/crates/forge-ci/src/mask.rs +++ b/crates/forge-ci/src/mask.rs @@ -1,22 +1,14 @@ -//! Secret masking for job logs. Replaces every secret value, and its standard base64 encoding, -//! with `***`. [`MaskStream`] does the same over chunks, so a secret split across two chunks is -//! still masked. - use std::collections::BTreeSet; use std::fmt; use base64::Engine as _; use base64::engine::general_purpose::STANDARD; -/// The text that replaces every match. pub const MASK: &str = "***"; -/// Values shorter than this (in chars) are not masked, since they would hide ordinary output. pub const MIN_SECRET_CHARS: usize = 4; -/// Masks a fixed set of secret values. #[derive(Clone)] pub struct Masker { - /// Byte patterns (raw values and their base64), longest first, deduplicated. patterns: Vec>, } @@ -29,7 +21,6 @@ impl fmt::Debug for Masker { } impl Masker { - /// Builds a masker. Values shorter than [`MIN_SECRET_CHARS`] are ignored. pub fn new(secrets: impl IntoIterator) -> Self { let mut set: BTreeSet> = BTreeSet::new(); for value in secrets { @@ -46,12 +37,9 @@ impl Masker { } } -/// Masks a byte stream that arrives in chunks. #[derive(Debug, Clone)] pub struct MaskStream { masker: Masker, - /// Bytes held back because they may be the start of a secret. Never more than the longest - /// pattern minus one. held: Vec, } @@ -63,7 +51,6 @@ impl MaskStream { } } - /// Feeds one chunk. Returns the masked bytes that are now safe to emit. pub fn push(&mut self, chunk: &[u8]) -> Vec { self.held.extend_from_slice(chunk); let (out, rest) = scan(&self.masker.patterns, &self.held, false); @@ -71,7 +58,6 @@ impl MaskStream { out } - /// Ends the stream and returns whatever is still held back, masked. pub fn finish(&mut self) -> Vec { let held = std::mem::take(&mut self.held); let (out, _) = scan(&self.masker.patterns, &held, true); @@ -79,9 +65,6 @@ impl MaskStream { } } -/// Walks `input` and writes masked bytes. A match is replaced by [`MASK`]. When `last` is false, -/// the scan stops at the first position where a pattern could still complete in later input, and -/// returns that unprocessed tail. When `last` is true, the whole input is processed. fn scan(patterns: &[Vec], input: &[u8], last: bool) -> (Vec, Vec) { let mut out = Vec::with_capacity(input.len()); let mut i = 0; @@ -141,7 +124,6 @@ mod tests { fn short_values_are_ignored() { let m = masker(&["abc", "", "ab"]); assert_eq!(stream_all(&m, &[b"abc ab"]), "abc ab"); - // 4 chars is the minimum that is masked. let m = masker(&["abcd"]); assert_eq!(stream_all(&m, &[b"xabcdx"]), "x***x"); } diff --git a/crates/forge-ci/src/proto.rs b/crates/forge-ci/src/proto.rs index b68d1bf..f5b0c13 100644 --- a/crates/forge-ci/src/proto.rs +++ b/crates/forge-ci/src/proto.rs @@ -1,8 +1,3 @@ -//! Runner <-> forge JSON protocol. All types use snake_case field names and are serialized as JSON. -//! -//! Types that carry secrets (`RegisterRequest`, `RegisterResponse`, `JobAssignment`) implement -//! `Debug` by hand and print `` for their secret fields, so they never end up in logs. - use std::collections::BTreeMap; use std::fmt; @@ -10,10 +5,8 @@ use serde::{Deserialize, Serialize}; pub const RESTART_EXIT_CODE: u8 = 75; -/// `POST /api/v1/ci/runners/register` #[derive(Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct RegisterRequest { - /// Single-use registration token, as shown once by the admin page. pub token: String, pub name: String, pub labels: Vec, @@ -29,11 +22,9 @@ impl fmt::Debug for RegisterRequest { } } -/// Response to [`RegisterRequest`]. #[derive(Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct RegisterResponse { pub runner_id: String, - /// Bearer secret for all later runner calls. Shown to the runner once. pub runner_secret: String, } @@ -46,66 +37,42 @@ impl fmt::Debug for RegisterResponse { } } -/// `POST /api/v1/ci/runners/claim`. Long-polls for up to 30s; 204 means nothing was claimed. -/// The labels are informational: the server uses the labels stored for the runner. #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct ClaimRequest { pub labels: Vec, - /// The runner's live job concurrency. Absent from an older runner. #[serde(default, skip_serializing_if = "Option::is_none")] pub concurrency: Option, - /// The runner's version, for the admin page. #[serde(default, skip_serializing_if = "Option::is_none")] pub version: Option, - /// Logical CPUs of the runner's host. #[serde(default, skip_serializing_if = "Option::is_none")] pub cpus: Option, - /// Total memory of the runner's host, in bytes. #[serde(default, skip_serializing_if = "Option::is_none")] pub memory_bytes: Option, - /// The runner's build identity (`0.1.0 (cf8e648, 2026-10-20)`). Absent from an older runner. #[serde(default, skip_serializing_if = "Option::is_none")] pub build: Option, - /// Random per process start. The forge sees a restart when it changes. #[serde(default, skip_serializing_if = "Option::is_none")] pub boot_id: Option, - /// Features this runner has, such as [`CAP_RESTART`]. The crate version is the same for every - /// build, so the forge gates features on this list. Absent from an older runner. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub capabilities: Vec, - /// Memory the runner can admit right now: its budget minus what running jobs reserved, in - /// bytes. The forge hands out only a job whose reservation fits. Absent from an older runner, - /// which gets the first job in the queue as before. #[serde(default, skip_serializing_if = "Option::is_none")] pub free_memory_bytes: Option, - /// The runner's whole memory budget for jobs, in bytes. A job that reserves more than this - /// still runs when the runner is idle. #[serde(default, skip_serializing_if = "Option::is_none")] pub memory_budget_bytes: Option, - /// What the runner reserves for a job that declares no `memory`, in bytes. #[serde(default, skip_serializing_if = "Option::is_none")] pub reserve_memory_bytes: Option, } -/// The capability of a runner that obeys [`RESTART_HEADER`]. pub const CAP_RESTART: &str = "restart"; -/// The capability of a runner that may hand a running job back with [`RequeueRequest`]. pub const CAP_REQUEUE: &str = "requeue"; -/// `POST /api/v1/ci/jobs/{id}/requeue`: the runner hands a running job back to the queue, for -/// example to free memory. The job keeps its place in the queue and starts again from a clean log. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct RequeueRequest { pub reason: String, } -/// The capability of a runner that ships its own log with [`RunnerLogBatch`]. pub const CAP_RUNNER_LOG: &str = "runner_log"; -/// `POST /api/v1/ci/runners/log`: lines of the runner's own log (not a job's), so an admin can see -/// on the runner's page what it was doing, for example why it claimed nothing. Lines are numbered -/// from 0 per process start (`boot_id`); `first_seq` is the number of the first line in `lines`. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct RunnerLogBatch { pub boot_id: String, @@ -113,21 +80,15 @@ pub struct RunnerLogBatch { pub lines: Vec, } -/// One line of a runner's own log. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct RunnerLogLine { - /// Unix time in milliseconds. pub at_ms: i64, - /// `error`, `warn`, `info`, `debug` or `trace`. pub level: String, - /// The formatted message with its fields, without timestamp or level. pub text: String, } -/// Longest text kept for one runner log line, in bytes. pub const RUNNER_LOG_MAX_TEXT: usize = 4096; -/// `text` cut to at most `max` bytes, on a character boundary. pub fn truncate_text(text: &str, max: usize) -> &str { if text.len() <= max { return text; @@ -139,59 +100,39 @@ pub fn truncate_text(text: &str, max: usize) -> &str { &text[..end] } -/// The answer to a [`RunnerLogBatch`]: the number of the next line the forge wants for this boot -/// id. A forge that restarted (or never saw this boot id) answers 0 and the runner resends what it -/// still holds; lines it no longer holds are skipped. #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct RunnerLogAck { pub next_seq: u64, } -/// The capability of a runner that sends [`RunnerMetricsBatch`]. pub const CAP_RUNNER_METRICS: &str = "runner_metrics"; -/// `POST /api/v1/ci/runners/metrics`: host usage samples, oldest first, for the graphs on the -/// runner's admin page. Answered with 204. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RunnerMetricsBatch { pub samples: Vec, } -/// One sample of the runner's host. Rates cover the time since the previous sample. #[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] pub struct RunnerSample { - /// Unix time in milliseconds. pub at_ms: i64, - /// Busy share of all CPUs, 0 to 100. pub cpu_percent: f32, - /// Memory in use (total minus available), in bytes. pub mem_used_bytes: u64, pub mem_total_bytes: u64, - /// Received and sent bytes per second over every interface but loopback. pub net_rx_bytes_per_s: u64, pub net_tx_bytes_per_s: u64, - /// Used and total bytes of the filesystem holding the runner's work dir. Zero from older runners. #[serde(default)] pub disk_used_bytes: u64, #[serde(default)] pub disk_total_bytes: u64, - /// Jobs running on the runner. pub running_jobs: u32, } -/// Response header on a claim: an admin asked this runner to restart. The value is `drain` (finish -/// the running jobs first) or `now` (cancel them). Absent means no request. The runner stops -/// claiming, restarts the way a self-update does (exit 75), and the forge clears -/// the request when it sees a new boot id. pub const RESTART_HEADER: &str = "Forge-Runner-Restart"; -/// How a runner restarts when an admin asks. #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum RestartMode { - /// Stop claiming, let the running jobs finish, then restart. Drain, - /// Cancel the running jobs, then restart. Now, } @@ -203,7 +144,6 @@ impl RestartMode { } } - /// Parses a header value. Anything else counts as no request. pub fn parse(text: &str) -> Option { match text.trim() { "drain" => Some(Self::Drain), @@ -213,34 +153,22 @@ impl RestartMode { } } -/// Request header on a heartbeat: the runner's build identity, same value as `ClaimRequest::build`. pub const BUILD_HEADER: &str = "Forge-Runner-Build"; -/// Response header on a claim: the concurrency an admin set for this runner in the web UI. Absent -/// when there is no override, which means the runner uses the value from its own `runner.toml`. pub const CONCURRENCY_HEADER: &str = "Forge-Runner-Concurrency"; -/// Response header on a claim: the memory budget an admin set for this runner in the web UI -/// (`6g`). Absent means no override. Live, like [`CONCURRENCY_HEADER`]. pub const MEMORY_BUDGET_HEADER: &str = "Forge-Runner-Memory-Budget"; -/// Response header on a claim: the default memory reservation an admin set (`1g`). Absent means no -/// override. pub const RESERVE_MEMORY_HEADER: &str = "Forge-Runner-Reserve-Memory"; -/// The smallest and largest job concurrency a runner accepts. pub const MIN_CONCURRENCY: u32 = 1; pub const MAX_CONCURRENCY: u32 = 64; -/// Returned with 200 by the claim endpoint. #[derive(Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct JobAssignment { pub job_id: String, - /// Bearer token for `/api/v1/ci/jobs/{id}/...` and for read-only git access. pub job_token: String, - /// `owner/name`. pub repo: String, - /// HTTPS clone URL of the repo. pub clone_url: String, pub commit: String, pub git_ref: String, @@ -248,23 +176,16 @@ pub struct JobAssignment { pub image: String, pub run: String, pub env: BTreeMap, - /// Secret values, by name. Never print these. pub secrets: BTreeMap, pub artifacts: Vec, pub timeout_minutes: u32, pub network: bool, - /// Workspace-relative directories to cache, already validated. Empty when the job has no cache. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub cache: Vec, - /// The cache scope this job may write, e.g. `ref:refs/heads/main` or `pr:12`. Empty means the - /// runner neither restores nor saves a cache for this job. The runner namespaces it by repo and job. #[serde(default, skip_serializing_if = "String::is_empty")] pub cache_key: String, - /// Read-only fallback scopes, tried in order when `cache_key` has no entry. Never written. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub cache_restore_keys: Vec, - /// The job's declared peak memory in bytes (`memory` in ci.toml). Absent when the job did not - /// declare one, and from an older forge: the runner then reserves its default. #[serde(default, skip_serializing_if = "Option::is_none")] pub memory_bytes: Option, } @@ -294,53 +215,37 @@ impl fmt::Debug for JobAssignment { } } -/// `PUT /api/v1/ci/runners/config`: the runner's effective `runner.toml` as flat JSON by dotted key -/// (`limits.memory`). Secrets are redacted by the runner before they get here. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct RunnerConfigReport { pub config: BTreeMap, } -/// Response to `GET` and `PUT /api/v1/ci/runners/config`: the values an admin set in the web UI, -/// by the same dotted keys. A key that is absent has no override. The runner applies the -/// restart-time ones when it starts; `concurrency` and `labels` are live and travel elsewhere. #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct RunnerConfigOverrides { #[serde(default)] pub overrides: BTreeMap, } -/// Response to `POST /api/v1/ci/jobs/{id}/heartbeat`. #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct HeartbeatResponse { pub cancel: bool, - /// The concurrency an admin set in the web UI. Absent means no override (use `runner.toml`). - /// A runner at its limit does not claim, so it learns about a change from its heartbeats. #[serde(default, skip_serializing_if = "Option::is_none")] pub concurrency: Option, - /// A restart an admin asked for. Absent from a forge that does not know the feature. #[serde(default, skip_serializing_if = "Option::is_none")] pub restart: Option, } -/// `POST /api/v1/ci/jobs/{id}/finish`. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct FinishRequest { pub outcome: Outcome, pub exit_code: Option, pub message: Option, - /// True when the OOM killer killed a process in the job's cgroup, read from its - /// `memory.events`. This is what shows an OOM kill that the job survived: cargo reports a - /// killed rustc in the log and exits 101. Absent from an older runner, from a runner that - /// cannot read the cgroup, and when nothing was killed. #[serde(default, skip_serializing_if = "Option::is_none")] pub oom_killed: Option, - /// How many processes the OOM killer took in the job's cgroup (`oom_kill`). #[serde(default, skip_serializing_if = "Option::is_none")] pub oom_kills: Option, } -/// Final result of a job, reported by the runner. #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum Outcome { @@ -364,7 +269,6 @@ mod tests { fn old_and_new_claim_and_heartbeat_bodies_parse() { let old: ClaimRequest = serde_json::from_str(r#"{"labels":["linux"]}"#).unwrap(); assert_eq!(old.concurrency, None); - // An old runner sends no memory fields, so the forge applies no memory filter. assert_eq!(old.free_memory_bytes, None); assert_eq!(old.reserve_memory_bytes, None); let json = serde_json::to_string(&old).unwrap(); @@ -405,7 +309,6 @@ mod tests { oom_kills: None, }; let json = serde_json::to_string(&req).unwrap(); - // An old runner's body, and a new runner that saw no OOM kill, look the same. assert_eq!( json, r#"{"outcome":"failure","exit_code":2,"message":null}"# @@ -449,7 +352,6 @@ mod tests { }; let json = serde_json::to_string(&job).unwrap(); assert!(!json.contains("cache"), "{json}"); - // An older server's reply, without the cache fields, still parses. let back: JobAssignment = serde_json::from_str(&json).unwrap(); assert_eq!(back, job); } diff --git a/crates/forge-ci/src/size.rs b/crates/forge-ci/src/size.rs index 8f0d386..2f1340f 100644 --- a/crates/forge-ci/src/size.rs +++ b/crates/forge-ci/src/size.rs @@ -1,7 +1,3 @@ -//! Byte sizes such as `4g` or `512m`, for `memory` in ci.toml and the runner's memory settings. - -/// Parses `4g`, `512m`, `1.5g`, `64k`, `4gb`, `4GiB`, `1t` or a plain byte count. Units are -/// powers of 1024. `None` for anything else, for zero and for a size that overflows. pub fn parse_size(text: &str) -> Option { let lower = text.trim().to_ascii_lowercase(); let split = lower @@ -34,8 +30,6 @@ pub fn parse_size(text: &str) -> Option { (bytes > 0).then_some(bytes) } -/// Formats a byte count the way an admin would type it: `4g`, `512m`, or plain bytes when it is -/// not a whole number of MiB. pub fn format_size(bytes: u64) -> String { const GIB: u64 = 1 << 30; const MIB: u64 = 1 << 20; diff --git a/crates/forge-ci/src/steps.rs b/crates/forge-ci/src/steps.rs index c27f9fc..5c54bde 100644 --- a/crates/forge-ci/src/steps.rs +++ b/crates/forge-ci/src/steps.rs @@ -1,30 +1,18 @@ -//! Job steps from the log: `::group::Name` opens a step and `::endgroup::` closes it, the way the -//! browser's log viewer reads them. Only top-level groups are steps; nested groups add no marks. - -/// The most steps kept per job. Later top-level groups are not stored. pub const MAX_STEPS: usize = 32; -/// The longest step name, in characters. Longer names are cut. pub const MAX_STEP_NAME_CHARS: usize = 80; -/// A change of step state found in a log line. #[derive(Debug, Clone, PartialEq, Eq)] pub enum StepMark { - /// A top-level group opened. `offset` is the byte position of its line in the log. Start { name: String, offset: u64 }, - /// The open top-level group closed. End, } -/// The marks found in the complete lines of a chunk, and how many bytes of it they used. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Scan { pub marks: Vec, - /// Bytes through the last newline. A partial last line is left for the next scan. pub consumed: usize, } -/// Reads the complete lines of `bytes`, which start at log byte `base_offset`. `depth` is the -/// number of open groups and carries over between scans. pub fn scan(bytes: &[u8], base_offset: u64, depth: &mut u32) -> Scan { let mut marks = Vec::new(); let mut start = 0; @@ -59,7 +47,6 @@ pub fn scan(bytes: &[u8], base_offset: u64, depth: &mut u32) -> Scan { } } -/// Drops the ANSI escape sequences and the other control characters (a tab stays) of a log line. pub fn strip_ansi(line: &str) -> String { let mut out = String::with_capacity(line.len()); let mut chars = line.chars().peekable(); diff --git a/crates/forge-core/src/advisories.rs b/crates/forge-core/src/advisories.rs index 819dc77..f453cc2 100644 --- a/crates/forge-core/src/advisories.rs +++ b/crates/forge-core/src/advisories.rs @@ -1,12 +1,3 @@ -//! Security advisories: the OSV records read from a dump, the version ranges they name, and the -//! lockfile parsers that turn a repo's `Cargo.lock`, `package-lock.json` and `go.sum` into -//! dependencies. Storage is in `store/advisories.rs`; the download and the scan are in forge-web. -//! -//! Only the OSV fields the forge needs are read: `id`, `summary`, `aliases`, `severity`, -//! `affected[].package`, `affected[].ranges` (SEMVER and ECOSYSTEM events) and -//! `affected[].versions`. Git ranges are skipped. Versions are compared as semver: a leading `v` -//! is dropped first, so Go versions and Go pseudo-versions compare as semver too. - use std::collections::{BTreeMap, BTreeSet}; use std::io::{Read, Seek}; @@ -15,13 +6,10 @@ use serde_json::Value; use crate::error::{Error, Result}; -/// The OSV ecosystem names the forge knows how to scan. `[advisories] ecosystems` picks a subset. pub const KNOWN_ECOSYSTEMS: [&str; 3] = ["crates.io", "npm", "Go"]; -/// Largest single OSV record read from a dump. Real records are a few KiB. const MAX_RECORD_BYTES: u64 = 4 * 1024 * 1024; -/// One event of a range, in the order it appears in the record. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum Event { @@ -31,13 +19,11 @@ pub enum Event { Limit(String), } -/// One SEMVER or ECOSYSTEM range of an affected package. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct Range { pub events: Vec, } -/// An advisory as it applies to one package in one ecosystem. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct Advisory { pub id: String, @@ -52,7 +38,6 @@ pub struct Advisory { pub versions: Vec, } -/// A package version read from a lockfile. #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] pub struct Dependency { pub ecosystem: String, @@ -118,8 +103,6 @@ struct RawEvent { limit: Option, } -/// Parses one OSV record into one [`Advisory`] per affected package of `ecosystem`. Several -/// `affected` entries for the same package are merged into one advisory. pub fn parse_record(json: &[u8], ecosystem: &str) -> Result> { let record: Record = serde_json::from_slice(json) .map_err(|e| Error::Invalid(format!("advisory record is not valid OSV: {e}")))?; @@ -182,13 +165,8 @@ pub fn parse_record(json: &[u8], ecosystem: &str) -> Result> { Ok(merged.into_values().collect()) } -/// Advisories handed to the sink of [`read_dump`] at a time. const IMPORT_BATCH: usize = 500; -/// Reads every `.json` record of an OSV zip dump for `ecosystem`, handing the advisories to `sink` -/// in batches of about [`IMPORT_BATCH`], so the whole dump is never held in memory. A record that -/// does not parse, or is too large, is skipped and counted in the returned value. An error from -/// the sink or from a broken zip stops the read and is returned. pub fn read_dump(reader: R, ecosystem: &str, mut sink: F) -> Result where R: Read + Seek, @@ -227,13 +205,10 @@ where Ok(skipped) } -/// Parses a version as semver, after dropping a leading `v` (Go style). pub fn parse_version(raw: &str) -> Option { semver::Version::parse(raw.trim().trim_start_matches('v')).ok() } -/// Whether `advisory` covers `version` of its package. A version listed in `versions` matches by -/// text. Otherwise the version must fall inside one of the ranges. pub fn affects(advisory: &Advisory, version: &str) -> bool { let wanted = version.trim().trim_start_matches('v'); if advisory @@ -252,9 +227,6 @@ pub fn affects(advisory: &Advisory, version: &str) -> bool { .any(|range| range_affects(range, &parsed)) } -/// Walks the events of one range. An interval runs from an `introduced` event to the next -/// `fixed` (exclusive) or `last_affected` (inclusive). `introduced` of `0` starts at the beginning. -/// An interval still open at the end runs forever. fn range_affects(range: &Range, version: &semver::Version) -> bool { let mut open: Option> = None; for event in &range.events { @@ -288,8 +260,6 @@ fn starts_before(start: &Option, version: &semver::Version) -> start.as_ref().is_none_or(|s| version >= s) } -/// Reads `Cargo.lock`. Only registry packages count: path and git packages have no `source` -/// from crates.io and are skipped. pub fn parse_cargo_lock(text: &str, manifest_path: &str) -> Result> { #[derive(Deserialize)] struct Lock { @@ -317,8 +287,6 @@ pub fn parse_cargo_lock(text: &str, manifest_path: &str) -> Result Result> { let doc: Value = serde_json::from_str(text) .map_err(|e| Error::Invalid(format!("package-lock.json is not valid JSON: {e}")))?; @@ -333,7 +301,6 @@ pub fn parse_package_lock(text: &str, manifest_path: &str) -> Result name, None => continue, @@ -348,8 +315,6 @@ pub fn parse_package_lock(text: &str, manifest_path: &str) -> Result Vec { let mut seen = BTreeSet::new(); for line in text.lines() { @@ -405,7 +370,6 @@ mod tests { #[test] fn range_events_match_by_table() { - // (case name, range events, (version, expected affected) checks) type Case<'a> = (&'a str, Vec, Vec<(&'a str, bool)>); let cases: Vec = vec![ ( diff --git a/crates/forge-core/src/alerts.rs b/crates/forge-core/src/alerts.rs index 2c0c004..40c1b2c 100644 --- a/crates/forge-core/src/alerts.rs +++ b/crates/forge-core/src/alerts.rs @@ -1,25 +1,13 @@ -//! Admin alerts: the kinds of trouble the forge tells its admins about, and the pure rules that -//! decide when to. Delivery and state live in `store::admin_alerts` and forge-web's `alerts`. - -/// What an alert is about. Each kind has its own on/off setting. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum AlertKind { - /// A CI runner stopped checking in. RunnerOffline, - /// A backup, its verification or an fsck failed, or no backup succeeded in time. Backup, - /// The data directory is nearly full. Disk, - /// A CI job was killed by SIGKILL or the OOM killer. CiKilled, - /// A self-update deployed or failed, and the server restarted. SelfUpdate, - /// The standby is failing or lagging. Replication, } -/// Whether a job's result looks like the process was killed: SIGKILL (`signal: 9`, `SIGKILL`, -/// `Killed`), the shell's `128 + 9` exit code, or an out-of-memory message. pub fn is_kill_signature(exit_code: Option, message: Option<&str>) -> bool { if matches!(exit_code, Some(137) | Some(-9)) { return true; @@ -39,8 +27,6 @@ pub fn is_kill_signature(exit_code: Option, message: Option<&str>) -> bool { return true; } - // "signal: 9", "signal 9", "signal=9", "killed by signal 9". A longer number such as 90 is - // not a match. let mut rest = text.as_str(); while let Some(at) = rest.find("signal") { rest = &rest[at + "signal".len()..]; @@ -56,23 +42,18 @@ pub fn is_kill_signature(exit_code: Option, message: Option<&str>) -> bool text.trim() == "killed" } -/// Free space as a percentage of the total, rounded down. `None` for an empty filesystem. pub fn free_percent(total: u64, available: u64) -> Option { (u128::from(available) * 100) .checked_div(u128::from(total)) .map(|p| u64::try_from(p).unwrap_or(100)) } -/// Whether free space is below the configured floor: under `min_percent` of the total, or under -/// `min_gib` GiB when that is non-zero. pub fn disk_is_low(total: u64, available: u64, min_percent: u64, min_gib: u64) -> bool { let low_percent = free_percent(total, available).is_some_and(|p| p < min_percent); let low_gib = min_gib > 0 && available < min_gib.saturating_mul(1 << 30); low_percent || low_gib } -/// Whether the newest successful backup is older than twice the schedule interval. A forge that -/// never made one counts from `since_unix`, when the alerting began. pub fn backup_overdue( now_unix: i64, last_ok_unix: Option, @@ -85,8 +66,6 @@ pub fn backup_overdue( now_unix.saturating_sub(basis) > limit } -/// Whether a runner has been silent too long. `last_seen_unix` is `None` for one that never -/// checked in, which is not offline: it was never online. pub fn runner_is_offline(now_unix: i64, last_seen_unix: Option, minutes: u64) -> bool { let limit = i64::try_from(minutes.saturating_mul(60)).unwrap_or(i64::MAX); last_seen_unix.is_some_and(|seen| now_unix.saturating_sub(seen) > limit) @@ -98,7 +77,6 @@ mod tests { #[test] fn kill_signatures_are_recognised_and_other_failures_are_not() { - // (exit code, log tail, expected kill) let cases: [(Option, Option<&str>, bool); 15] = [ (Some(137), None, true), (Some(-9), None, true), diff --git a/crates/forge-core/src/audit.rs b/crates/forge-core/src/audit.rs index 67891ab..9653daf 100644 --- a/crates/forge-core/src/audit.rs +++ b/crates/forge-core/src/audit.rs @@ -1,7 +1,3 @@ -//! Security audit log: the action names, the entry shape and the list filter. The stored shape is -//! in migrations/0010_audit_log.sql; the store functions live in store/audit.rs. Rows are never -//! edited; only the retention purge removes them. - use ulid::Ulid; use crate::time::now_stamp; @@ -135,7 +131,6 @@ audit_actions! { } impl AuditAction { - /// The action with this stored name, if any. pub fn parse(name: &str) -> Option { AuditAction::ALL .iter() @@ -144,7 +139,6 @@ impl AuditAction { } } -/// One row of the audit log. `at` is an RFC 3339 UTC stamp. `data` is a JSON object as text. #[derive(Debug, Clone, PartialEq, Eq)] pub struct AuditEntry { pub id: String, @@ -160,7 +154,6 @@ pub struct AuditEntry { } impl AuditEntry { - /// A new entry stamped with the current time and a fresh id. Everything else is empty. pub fn new(action: AuditAction) -> AuditEntry { AuditEntry { id: Ulid::generate().to_string(), @@ -177,22 +170,17 @@ impl AuditEntry { } } -/// Optional filters for [`crate::store::Store::list_audit`]. Unset fields do not restrict. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct AuditFilter { pub actor_id: Option, pub action: Option, pub target_kind: Option, pub target_id: Option, - /// Matches entries where this user is the actor, or the `user` target. pub involving_user: Option, - /// Entries stamped at or after this stamp. pub since: Option, - /// Entries stamped before this stamp. pub until: Option, } -/// Position in the newest-first listing: the last entry of the previous page. #[derive(Debug, Clone, PartialEq, Eq)] pub struct AuditCursor { pub at: String, @@ -200,7 +188,6 @@ pub struct AuditCursor { } impl AuditCursor { - /// The cursor for the entry a page ended on. pub fn after(entry: &AuditEntry) -> AuditCursor { AuditCursor { at: entry.at.clone(), @@ -208,12 +195,10 @@ impl AuditCursor { } } - /// Text form for a URL: `_`. Neither part contains `_`. pub fn encode(&self) -> String { format!("{}_{}", self.at, self.id) } - /// Parses [`AuditCursor::encode`] output. Anything malformed is `None`. pub fn decode(text: &str) -> Option { let (at, id) = text.split_once('_')?; let stamp_ok = at.len() == 30 && at.ends_with('Z') && at.contains('T'); diff --git a/crates/forge-core/src/authz.rs b/crates/forge-core/src/authz.rs index 9cf9d16..ee56c86 100644 --- a/crates/forge-core/src/authz.rs +++ b/crates/forge-core/src/authz.rs @@ -1,40 +1,24 @@ -//! Authorization rules. Pure, no IO. - use crate::model::{Repo, Role, User, Visibility}; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Action { Read, - /// Edit anyone's issue or comment, close/reopen, labels, assignees, milestones. - /// Not blocked by `archived` (the pages handle archived repos). Triage, Write, Admin, - /// Delete the repo. Owner and instance admin only; a collaborator role never grants it. Delete, } -/// `NotFound` when the actor cannot even see the repo; `Forbidden` when they can see it but lack the right. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Denied { NotFound, Forbidden, } -/// The higher of two optional roles. `Read < Triage < Write < Maintain < Admin`. pub fn max_role(a: Option, b: Option) -> Option { a.max(b) } -/// Owner or instance admin: all actions. Public repo: Read for anyone. -/// Private repo with no role: NotFound. Read/Triage: Read. Write/Maintain: Read+Write. Admin: all. -/// Triage is granted to Triage, Write, Maintain and Admin. -/// Archived repos deny Write with Forbidden. -/// -/// `org_role` is the role the actor gets through an organization that owns the repo (see -/// `Store::org_repo_role`). The effective role is `max_role(collaborator_role, org_role)`. A -/// collaborator Admin never deletes a repo; an org-derived Admin (org owner, or a team with -/// the admin role) does, because org-owned repos have no single owner person. pub fn authorize( actor: Option<&User>, repo: &Repo, @@ -42,7 +26,6 @@ pub fn authorize( org_role: Option, action: Action, ) -> Result<(), Denied> { - // A role only belongs to a signed-in actor. let role = if actor.is_some() { max_role(collaborator_role, org_role) } else { @@ -140,7 +123,6 @@ mod tests { } } - /// Expected result from the contract, written independently of the implementation. fn expected( actor: Option<&User>, r: &Repo, @@ -155,7 +137,6 @@ mod tests { return Ok(()); } if action == Action::Delete { - // Only owner or instance admin: hidden repos are 404, visible ones 403. return if r.visibility == Visibility::Public || role.is_some() { Err(Denied::Forbidden) } else { @@ -393,7 +374,6 @@ mod tests { authorize(Some(&root), &r, None, None, Action::Delete), Ok(()) ); - // A collaborator with the top role still cannot delete. assert_eq!( authorize(Some(&stranger), &r, Some(Role::Admin), None, Action::Delete), Err(Denied::Forbidden) @@ -407,7 +387,6 @@ mod tests { } ); } - // Visible to a stranger on a public repo: 403. Hidden: 404. let public = repo(Visibility::Public, false); assert_eq!( authorize(Some(&stranger), &public, None, None, Action::Delete), @@ -418,7 +397,6 @@ mod tests { authorize(Some(&stranger), &private, None, None, Action::Delete), Err(Denied::NotFound) ); - // Archiving does not stop an owner from deleting. let archived = repo(Visibility::Private, true); assert_eq!( authorize(Some(&owner), &archived, None, None, Action::Delete), @@ -514,7 +492,6 @@ mod tests { fn org_role_grants_what_the_collaborator_role_would() { let r = repo(Visibility::Private, false); let member = user("member", false); - // Read-only collaborator, but the org gives Write. assert_eq!( authorize( Some(&member), @@ -525,7 +502,6 @@ mod tests { ), Ok(()) ); - // An org role alone makes a private repo visible. assert_eq!( authorize(Some(&member), &r, None, Some(Role::Read), Action::Read), Ok(()) diff --git a/crates/forge-core/src/avatar.rs b/crates/forge-core/src/avatar.rs index b7d54f2..5c0abc4 100644 --- a/crates/forge-core/src/avatar.rs +++ b/crates/forge-core/src/avatar.rs @@ -1,7 +1,3 @@ -//! Avatar upload processing: validate, decode with limits, crop, resize and re-encode as PNG. -//! -//! Re-encoding to PNG drops all metadata (EXIF, GPS, comments) from the input. - use std::io::Cursor; use image::{ImageFormat, ImageReader, Limits, imageops::FilterType}; @@ -9,16 +5,12 @@ use sha2::{Digest, Sha256}; use crate::error::{Error, Result}; -/// Largest accepted upload, in bytes. pub const MAX_UPLOAD_BYTES: usize = 5 * 1024 * 1024; -/// Largest accepted width or height of the decoded source image, in pixels. const MAX_SOURCE_DIMENSION: u32 = 4096; -/// Upper bound on decoder allocations (128 MiB). const MAX_ALLOC_BYTES: u64 = 128 * 1024 * 1024; -/// Edge length of the stored avatar, in pixels. const AVATAR_SIZE: u32 = 256; #[derive(Debug, Clone, PartialEq, Eq)] @@ -27,9 +19,6 @@ pub struct ProcessedAvatar { pub hash: String, } -/// Decode with limits (max 4096x4096, image::Limits), center-crop to a square, resize to 256x256 -/// (Lanczos3), re-encode as PNG. Metadata (EXIF/GPS) is dropped by re-encoding. SVG, unknown -/// formats, too-large input or a decode failure give Error::Invalid. pub fn process_avatar(bytes: &[u8]) -> Result { if bytes.len() > MAX_UPLOAD_BYTES { return Err(Error::Invalid(format!( @@ -37,7 +26,6 @@ pub fn process_avatar(bytes: &[u8]) -> Result { ))); } - // Format is decided from magic bytes only; the client-supplied type is never consulted. let mut reader = ImageReader::new(Cursor::new(bytes)) .with_guessed_format() .map_err(|_| Error::Invalid("unreadable image header".into()))?; @@ -56,8 +44,6 @@ pub fn process_avatar(bytes: &[u8]) -> Result { limits.max_alloc = Some(MAX_ALLOC_BYTES); reader.limits(limits); - // Center-crop to the largest square, then scale down to the avatar size. The decoded image - // (up to 128 MiB) is dropped as soon as the crop copies it, before the resize allocates. let resized = { let decoded = reader .decode() @@ -116,7 +102,6 @@ mod tests { #[test] fn accepted_inputs_become_256_png_avatars() { - // (name, encoded input). Every accepted input yields a 256x256 PNG. let cases = [ ("png 300x200", encode(&sample(300, 200), ImageFormat::Png)), ("png 64x64", encode(&sample(64, 64), ImageFormat::Png)), @@ -157,10 +142,7 @@ mod tests { #[test] fn huge_declared_dimensions_are_rejected() { - // Take a valid tiny PNG and rewrite its IHDR to claim 50000x50000, fixing the CRC so - // only the dimension limit can reject it. let mut png = encode(&sample(2, 2), ImageFormat::Png); - // Layout: 8-byte signature, 4-byte length, 4-byte "IHDR", then width and height. assert_eq!(&png[12..16], b"IHDR"); png[16..20].copy_from_slice(&50_000u32.to_be_bytes()); png[20..24].copy_from_slice(&50_000u32.to_be_bytes()); diff --git a/crates/forge-core/src/cargo.rs b/crates/forge-core/src/cargo.rs index ad1d4dd..6df84c8 100644 --- a/crates/forge-core/src/cargo.rs +++ b/crates/forge-core/src/cargo.rs @@ -1,8 +1,3 @@ -//! Cargo registry rules, pure and without IO: crate and version names, the publish body, the -//! index line written for each version, the index file path of a crate, and the README and -//! repository link found in a `.crate` file. The wire formats follow the Cargo book's registry -//! chapters: the publish body, the index format (version 2) and the sparse index layout. - use std::io::Read; use flate2::read::GzDecoder; @@ -10,13 +5,9 @@ use serde_json::{Map, Value, json}; use crate::error::{Error, Result}; -/// Longest crate name, in characters. pub const MAX_NAME_CHARS: usize = 64; -/// Largest README read out of a `.crate` file, in bytes. pub const MAX_README_BYTES: u64 = 256 * 1024; -/// Checks a crate name and returns its lowercase key. The key names the index file, so it is -/// what routes and storage use; the name as published is kept for display and the index. pub fn crate_name_key(name: &str) -> Result { let starts_alpha = name.chars().next().is_some_and(|c| c.is_ascii_alphabetic()); let chars_ok = name @@ -30,8 +21,6 @@ pub fn crate_name_key(name: &str) -> Result { Ok(name.to_ascii_lowercase()) } -/// The sparse index path of a crate key, relative to the index URL (`1/a`, `2/ab`, `3/a/abc`, -/// `ab/cd/abcdef`). The key is ASCII, checked by [`crate_name_key`]. pub fn index_path(key: &str) -> String { match key.len() { 1 => format!("1/{key}"), @@ -41,21 +30,16 @@ pub fn index_path(key: &str) -> String { } } -/// Parses a version as semver. Cargo versions are semver, with build metadata kept as written. pub fn parse_version(version: &str) -> Result { semver::Version::parse(version) .map_err(|e| Error::Invalid(format!("`{version}` is not a valid version: {e}"))) } -/// A publish body split into its parts. The metadata is the JSON document, the crate the -/// gzipped tarball whose sha256 the index records. pub struct Publish<'a> { pub metadata: Value, pub crate_file: &'a [u8], } -/// Splits a publish body: a little-endian u32 length and the JSON metadata, then a little-endian -/// u32 length and the `.crate` bytes. Both lengths must match the body exactly. pub fn parse_publish(body: &[u8]) -> Result> { let (json_len, rest) = take_len(body)?; if json_len > rest.len() { @@ -92,13 +76,10 @@ fn take_len(bytes: &[u8]) -> Result<(usize, &[u8])> { Ok((len, rest)) } -/// Text field of the metadata, or `None` when absent or not a string. pub fn meta_str<'a>(meta: &'a Value, key: &str) -> Option<&'a str> { meta.get(key).and_then(Value::as_str) } -/// The dependencies of an index line, from the publish metadata. A renamed dependency -/// (`explicit_name_in_toml`) is listed under its local name, with the real crate in `package`. pub fn index_deps(meta: &Value) -> Vec { let deps = meta.get("deps").and_then(Value::as_array); deps.map_or_else(Vec::new, |list| { @@ -122,8 +103,6 @@ pub fn index_deps(meta: &Value) -> Vec { }) } -/// The index line of one version (format version 2). Features that use the `dep:` or `?` -/// syntax go to `features2`, as the format requires; the rest stay in `features`. pub fn index_line(meta: &Value, checksum: &str) -> Result { let name = meta_str(meta, "name").ok_or_else(|| Error::Invalid("metadata has no name".into()))?; @@ -164,8 +143,6 @@ pub fn index_line(meta: &Value, checksum: &str) -> Result { Ok(line) } -/// The `(owner, repo)` a `repository` URL names on this forge, when it points at a repo under -/// `base_url` (for example `https://git.tahinli.com/`). Any other URL links nothing. pub fn repo_link(repository: &str, base_url: &str) -> Option<(String, String)> { let base = base_url.trim_end_matches('/'); let rest = repository.trim().strip_prefix(base)?.strip_prefix('/')?; @@ -180,12 +157,8 @@ pub fn repo_link(repository: &str, base_url: &str) -> Option<(String, String)> { Some((owner.to_owned(), repo.to_owned())) } -/// The README of a `.crate` file: the first `README*` file at the top of the package directory -/// (`-/README.md`). Read at most [`MAX_README_BYTES`] bytes. Returns `None` when -/// the archive is not a gzipped tarball or has no README. pub fn crate_readme(crate_file: &[u8]) -> Option { const MAX_INFLATED_SCAN_BYTES: u64 = 256 * 1024 * 1024; - // A small upload can inflate without end; past this much the README search gives up. let inflated = GzDecoder::new(crate_file).take(MAX_INFLATED_SCAN_BYTES); let mut archive = tar::Archive::new(inflated); let entries = archive.entries().ok()?; diff --git a/crates/forge-core/src/ci.rs b/crates/forge-core/src/ci.rs index 468fd9f..42d4fd8 100644 --- a/crates/forge-core/src/ci.rs +++ b/crates/forge-core/src/ci.rs @@ -1,9 +1,3 @@ -//! CI models: run and job states, runners, runs, jobs and artifacts. The stored shape is in -//! migrations/0024_ci.sql; the store functions live in store/ci.rs. -//! -//! Job specs are kept as JSON text (`CiJob::spec_json`). The store reads only the `needs` and -//! `runs_on` arrays out of it. - use std::collections::BTreeMap; use std::str::FromStr; @@ -13,7 +7,6 @@ pub use forge_ci::proto::RestartMode; use crate::error::{Error, Result}; -/// State of a run. Stored as the `as_str` name. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum RunState { WaitingApproval, @@ -38,7 +31,6 @@ impl RunState { } } - /// True for states a run cannot leave. pub fn is_terminal(self) -> bool { matches!( self, @@ -64,7 +56,6 @@ impl FromStr for RunState { } } -/// State of a job. Stored as the `as_str` name. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum JobState { Blocked, @@ -91,7 +82,6 @@ impl JobState { } } - /// True for states a job cannot leave. pub fn is_terminal(self) -> bool { matches!( self, @@ -122,7 +112,6 @@ impl FromStr for JobState { } } -/// A registered runner. The secret and its hash are never part of this type. #[derive(Debug, Clone, PartialEq, Eq)] pub struct CiRunner { pub id: String, @@ -131,50 +120,33 @@ pub struct CiRunner { pub created_at: String, pub last_seen_at: Option, pub disabled: bool, - /// The concurrency an admin set in the web UI (1 to 64). `None` means the runner uses the - /// value from its own `runner.toml`. pub concurrency_override: Option, - /// What the runner last reported about itself. All `None` for a runner that never has. pub reported: RunnerReport, - /// Jobs this runner is running now, counted from the job table. pub running_jobs: u32, - /// The runner's effective config as it last reported it, by field key. Secrets are redacted. pub reported_config: BTreeMap, - /// A restart an admin asked for that the runner has not yet carried out. pub restart: Option, - /// Admin-set values by field key. A key here beats the runner's own runner.toml. pub config_overrides: BTreeMap, } -/// A pending runner restart: asked for, not yet seen to happen. #[derive(Debug, Clone, PartialEq, Eq)] pub struct RunnerRestart { pub mode: RestartMode, pub requested_at: String, } -/// How a runner config field can be changed from the web UI. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum FieldKind { - /// Applied on the runner's next check-in, with no restart. Live, - /// Stored now, applied when the runner next starts. Restart, - /// Shown only. ReadOnly, } -/// One field of `runner.toml` as the admin UI sees it. `key` is the dotted TOML path. #[derive(Debug, Clone, Copy)] pub struct RunnerField { pub key: &'static str, pub kind: FieldKind, } -/// Every field the runner reports, in display order. Identity, the secret and the forge URL are -/// read-only: changing them from the forge would lock the runner out. Only `concurrency` and -/// `labels` can be applied without a restart, because the forge holds the labels itself and the -/// runner resizes its job slots live. Everything else is read once at startup. pub const RUNNER_FIELDS: &[RunnerField] = &[ RunnerField { key: "concurrency", @@ -266,7 +238,6 @@ pub const RUNNER_FIELDS: &[RunnerField] = &[ }, ]; -/// The field with this key. pub fn runner_field(key: &str) -> Option<&'static RunnerField> { RUNNER_FIELDS.iter().find(|f| f.key == key) } @@ -283,8 +254,6 @@ fn int_in( } } -/// Checks `raw` (the text the admin typed) for field `key` and returns the JSON value to store. -/// `Err` carries a message for the admin. Read-only and unknown fields are refused. pub fn validate_runner_field( key: &str, raw: &str, @@ -387,72 +356,46 @@ pub fn validate_runner_field( } } -/// Facts a runner reports about itself on a claim or heartbeat. A field the runner did not send is -/// `None` and leaves the stored value alone. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct RunnerReport { - /// The concurrency the runner is applying right now. pub concurrency: Option, pub version: Option, pub cpus: Option, pub memory_bytes: Option, - /// The runner's build identity, like `0.1.0 (cf8e648, 2026-10-20)`. pub build: Option, - /// Random per process start. A change means the runner restarted. pub boot_id: Option, - /// Features the runner says it has. The crate version never changes between builds, so the - /// forge gates features on these and not on the version. pub capabilities: Vec, - /// The runner's memory budget for jobs, in bytes. pub memory_budget: Option, - /// Budget minus what running jobs reserved, as of the runner's last claim. pub memory_free: Option, - /// What the runner reserves for a job that declares no `memory`. pub memory_reserve: Option, } impl RunnerReport { - /// Memory the running jobs reserved, when the runner reports a budget. pub fn memory_reserved(&self) -> Option { Some(self.memory_budget?.saturating_sub(self.memory_free?)) } } -/// How long a queued job that does not fit a runner may wait before smaller jobs stop passing it. -/// See [`pick_by_memory`]. pub const STARVE_AFTER_SECS: u64 = 300; -/// What a runner can admit right now, from its claim. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct MemoryOffer { - /// Budget minus what running jobs reserved, in bytes. pub free: u64, - /// The runner's whole budget. A job that reserves more than this is treated as reserving the - /// whole budget, so it still runs when the runner is idle instead of waiting forever. pub budget: Option, - /// The reservation of a job that declares no `memory`. pub default_reserve: u64, } impl MemoryOffer { - /// What a job reserves on this runner: its declared memory or the default, capped at the - /// budget. pub fn reservation(&self, declared: Option) -> u64 { let want = declared.unwrap_or(self.default_reserve); self.budget.map_or(want, |budget| want.min(budget)) } - /// True when a job with this declared memory fits in the free memory. pub fn fits(&self, declared: Option) -> bool { self.reservation(declared) <= self.free } } -/// Picks which of the label-compatible queued jobs, oldest first, a runner with `offer` takes. -/// Each candidate is `(declared memory, seconds waited)`. Returns the index of the first job that -/// fits. A job that does not fit is skipped so smaller jobs behind it can run, but only while it -/// has waited less than `starve_after` seconds. Once an unfit job has waited that long, nothing -/// behind it is handed out: the runner drains its running jobs until the old job fits. pub fn pick_by_memory( candidates: &[(Option, u64)], offer: &MemoryOffer, @@ -469,24 +412,14 @@ pub fn pick_by_memory( None } -/// Why the queued jobs were not handed to one runner's claim. Counts only: nothing is claimed. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct QueueSkips { - /// Queued jobs in all. pub queued: usize, - /// Queued jobs whose `runs_on` names a label the runner lacks. pub lacking_labels: usize, - /// The labels those jobs name that the runner lacks. Sorted, without repeats. pub missing_labels: Vec, - /// Jobs the runner has the labels for but not the free memory. Only counted when the runner - /// offered its memory. pub too_big: usize, - /// The smallest reservation among the `too_big` jobs, in bytes. pub smallest_need: Option, - /// Jobs that fit but wait behind an older one that has starved (see [`pick_by_memory`]): the - /// runner takes nothing until that one fits. pub held_behind: usize, - /// What the starved job reserves, in bytes, when one holds the queue. pub starved_need: Option, } @@ -494,23 +427,19 @@ fn size_in_range(raw: &str, lo: u64, hi: u64) -> bool { forge_ci::size::parse_size(raw).is_some_and(|n| (lo..=hi).contains(&n)) } -/// The capability of a runner that restarts when the forge asks. pub const CAP_RESTART: &str = "restart"; impl CiRunner { - /// True when the runner advertises that it honours a restart request. pub fn supports_restart(&self) -> bool { self.reported.capabilities.iter().any(|c| c == CAP_RESTART) } } -/// One run of the workflow for a commit. #[derive(Debug, Clone, PartialEq, Eq)] pub struct CiRun { pub id: String, pub repo_id: String, pub number: i64, - /// `push`, `tag`, `pull_request` or `manual`. pub trigger: String, pub git_ref: String, pub commit_oid: String, @@ -522,7 +451,6 @@ pub struct CiRun { pub finished_at: Option, } -/// One job of a run. `spec_json` is the JobSpec as JSON text. #[derive(Debug, Clone, PartialEq, Eq)] pub struct CiJob { pub id: String, @@ -539,40 +467,28 @@ pub struct CiJob { pub heartbeat_at: Option, pub cancel_requested: bool, pub log_bytes: i64, - /// Processes the OOM killer took in the job's cgroup, as its runner reported. `None` when the - /// runner did not say (an older runner) or nothing was killed. pub oom_kills: Option, } -/// One job's duration in a recent successful run of a repo, for the CI time estimate. Only the -/// newest five successful runs per branch and per repo are sampled, so the ranks are 1 for the newest. #[derive(Debug, Clone, PartialEq, Eq)] pub struct JobSample { pub git_ref: String, - /// The run's place among the repo's successful runs on its branch, newest first. pub branch_rank: i64, - /// The run's place among the repo's successful runs on any branch, newest first. pub repo_rank: i64, pub job: String, - /// The job's duration in seconds. pub secs: i64, } -/// A step of a job: a top-level `::group::` section of its log (migration 0071). #[derive(Debug, Clone, PartialEq, Eq)] pub struct JobStep { pub job_id: String, - /// The step's place in its job, from 0. pub seq: i64, pub name: String, pub started_at: String, - /// Set when the group closed. Unset while it is open. pub finished_at: Option, - /// Byte position of the group's line in the job's log. pub log_offset: i64, } -/// What a step shows: its own state, or the job's once the job ended without closing it. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum StepState { Running, @@ -582,7 +498,6 @@ pub enum StepState { } impl JobStep { - /// A closed step passed. An open one follows its job: a job that succeeded passed it too. pub fn state(&self, job: JobState) -> StepState { if self.finished_at.is_some() { return StepState::Passed; @@ -596,36 +511,24 @@ impl JobStep { } } -/// One step's duration in a recent successful run of a repo, for the CI time estimate. Sampled like -/// `JobSample`. #[derive(Debug, Clone, PartialEq, Eq)] pub struct StepSample { pub git_ref: String, - /// The run's place among the repo's successful runs on its branch, newest first. pub branch_rank: i64, - /// The run's place among the repo's successful runs on any branch, newest first. pub repo_rank: i64, pub job: String, pub step: String, - /// The step's duration in seconds. pub secs: i64, } -/// A job of one runner, with the run and repo it belongs to, for the runner's admin page. The -/// run's page is `/{owner}/{repo}/ci/runs/{run_number}`. #[derive(Debug, Clone, PartialEq, Eq)] pub struct RunnerJob { - /// The job itself. pub job: CiJob, - /// The number of the job's run, within its repo. pub run_number: i64, - /// The username of the repo's owner. pub owner: String, - /// The repo's name. pub repo: String, } -/// An artifact uploaded by a job. The file itself is stored outside the database. #[derive(Debug, Clone, PartialEq, Eq)] pub struct CiArtifact { pub id: String, @@ -636,7 +539,6 @@ pub struct CiArtifact { pub created_at: String, } -/// A job to create with a run. `needs` must match the `needs` in `spec_json`. #[derive(Debug, Clone, Copy)] pub struct NewJob<'a> { pub name: &'a str, diff --git a/crates/forge-core/src/config.rs b/crates/forge-core/src/config.rs index 8e690c7..16e3b2e 100644 --- a/crates/forge-core/src/config.rs +++ b/crates/forge-core/src/config.rs @@ -1,5 +1,3 @@ -//! Instance configuration, read from TOML. - use std::net::{IpAddr, SocketAddr}; use std::path::{Path, PathBuf}; @@ -16,7 +14,6 @@ pub enum Registration { Open, } -/// Parses each entry as a CIDR network or as a single address (a /32 or /128). fn deserialize_trusted_proxies<'de, D: Deserializer<'de>>( deserializer: D, ) -> std::result::Result, D::Error> { @@ -45,14 +42,11 @@ fn default_user_content_listen() -> SocketAddr { .expect("valid default socket address") } -/// Outbound webhook delivery policy. Internal destinations are refused unless listed in `allowed_hosts`. #[derive(Debug, Clone, Default, Deserialize)] #[serde(deny_unknown_fields)] pub struct WebhookConfig { - /// Permit `http://` hook URLs in addition to `https://`. #[serde(default)] pub allow_http: bool, - /// Exact hostnames or CIDR networks that may be reached even when they resolve to internal addresses. #[serde(default)] pub allowed_hosts: Vec, } @@ -65,70 +59,49 @@ pub struct Config { pub listen: SocketAddr, pub base_url: String, pub user_content_base_url: String, - /// Listener that serves raw user files on the separate user-content origin. #[serde(default = "default_user_content_listen")] pub user_content_listen: SocketAddr, pub ssh_listen: SocketAddr, pub ssh_public_host: String, pub ssh_public_port: u16, - /// Seconds a failed SSH authentication waits before it is answered (brute-force damping). - /// Every SSH connection's first `none` probe fails, so this is paid per connection. #[serde(default = "default_ssh_auth_rejection_secs")] pub ssh_auth_rejection_secs: u64, pub registration: Registration, - /// Peers whose `X-Forwarded-For` header is trusted, such as the reverse proxy in front of forge. - /// Entries are addresses or CIDR networks. Empty by default, so the TCP peer is the client. #[serde(default, deserialize_with = "deserialize_trusted_proxies")] pub trusted_proxies: Vec, - /// Outbound webhook policy, from the `[webhooks]` section. #[serde(default)] pub webhooks: WebhookConfig, - /// Scheduled backups and fsck, from the `[backup]` section. An empty `dir` disables both. #[serde(default)] pub backup: BackupConfig, - /// Release asset limits, from the `[releases]` section. #[serde(default)] pub releases: ReleasesConfig, - /// Where release assets and CI artifacts are stored, from the `[storage]` section. #[serde(default)] pub storage: StorageConfig, - /// Standby replication, from the `[replication]` section. An empty `target` disables it. #[serde(default)] pub replication: ReplicationConfig, - /// Git LFS limits, from the `[lfs]` section. #[serde(default)] pub lfs: LfsConfig, - /// CI limits and retention, from the `[ci]` section. #[serde(default)] pub ci: CiConfig, - /// Security advisories (opt-in), from the `[advisories]` section. #[serde(default)] pub advisories: AdvisoriesConfig, - /// Outgoing mail transport, from the `[mail]` section. The SMTP account is set in the database. #[serde(default)] pub mail: MailConfig, - /// Organization rules, from the `[orgs]` section. #[serde(default)] pub orgs: OrgsConfig, - /// Self-update after a green CI run of the forge's own repo, from the `[self_update]` section. #[serde(default)] pub self_update: SelfUpdateConfig, - /// Site announcement shown under every page header, from the `[banner]` section. #[serde(default)] pub banner: BannerConfig, - /// Alerts to site admins, from the `[alerts]` section. #[serde(default)] pub alerts: AlertsConfig, - /// Mirror sync timing, from the `[mirrors]` section. #[serde(default)] pub mirrors: MirrorsConfig, } -/// Mirror sync timing. The default is what production runs with; the e2e tests shorten it. #[derive(Debug, Clone, Deserialize)] #[serde(deny_unknown_fields, default)] pub struct MirrorsConfig { - /// Seconds a push mirror waits after the last ref update before it is sent. pub push_debounce_secs: u64, } @@ -140,21 +113,14 @@ impl Default for MirrorsConfig { } } -/// Admin alerts: what the forge tells the site admins about before something breaks. #[derive(Debug, Clone, Deserialize)] #[serde(deny_unknown_fields, default)] pub struct AlertsConfig { - /// Master switch. Off sends nothing and raises nothing. pub enabled: bool, - /// Also email the admins, when they have a verified address and mail is set up. pub email: bool, - /// Minutes without a heartbeat before a runner counts as offline. pub runner_offline_minutes: u64, - /// Alert when the data directory has less than this percent free. pub disk_free_percent: u64, - /// Alert when the data directory has less than this many GiB free. 0 turns this check off. pub disk_free_gib: u64, - /// Per-kind switches. pub on_runner_offline: bool, pub on_backup: bool, pub on_disk: bool, @@ -182,7 +148,6 @@ impl Default for AlertsConfig { } impl AlertsConfig { - /// Whether alerts of `kind` are raised: the master switch and the kind's own switch. pub fn kind_enabled(&self, kind: crate::alerts::AlertKind) -> bool { use crate::alerts::AlertKind as K; self.enabled @@ -197,15 +162,11 @@ impl AlertsConfig { } } -/// Site announcement banner. An empty `message` shows nothing. #[derive(Debug, Clone, Deserialize)] #[serde(deny_unknown_fields, default)] pub struct BannerConfig { - /// One line of text. Empty turns the banner off. pub message: String, - /// `info` or `warning`. pub level: String, - /// UTC time as `YYYY-MM-DD HH:MM` after which the banner disappears. Empty for never. pub expires: String, } @@ -220,18 +181,15 @@ impl Default for BannerConfig { } impl BannerConfig { - /// Unix seconds of `expires`, or `None` when unset or malformed. pub fn expires_unix(&self) -> Option { parse_banner_expiry(&self.expires) } - /// Whether the banner shows at `now` (unix seconds). pub fn active_at(&self, now: i64) -> bool { !self.message.trim().is_empty() && self.expires_unix().is_none_or(|t| now < t) } } -/// Parses `YYYY-MM-DD HH:MM` (UTC) into unix seconds. pub fn parse_banner_expiry(raw: &str) -> Option { let dt = jiff::civil::DateTime::strptime("%Y-%m-%d %H:%M", raw.trim()).ok()?; if dt.year() < 1970 { @@ -241,22 +199,13 @@ pub fn parse_banner_expiry(raw: &str) -> Option { Some(zoned.timestamp().as_second()) } -/// Self-update, from the `[self_update]` section. When enabled, a successful push run of `repo` -/// on `branch` replaces the running binary with the `artifact` of `job` and restarts. #[derive(Debug, Clone, Deserialize)] #[serde(deny_unknown_fields, default)] pub struct SelfUpdateConfig { - /// Whether a green run deploys its artifact. Off by default. pub enabled: bool, - /// The repo whose runs deploy, as `owner/name`. pub repo: String, - /// The branch whose push runs deploy. pub branch: String, - /// The CI job that produces the artifact. pub job: String, - /// The artifact name produced by `job`. A single file. `{target}` is replaced with the - /// server's own `-` target (e.g. `x86_64-linux`), so the same setting works on any - /// arch. pub artifact: String, } @@ -298,16 +247,12 @@ impl SelfUpdateConfig { } } -/// Organization rules, from the `[orgs]` section. #[derive(Debug, Clone, Default, Deserialize)] #[serde(deny_unknown_fields, default)] pub struct OrgsConfig { - /// Who may create an organization: `all` (any signed-in person, the default) or `admin` - /// (instance admins only). pub creation: OrgCreation, } -/// Who may create organizations. See `OrgsConfig::creation`. #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)] #[serde(rename_all = "lowercase")] pub enum OrgCreation { @@ -316,16 +261,12 @@ pub enum OrgCreation { Admin, } -/// Outgoing mail transport, from the `[mail]` section. The SMTP server, sender and password are -/// set on `/admin/mail` and stored in the database; this section only picks the transport. #[derive(Debug, Clone, Default, Deserialize)] #[serde(deny_unknown_fields, default)] pub struct MailConfig { pub transport: MailTransport, } -/// `smtp` sends through the configured server. `log` writes each message to `/mail-log/` -/// instead, for development and tests. #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)] #[serde(rename_all = "lowercase")] pub enum MailTransport { @@ -334,33 +275,19 @@ pub enum MailTransport { Log, } -/// CI settings, from the `[ci]` section. #[derive(Debug, Clone, Deserialize)] #[serde(deny_unknown_fields, default)] pub struct CiConfig { - /// Whether CI runs at all. When false, pushes and pull requests create no runs. pub enabled: bool, - /// Largest job log, in MiB. Past it the log is truncated. pub max_log_mb: u64, - /// Largest artifact, in MiB. pub max_artifact_mb: u64, - /// Artifacts a single job may upload. pub max_artifacts_per_job: u32, - /// Largest total size of one job's artifacts, in MiB. pub max_job_artifacts_mb: u64, - /// Days a job log is kept. pub log_retention_days: u64, - /// Days an artifact is kept. pub artifact_retention_days: u64, - /// Artifacts of the newest this-many runs per repo (that have artifacts) are kept; older runs - /// lose theirs. 0 keeps all. pub artifact_keep_runs: u32, - /// Largest total size of all CI artifacts, in MiB. Past it, the oldest runs' artifacts are - /// deleted whole until the total fits. 0 is no limit. pub artifact_max_total_mb: u64, - /// Hours a runner registration token stays valid. pub registration_token_hours: u32, - /// Milliseconds a runner claim waits for work before it is answered with no job. pub claim_wait_ms: u64, } @@ -382,16 +309,11 @@ impl Default for CiConfig { } } -/// Security advisories, from the `[advisories]` section. Off by default: when on, the forge -/// downloads the OSV dumps for `ecosystems` and scans each repo's lockfiles. #[derive(Debug, Clone, Deserialize)] #[serde(deny_unknown_fields, default)] pub struct AdvisoriesConfig { - /// Whether the advisory download and the lockfile scans run at all. pub enabled: bool, - /// OSV ecosystems to download and scan: any of `crates.io`, `npm`, `Go`. pub ecosystems: Vec, - /// Hours before a downloaded dump is fetched again. pub refresh_hours: u64, } @@ -420,11 +342,9 @@ impl AdvisoriesConfig { } } -/// Git LFS limits, from the `[lfs]` section. #[derive(Debug, Clone, Deserialize)] #[serde(deny_unknown_fields, default)] pub struct LfsConfig { - /// Largest accepted LFS object, in MiB. pub max_object_mb: u64, } @@ -437,29 +357,20 @@ impl Default for LfsConfig { } impl LfsConfig { - /// The object size limit in bytes. pub fn max_object_bytes(&self) -> u64 { self.max_object_mb.saturating_mul(1024 * 1024) } } -/// Standby replication, from the `[replication]` section. See `docs/backup.md`. #[derive(Debug, Clone, Deserialize)] #[serde(deny_unknown_fields, default)] pub struct ReplicationConfig { - /// `[user@]host:/absolute/base` of the standby account. Empty disables replication. pub target: String, - /// SSH port of the standby host. pub ssh_port: u16, - /// Private key of the standby account (mode 0600). Required when `target` is set. pub identity_file: PathBuf, - /// Pinned host keys of the standby. Required when `target` is set; StrictHostKeyChecking is always `yes`. pub known_hosts_file: PathBuf, - /// Minutes between database snapshots shipped to the standby. pub db_snapshot_minutes: u64, - /// Minutes between reconcile passes (refs checksums, deleted repos, healthcheck). pub reconcile_minutes: u64, - /// Optional URL pinged after each reconcile pass. Empty disables it. pub healthcheck_url: String, } @@ -478,7 +389,6 @@ impl Default for ReplicationConfig { } impl ReplicationConfig { - /// Whether the replication worker runs at all. pub fn enabled(&self) -> bool { !self.target.is_empty() } @@ -511,11 +421,9 @@ impl ReplicationConfig { } } -/// Release settings, from the `[releases]` section. #[derive(Debug, Clone, Deserialize)] #[serde(deny_unknown_fields, default)] pub struct ReleasesConfig { - /// Largest accepted release asset, in mebibytes. pub max_asset_mb: u64, } @@ -525,77 +433,48 @@ impl Default for ReleasesConfig { } } -/// Blob storage for release assets and CI artifacts, from the `[storage]` section. See -/// `docs/backup.md`. The default keeps blobs on the local disk under `/blobs`. #[derive(Debug, Clone, Default, Deserialize)] #[serde(deny_unknown_fields, default)] pub struct StorageConfig { - /// `fs` (local disk, the default) or `s3` (any S3-compatible object store). pub backend: StorageBackend, - /// Settings for `backend = "s3"`, from the `[storage.s3]` table. Ignored for `fs` and `r2`. pub s3: S3Config, - /// Settings for `backend = "r2"`, from the `[storage.r2]` table. Ignored for `fs` and `s3`. pub r2: R2Config, } -/// Blob backend. See `StorageConfig::backend`. #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)] #[serde(rename_all = "lowercase")] pub enum StorageBackend { #[default] Fs, S3, - /// Cloudflare R2, configured by account rather than by endpoint. See `R2Config`. R2, } -/// S3-compatible object store settings, from the `[storage.s3]` table. Works with AWS S3, MinIO, -/// Garage, Cloudflare R2 and similar. The secret is read from a file, so it stays out of this config. #[derive(Debug, Clone, Default, Deserialize)] #[serde(deny_unknown_fields, default)] pub struct S3Config { - /// Bucket that holds the blobs. Required. pub bucket: String, - /// Signing region, such as `eu-central-1`, or `auto` for R2. Required. pub region: String, - /// Full URL of a non-AWS endpoint, such as `https://s3.example.internal:9000`. Empty uses AWS. pub endpoint: String, - /// Key prefix inside the bucket, such as `forge/`. Empty stores keys at the bucket root. pub prefix: String, - /// Access key id. Required. pub access_key_id: String, - /// File holding the secret access key (mode 0600). Its contents are trimmed. Required. pub secret_access_key_file: PathBuf, - /// Permit an `http://` endpoint. Only for a store on a trusted private network. pub allow_http: bool, - /// Address buckets as subdomains (`bucket.host`) instead of paths (`host/bucket`). Path style is - /// the default because MinIO, Garage and most self-hosted stores expect it. pub virtual_hosted_style: bool, } -/// Cloudflare R2 settings, from the `[storage.r2]` table. The endpoint is derived from the account -/// id and jurisdiction, so the S3 wire details never appear in the config. The secret is read from -/// a file, as for `S3Config`. #[derive(Debug, Clone, Default, Deserialize)] #[serde(deny_unknown_fields, default)] pub struct R2Config { - /// Cloudflare account id, the 32-character hex string from the dashboard. Required. pub account_id: String, - /// Bucket that holds the blobs. Required. pub bucket: String, - /// `""` (the default, global), `"eu"`, or `"fedramp"`. Must match the jurisdiction the bucket - /// was created in, or requests fail. pub jurisdiction: String, - /// Key prefix inside the bucket, such as `forge/`. Empty stores keys at the bucket root. pub prefix: String, - /// Access key id of an R2 API token with object read and write. Required. pub access_key_id: String, - /// File holding the secret access key (mode 0600). Its contents are trimmed. Required. pub secret_access_key_file: PathBuf, } impl R2Config { - /// The S3 API endpoint for this account and jurisdiction. Path-style, https only. pub fn endpoint(&self) -> String { match self.jurisdiction.as_str() { "" => format!("https://{}.r2.cloudflarestorage.com", self.account_id), @@ -607,7 +486,6 @@ impl R2Config { } } -/// Fails unless `value` is non-empty after trimming. `section` names the table in the message. fn require(section: &str, field: &str, value: &str) -> Result<()> { if value.trim().is_empty() { return Err(Error::Config(format!( @@ -618,7 +496,6 @@ fn require(section: &str, field: &str, value: &str) -> Result<()> { Ok(()) } -/// Checks that the secret file named by `[section]` exists and is a file. fn check_secret_file(section: &str, path: &Path) -> Result<()> { if path.as_os_str().is_empty() { return Err(Error::Config(format!( @@ -668,7 +545,6 @@ impl StorageConfig { fn validate_r2(&self) -> Result<()> { let r2 = &self.r2; require("storage.r2", "account_id", &r2.account_id)?; - // The account id becomes part of the host name, so only hex digits are allowed. if !r2.account_id.chars().all(|c| c.is_ascii_hexdigit()) { return Err(Error::Config( "[storage.r2] account_id must contain only hex digits (copy it from the Cloudflare dashboard)".into(), @@ -687,19 +563,13 @@ impl StorageConfig { } } -/// Scheduled backups, from the `[backup]` section. See `docs/backup.md`. #[derive(Debug, Clone, Deserialize)] #[serde(deny_unknown_fields, default)] pub struct BackupConfig { - /// Directory that receives the backup sets. Empty disables the scheduler. pub dir: PathBuf, - /// Hours between full backup sets. pub interval_hours: u64, - /// Newest complete sets kept in `dir`. Older complete sets are deleted after a good run. pub keep: usize, - /// Optional healthchecks.io style URL. Pinged with `/start`, then the URL itself or `/fail`. pub healthcheck_url: String, - /// Days between `git fsck` and integrity checks of every repo and the database. pub fsck_interval_days: u64, } @@ -716,7 +586,6 @@ impl Default for BackupConfig { } impl BackupConfig { - /// Whether the scheduler runs at all. pub fn enabled(&self) -> bool { !self.dir.as_os_str().is_empty() } @@ -739,7 +608,6 @@ impl BackupConfig { } } -/// Development defaults, written when the config file is missing. Keep in sync with `config/forge.example.toml`. const DEV_DEFAULTS: &str = r#"# forge configuration (development defaults). Production values belong in /etc/forge/forge.toml. # SQLite/Turso database file. @@ -766,13 +634,10 @@ trusted_proxies = [] "#; impl Config { - /// Loads the config from `path`. Writes development defaults if the file is missing. pub fn load(path: &Path) -> Result { Self::load_with_keys(path).map(|(config, _)| config) } - /// Like `load`, and also returns the dotted keys the file sets (such as `ci.max_log_mb`), so the - /// settings page can tell a file value from a default. pub fn load_with_keys(path: &Path) -> Result<(Config, std::collections::BTreeSet)> { let text = match std::fs::read_to_string(path) { Ok(text) => text, @@ -795,8 +660,6 @@ impl Config { Ok((config, keys)) } - /// The cross-field rules the loader applies after parsing. The settings page runs the same - /// check before it stores an override. pub fn validate(&self) -> Result<()> { self.backup.validate()?; self.replication.validate()?; @@ -807,7 +670,6 @@ impl Config { } } -/// Collects the dotted path of every non-table value in `table`. fn flatten_keys(prefix: &str, table: &toml::Table, out: &mut std::collections::BTreeSet) { for (key, value) in table { let path = if prefix.is_empty() { @@ -840,7 +702,6 @@ mod tests { assert_eq!(cfg.ssh_listen, "0.0.0.0:2222".parse().unwrap()); assert_eq!(cfg.ssh_public_port, 2222); assert_eq!(cfg.registration, Registration::Closed); - // Reloading the written file gives the same config. let again = Config::load(&path).unwrap(); assert_eq!(again.base_url, cfg.base_url); } @@ -957,13 +818,11 @@ mod tests { let path = dir.path().join("forge.toml"); std::fs::write(&path, DEV_DEFAULTS).unwrap(); let cfg = Config::load(&path).unwrap(); - // backup assert!(!cfg.backup.enabled(), "backup enabled"); assert_eq!(cfg.backup.interval_hours, 24, "backup interval"); assert_eq!(cfg.backup.keep, 7, "backup keep"); assert_eq!(cfg.backup.fsck_interval_days, 7, "backup fsck"); assert!(cfg.backup.healthcheck_url.is_empty(), "backup healthcheck"); - // replication assert!(!cfg.replication.enabled(), "replication enabled"); assert_eq!(cfg.replication.ssh_port, 22, "replication ssh port"); assert_eq!( @@ -978,7 +837,6 @@ mod tests { cfg.replication.healthcheck_url.is_empty(), "replication healthcheck" ); - // self_update assert!(!cfg.self_update.enabled, "self_update enabled"); assert_eq!(cfg.self_update.branch, "main", "self_update branch"); assert_eq!(cfg.self_update.job, "build", "self_update job"); @@ -986,7 +844,6 @@ mod tests { cfg.self_update.artifact, "forge-{target}", "self_update artifact" ); - // storage assert_eq!(cfg.storage.backend, StorageBackend::Fs, "storage backend"); assert!(cfg.storage.s3.bucket.is_empty(), "s3 bucket"); assert!(!cfg.storage.s3.allow_http, "s3 allow_http"); @@ -1129,7 +986,6 @@ mod tests { assert!(Config::load(&path).is_ok()); } - /// A complete `[storage.r2]` table with a real secret file, minus any lines the caller drops. fn r2_config_text(dir: &Path, drop: &[&str], extra: &str) -> String { let secret = dir.join("r2-secret"); std::fs::write(&secret, "r2s3cret\n").unwrap(); @@ -1186,7 +1042,6 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("forge.toml"); let absent = dir.path().join("absent").display().to_string(); - // (label, lines to drop from the complete table, extra lines, expected to load) let cases: Vec<(&str, &[&str], String, bool)> = vec![ ("complete", &[], String::new(), true), ("account_id missing", &["account_id"], String::new(), false), diff --git a/crates/forge-core/src/discussions.rs b/crates/forge-core/src/discussions.rs index a234e85..a42c68b 100644 --- a/crates/forge-core/src/discussions.rs +++ b/crates/forge-core/src/discussions.rs @@ -1,19 +1,13 @@ -//! Discussion types: a per-repo forum next to issues. Storage lives in `store/discussions.rs`. -//! Titles and bodies are checked with the issue validators, since the limits are the same. - use crate::error::{Error, Result}; -/// Categories a discussion can be filed under. The `as_str` names are stored. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum DiscussionCategory { General, Ideas, Qa, - /// Only Maintain or higher may post here. Announcements, } -/// Every category, in the order the chooser shows them. pub const DISCUSSION_CATEGORIES: &[DiscussionCategory] = &[ DiscussionCategory::General, DiscussionCategory::Ideas, @@ -22,7 +16,6 @@ pub const DISCUSSION_CATEGORIES: &[DiscussionCategory] = &[ ]; impl DiscussionCategory { - /// The stored and URL name. pub fn as_str(self) -> &'static str { match self { DiscussionCategory::General => "general", @@ -32,7 +25,6 @@ impl DiscussionCategory { } } - /// The label people read. pub fn label(self) -> &'static str { match self { DiscussionCategory::General => "General", @@ -42,7 +34,6 @@ impl DiscussionCategory { } } - /// The category with this stored name, if any. pub fn parse(name: &str) -> Option { DISCUSSION_CATEGORIES .iter() @@ -51,7 +42,6 @@ impl DiscussionCategory { } } -/// One discussion. `answer_comment_id` is set only in Q&A, and names the accepted reply. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Discussion { pub id: String, @@ -68,24 +58,19 @@ pub struct Discussion { pub updated_at: String, } -/// A discussion with its author's username, for the list. #[derive(Debug, Clone, PartialEq, Eq)] pub struct DiscussionListItem { pub discussion: Discussion, pub author: String, } -/// Why a discussion is in a user's inbox. The `as_str` names are stored in `discussion_notifications`. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum DiscussionReason { - /// The user was @mentioned in the discussion or one of its comments. Mention, - /// Someone commented on the user's discussion. Reply, } impl DiscussionReason { - /// The stored name. pub fn as_str(self) -> &'static str { match self { DiscussionReason::Mention => "mention", @@ -93,7 +78,6 @@ impl DiscussionReason { } } - /// The reason with this stored name, if any. pub fn parse(name: &str) -> Option { match name { "mention" => Some(DiscussionReason::Mention), @@ -103,7 +87,6 @@ impl DiscussionReason { } } -/// One inbox row for a discussion, joined with its repo and title for the notifications page. #[derive(Debug, Clone, PartialEq, Eq)] pub struct DiscussionNotification { pub discussion_id: String, @@ -113,14 +96,11 @@ pub struct DiscussionNotification { pub number: i64, pub title: String, pub reason: DiscussionReason, - /// Username of the last person who acted, if the account still exists. pub last_actor_name: Option, pub unread: bool, pub updated_at: String, } -/// One comment. A top-level comment has no `parent_id`; a reply names a top-level comment of the -/// same discussion. A deleted comment has `deleted` set and an empty body. #[derive(Debug, Clone, PartialEq, Eq)] pub struct DiscussionComment { pub id: String, @@ -133,7 +113,6 @@ pub struct DiscussionComment { pub deleted: bool, } -/// Filters and paging for the discussion list. `category: None` lists every category. #[derive(Debug, Clone, PartialEq, Eq)] pub struct DiscussionFilter { pub category: Option, @@ -141,14 +120,12 @@ pub struct DiscussionFilter { pub per_page: u32, } -/// Validates a discussion title (trimmed, returned) and body. pub fn validate_discussion(title: &str, body: &str) -> Result { let title = crate::issues::validate_title(title)?; crate::issues::validate_body(body)?; Ok(title) } -/// Validates a comment body: not blank, and within the body limit. pub fn validate_comment(body: &str) -> Result<()> { crate::issues::validate_body(body)?; if body.trim().is_empty() { diff --git a/crates/forge-core/src/error.rs b/crates/forge-core/src/error.rs index 63dfca0..cf488dc 100644 --- a/crates/forge-core/src/error.rs +++ b/crates/forge-core/src/error.rs @@ -1,5 +1,3 @@ -//! The error type shared across forge crates. - #[derive(Debug, thiserror::Error)] pub enum Error { #[error("io error: {0}")] diff --git a/crates/forge-core/src/issue_refs.rs b/crates/forge-core/src/issue_refs.rs index 108b3cc..50c7162 100644 --- a/crates/forge-core/src/issue_refs.rs +++ b/crates/forge-core/src/issue_refs.rs @@ -1,30 +1,15 @@ -//! Parsing of issue references (`#12`) and closing keywords (`fixes #12`) in free text. -//! Hand-written scanner, no regex. Pure, no IO. - use std::ops::Range; -/// Keywords that close an issue when followed by a `#N` reference. Compared case-insensitively. const CLOSING_KEYWORDS: [&str; 9] = [ "close", "closes", "closed", "fix", "fixes", "fixed", "resolve", "resolves", "resolved", ]; -/// Maximum number of digits in an issue number. const MAX_DIGITS: usize = 9; -/// Every `#N` reference in `text`, deduplicated, in order of first appearance. -/// -/// A reference is `#` followed by 1 to 9 digits. It is not recognised when the `#` is preceded by -/// an alphanumeric char, `&` or `/`, or when the digits are followed by an alphanumeric char. -/// `#0` is not an issue number and is ignored. pub fn find_issue_refs(text: &str) -> Vec { dedup(issue_ref_spans(text).into_iter().map(|(_, n)| n)) } -/// Issue numbers closed by closing keywords in `text`, deduplicated, in order. -/// -/// The keyword (case-insensitive, whole word) must directly precede the reference, optionally -/// separated by a `:`, with at least one whitespace char between the keyword (or colon) and `#`. -/// Example: `"Fixes: #3, closes #4"` gives `[3, 4]`; `"unfixes #2"` gives nothing. pub fn find_closing_refs(text: &str) -> Vec { dedup( issue_ref_spans(text) @@ -44,8 +29,6 @@ fn dedup(values: impl Iterator) -> Vec { out } -/// Byte range (including the `#`) and value of every valid `#N` reference in `text`, in order. -/// Duplicates are kept. Used to link references in rendered markdown with the same rules. pub fn issue_ref_spans(text: &str) -> Vec<(Range, i64)> { let bytes = text.as_bytes(); let mut refs = Vec::new(); @@ -86,12 +69,9 @@ pub fn issue_ref_spans(text: &str) -> Vec<(Range, i64)> { refs } -/// True when `before` (the text preceding a `#N` reference) ends with a closing keyword, -/// an optional `:`, and at least one whitespace char. fn preceded_by_closing_keyword(before: &str) -> bool { let trimmed = before.trim_end(); if trimmed.len() == before.len() { - // No whitespace between the keyword and the reference. return false; } let word_part = trimmed.strip_suffix(':').unwrap_or(trimmed); diff --git a/crates/forge-core/src/issues.rs b/crates/forge-core/src/issues.rs index c330af3..24ebbe0 100644 --- a/crates/forge-core/src/issues.rs +++ b/crates/forge-core/src/issues.rs @@ -1,18 +1,10 @@ -//! Issue, comment, label and milestone types, and their validation. Stored shapes are in -//! migrations/0004_issues.sql; the store functions live in store/issues.rs and store/labels.rs. - use crate::error::{Error, Result}; use crate::model::Id; -/// Longest accepted issue title, in characters. pub const MAX_TITLE: usize = 256; -/// Largest accepted issue, comment or edit body, in bytes. pub const MAX_BODY: usize = 65536; -/// Longest accepted label name, in characters. pub const MAX_LABEL_NAME: usize = 50; -/// Longest label description, in characters. pub const MAX_LABEL_DESCRIPTION: usize = 500; -/// Most assignees one issue can have. pub const MAX_ASSIGNEES: usize = 10; #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -84,13 +76,10 @@ pub struct Issue { pub created_at: String, pub updated_at: String, pub closed_at: Option, - /// Locked conversations accept writes only from collaborators with Triage or higher. pub locked: bool, - /// One of `LOCK_REASONS`, or `None` when no reason was given. pub lock_reason: Option, } -/// Reasons accepted when locking a conversation. pub const LOCK_REASONS: &[&str] = &["off_topic", "too_heated", "resolved", "spam"]; #[derive(Debug, Clone, PartialEq)] @@ -108,7 +97,6 @@ pub struct Comment { pub struct IssueEvent { pub id: Id, pub issue_id: Id, - /// `None` for system events. pub actor_id: Option, pub kind: String, pub data: serde_json::Value, @@ -120,7 +108,6 @@ pub struct Label { pub id: Id, pub repo_id: Id, pub name: String, - /// Lowercase `#rrggbb`. pub color: String, pub description: String, } @@ -131,12 +118,10 @@ pub struct Milestone { pub repo_id: Id, pub title: String, pub description: String, - /// `YYYY-MM-DD` or `None`. pub due_on: Option, pub state: IssueState, pub created_at: String, pub closed_at: Option, - /// Counts filled by list/get queries. pub open_issues: i64, pub closed_issues: i64, } @@ -144,22 +129,14 @@ pub struct Milestone { #[derive(Debug, Clone, PartialEq)] pub struct IssueFilter { pub state: Option, - /// Label name. pub label: Option, - /// Milestone title. pub milestone: Option, - /// Author username. pub author: Option, - /// Assignee username. pub assignee: Option, - /// Username with a pending review request (pull requests only). pub review_requested: Option, - /// Substring of the title, case-insensitive. pub query: Option, - /// Pull requests only: `Some(true)` lists drafts, `Some(false)` lists ready pull requests. pub draft: Option, pub sort: IssueSort, - /// 1-based. pub page: u32, pub per_page: u32, } @@ -191,7 +168,6 @@ pub enum IssueSort { } impl IssueSort { - /// The value used in the `sort` query parameter. pub fn as_str(&self) -> &'static str { match self { IssueSort::Newest => "newest", @@ -217,14 +193,11 @@ impl std::str::FromStr for IssueSort { #[derive(Debug, Clone, PartialEq)] pub struct IssueListItem { pub issue: Issue, - /// Display username of the author. pub author: String, pub labels: Vec