Skip to content

Enforce cancellation token usage - #15

Merged
PANiXiDA merged 2 commits into
developmentfrom
feature/cancellation-token-convention
Aug 1, 2026
Merged

Enforce cancellation token usage#15
PANiXiDA merged 2 commits into
developmentfrom
feature/cancellation-token-convention

Conversation

@PANiXiDA

@PANiXiDA PANiXiDA commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

Что изменено

Добавлены четыре глобальные Roslyn-проверки:

  • в авторских C#-исходниках из src, tests и tools запрещены CancellationToken.None, default(CancellationToken) и default с целевым типом CancellationToken, включая optional-параметры;
  • объявленный параметр CancellationToken должен использоваться, кроме сигнатур overrides и реализаций внешних интерфейсов;
  • если вызываемый метод принимает CancellationToken, а токен доступен в текущей области видимости, его необходимо передать явно;
  • если production-код из src вызывает отменяемую операцию без токена и токен ещё недоступен, текущий метод должен получить CancellationToken параметром и прокинуть его от точки входа.

Общий source discovery расширен для анализа tests и tools. Два существовавших = default удалены из тестовой инфраструктуры, а xUnit fixtures передают TestContext.Current.CancellationToken в инициализацию базы и миграции.

Зачем

Чтобы отмена последовательно передавалась по цепочке Endpoint → Handler → Repository → DB, неиспользуемые токены не засоряли сигнатуры, а None/default не отключали отмену неявно.

Проверка не строит предположения по названию метода: необходимость токена определяется по выбранной сигнатуре вызываемой операции. Правило обязательного протягивания по всей иерархии ограничено production-кодом, чтобы optional-токены внутренних Roslyn/xUnit API не создавали ложные требования в самих архитектурных тестах.

Как проверить

dotnet build PANiXiDA.TacticalHeroes.slnx --no-restore
dotnet test tests/PANiXiDA.TacticalHeroes.ArchitectureTests/PANiXiDA.TacticalHeroes.ArchitectureTests.csproj --no-restore
dotnet format PANiXiDA.TacticalHeroes.slnx whitespace --verify-no-changes --no-restore

Совместимость

  • Миграций, изменений production-контрактов и конфигурации нет.
  • Breaking changes отсутствуют.
  • Для разработчиков новые нарушения соглашений будут останавливать архитектурные тесты.

@PANiXiDA
PANiXiDA marked this pull request as ready for review August 1, 2026 07:33
@PANiXiDA
PANiXiDA merged commit 3c43d03 into development Aug 1, 2026
7 checks passed
@PANiXiDA
PANiXiDA deleted the feature/cancellation-token-convention branch August 1, 2026 07:35

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: fa63676f7c

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +350 to +354
node is BaseMethodDeclarationSyntax or
LocalFunctionStatementSyntax or
ParenthesizedLambdaExpressionSyntax or
SimpleLambdaExpressionSyntax or
AnonymousMethodExpressionSyntax);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Analyze cancellation tokens in primary constructors

When a class uses a primary constructor such as sealed class Worker(CancellationToken cancellationToken) and never references that parameter, none of its ancestors match this callable list, so HasImplementation becomes false and the unused-token test silently skips it. Primary constructors are already common in this repository, so include type-declaration primary constructors in the callable/use analysis to enforce the convention consistently.

Useful? React with 👍 / 👎.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants