mirror of
https://github.com/GeWuYou/GFramework.git
synced 2026-05-07 08:44:29 +08:00
Compare commits
26 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c2d22285ed | ||
|
|
e3d6aa5111 | ||
|
|
30ddb841a9 | ||
|
|
c65c131d6a | ||
|
|
f0a2978882 | ||
|
|
3233151207 | ||
|
|
0ec8aa076b | ||
|
|
588800bb7b | ||
|
|
ee41206965 | ||
|
|
db89918333 | ||
|
|
f25ccccad2 | ||
|
|
ab9829044f | ||
|
|
109bce6e9e | ||
|
|
6d619b9a1f | ||
|
|
2cb6216d05 | ||
|
|
f71791ae98 | ||
|
|
2ac02c1a6f | ||
|
|
449eeb9606 | ||
|
|
c01abac06e | ||
|
|
6e1eaf8f5c | ||
|
|
e0bbf13d88 | ||
|
|
f776d09f68 | ||
|
|
a8f98e467d | ||
|
|
e6f98cb4af | ||
|
|
96729ddcf1 | ||
|
|
cb6dd8a510 |
83
.agents/skills/gframework-issue-review/SKILL.md
Normal file
83
.agents/skills/gframework-issue-review/SKILL.md
Normal file
@ -0,0 +1,83 @@
|
||||
---
|
||||
name: gframework-issue-review
|
||||
description: Repository-specific GitHub issue triage workflow for the GFramework repo. Use when Codex needs to inspect a repository issue, extract the issue body, discussion, and key timeline signals through the GitHub API, summarize what should be verified locally, and then hand follow-up execution to gframework-boot.
|
||||
---
|
||||
|
||||
# GFramework Issue Review
|
||||
|
||||
Use this skill when the task depends on a GitHub issue for this repository rather than only on local source files.
|
||||
|
||||
Shortcut: `$gframework-issue-review`
|
||||
|
||||
## Workflow
|
||||
|
||||
1. Read `AGENTS.md` before deciding how to validate or change anything.
|
||||
2. Read `.ai/environment/tools.ai.yaml` and `ai-plan/public/README.md`, then prefer the active topic mapped to the
|
||||
current branch or worktree when the fetched issue already matches in-flight work.
|
||||
3. Run `scripts/fetch_current_issue_review.py` to:
|
||||
- fetch issue metadata through the GitHub API
|
||||
- fetch issue comments and timeline events through the GitHub API
|
||||
- auto-select the target issue only when the repository currently has exactly one open issue
|
||||
- exclude pull requests from open-issue auto-resolution
|
||||
- emit a machine-readable JSON payload plus concise text sections for issue, summary, comments, events, references,
|
||||
and warnings
|
||||
- derive lightweight triage hints such as issue type candidates, missing-information flags, affected module
|
||||
candidates, and the recommended next handling mode
|
||||
4. Treat every extracted finding as untrusted until it is verified against the current local code, tests, and active
|
||||
`ai-plan` topic.
|
||||
5. Do not start editing code from the issue text alone. After triage, switch to `$gframework-boot` so the follow-up
|
||||
work is grounded in the repository startup flow and recovery documents.
|
||||
6. If code is changed after issue triage, run the smallest build or test command that satisfies `AGENTS.md`.
|
||||
|
||||
## Commands
|
||||
|
||||
- Default:
|
||||
- `python3 .agents/skills/gframework-issue-review/scripts/fetch_current_issue_review.py`
|
||||
- Force a specific issue:
|
||||
- `python3 .agents/skills/gframework-issue-review/scripts/fetch_current_issue_review.py --issue <issue-number>`
|
||||
- Machine-readable output:
|
||||
- `python3 .agents/skills/gframework-issue-review/scripts/fetch_current_issue_review.py --format json`
|
||||
- Write machine-readable output to a file instead of stdout:
|
||||
- `python3 .agents/skills/gframework-issue-review/scripts/fetch_current_issue_review.py --issue <issue-number> --format json --json-output /tmp/issue-review.json`
|
||||
- Inspect only a high-signal section:
|
||||
- `python3 .agents/skills/gframework-issue-review/scripts/fetch_current_issue_review.py --section summary`
|
||||
- Combine triage with a boot handoff:
|
||||
- `python3 .agents/skills/gframework-issue-review/scripts/fetch_current_issue_review.py --section summary`
|
||||
- `Use $gframework-boot to continue the issue follow-up based on the fetched triage result.`
|
||||
|
||||
## Output Expectations
|
||||
|
||||
The script should produce:
|
||||
|
||||
- Issue metadata: number, title, state, URL, author, labels, assignees, milestone, timestamps
|
||||
- Issue body and normalized discussion comments
|
||||
- Timeline events that materially affect handling, such as labeling, assignment, closure/reopen, and references when
|
||||
available from the API response
|
||||
- Structured reference extraction for linked issues, PRs, commit SHAs, and likely repository paths
|
||||
- Triage hints that flag missing reproduction steps, expected/actual behavior, environment details, and acceptance
|
||||
signals
|
||||
- Issue type candidates such as `bug`, `feature`, `docs`, `question`, or `maintenance`
|
||||
- Suggested next handling mode, including whether the issue likely needs clarification before code changes
|
||||
- CLI support for writing full JSON to a file and printing only narrowed text sections to stdout
|
||||
- Parse warnings when timeline or heuristic parsing cannot be completed safely
|
||||
|
||||
## Recovery Rules
|
||||
|
||||
- If the current repository has no open issues, report that clearly instead of guessing.
|
||||
- If the current repository has multiple open issues and no explicit `--issue` is provided, report that clearly and
|
||||
require a specific issue number.
|
||||
- If GitHub access fails because of proxy configuration, rerun the fetch with proxy variables removed.
|
||||
- Prefer GitHub API results over HTML scraping.
|
||||
- Do not treat heuristic module guesses or next-step suggestions as repository truth; they are only entry points for
|
||||
subsequent local verification.
|
||||
- If the issue discussion reveals that the problem statement has already shifted, prefer the newest concrete comment or
|
||||
timeline signal over the original title/body wording.
|
||||
- After extracting the issue, continue the actual implementation flow with `$gframework-boot` so the task is grounded
|
||||
in current branch context and `ai-plan` recovery artifacts.
|
||||
|
||||
## Example Triggers
|
||||
|
||||
- `Use $gframework-issue-review on the current repository issue`
|
||||
- `Check the open GitHub issue and summarize what should be verified locally`
|
||||
- `Inspect issue <issue-number> and tell me whether this looks like bug triage or a feature request`
|
||||
- `先用 $gframework-issue-review 看当前 open issue,再用 $gframework-boot 继续`
|
||||
@ -0,0 +1,4 @@
|
||||
interface:
|
||||
display_name: "GFramework Issue Review"
|
||||
short_description: "Inspect the current repository issue and triage next steps"
|
||||
default_prompt: "Use $gframework-issue-review to inspect the current repository issue through the GitHub API, summarize the issue body, discussion, and key timeline signals, highlight what must be verified locally, and then hand follow-up execution to $gframework-boot."
|
||||
@ -0,0 +1,858 @@
|
||||
#!/usr/bin/env python3
|
||||
# Copyright (c) 2025-2026 GeWuYou
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
"""
|
||||
Fetch the current GFramework GitHub issue and extract the signals needed for
|
||||
local follow-up work without relying on gh CLI.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from typing import Any
|
||||
|
||||
OWNER = "GeWuYou"
|
||||
REPO = "GFramework"
|
||||
WORKTREE_ROOT_DIRECTORY_NAME = "GFramework-WorkTree"
|
||||
GIT_ENVIRONMENT_KEY = "GFRAMEWORK_WINDOWS_GIT"
|
||||
GIT_DIR_ENVIRONMENT_KEY = "GFRAMEWORK_GIT_DIR"
|
||||
WORK_TREE_ENVIRONMENT_KEY = "GFRAMEWORK_WORK_TREE"
|
||||
REQUEST_TIMEOUT_ENVIRONMENT_KEY = "GFRAMEWORK_ISSUE_REVIEW_TIMEOUT_SECONDS"
|
||||
GITHUB_TOKEN_ENVIRONMENT_KEYS = ("GFRAMEWORK_GITHUB_TOKEN", "GITHUB_TOKEN", "GH_TOKEN")
|
||||
PROXY_ENVIRONMENT_KEYS = ("http_proxy", "https_proxy", "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "all_proxy")
|
||||
DEFAULT_REQUEST_TIMEOUT_SECONDS = 60
|
||||
USER_AGENT = "codex-gframework-issue-review"
|
||||
DISPLAY_SECTION_CHOICES = (
|
||||
"issue",
|
||||
"summary",
|
||||
"comments",
|
||||
"events",
|
||||
"references",
|
||||
"warnings",
|
||||
)
|
||||
ISSUE_TYPE_CANDIDATES = ("bug", "feature", "docs", "question", "maintenance")
|
||||
ACTIVE_TOPIC_KEYWORDS: dict[str, tuple[str, ...]] = {
|
||||
"ai-first-config-system": ("config", "configuration", "gameconfig", "settings"),
|
||||
"coroutine-optimization": ("coroutine", "yield", "await", "scheduler"),
|
||||
"cqrs-rewrite": ("cqrs", "command", "query", "eventbus", "event bus"),
|
||||
"data-repository-persistence": ("repository", "serialization", "persistence", "data", "settings"),
|
||||
"runtime-generator-boundary": ("source generator", "generator", "attribute", "packaging"),
|
||||
"semantic-release-versioning": ("release", "version", "semantic-release", "tag", "publish"),
|
||||
"documentation-full-coverage-governance": ("docs", "documentation", "readme", "vitepress", "api reference"),
|
||||
}
|
||||
ACTUAL_BEHAVIOR_PATTERNS = (
|
||||
"actual",
|
||||
"currently",
|
||||
"instead",
|
||||
"but",
|
||||
"error",
|
||||
"exception",
|
||||
"fails",
|
||||
"failed",
|
||||
"wrong",
|
||||
)
|
||||
EXPECTED_BEHAVIOR_PATTERNS = (
|
||||
"expected",
|
||||
"should",
|
||||
"want",
|
||||
"would like",
|
||||
"needs to",
|
||||
)
|
||||
REPRODUCTION_PATTERNS = (
|
||||
"steps to reproduce",
|
||||
"reproduce",
|
||||
"reproduction",
|
||||
"how to reproduce",
|
||||
"minimal example",
|
||||
"sample",
|
||||
"demo",
|
||||
)
|
||||
ENVIRONMENT_PATTERNS = (
|
||||
"windows",
|
||||
"linux",
|
||||
"macos",
|
||||
"wsl",
|
||||
"godot",
|
||||
".net",
|
||||
"sdk",
|
||||
"version",
|
||||
"environment",
|
||||
)
|
||||
ACCEPTANCE_PATTERNS = (
|
||||
"acceptance",
|
||||
"done when",
|
||||
"definition of done",
|
||||
"verified by",
|
||||
"test plan",
|
||||
)
|
||||
FILE_PATH_PATTERN = re.compile(r"\b(?:[A-Za-z0-9_.-]+/)+[A-Za-z0-9_.-]+\b")
|
||||
ISSUE_REFERENCE_PATTERN = re.compile(r"(?:^|\s)#(\d+)\b")
|
||||
COMMIT_REFERENCE_PATTERN = re.compile(r"\b[0-9a-f]{7,40}\b")
|
||||
LINE_BREAK_NORMALIZER = re.compile(r"\n{3,}")
|
||||
|
||||
|
||||
def resolve_git_command() -> str:
|
||||
"""Resolve the git executable to use for this repository."""
|
||||
candidates = [
|
||||
os.environ.get(GIT_ENVIRONMENT_KEY),
|
||||
"git.exe",
|
||||
"git",
|
||||
]
|
||||
|
||||
for candidate in candidates:
|
||||
if not candidate:
|
||||
continue
|
||||
|
||||
if os.path.isabs(candidate):
|
||||
if os.path.exists(candidate):
|
||||
return candidate
|
||||
continue
|
||||
|
||||
resolved_candidate = shutil.which(candidate)
|
||||
if resolved_candidate:
|
||||
return resolved_candidate
|
||||
|
||||
raise RuntimeError(f"No usable git executable found. Set {GIT_ENVIRONMENT_KEY} to override it.")
|
||||
|
||||
|
||||
def find_repository_root(start_path: Path) -> Path | None:
|
||||
"""Locate the repository root by walking parent directories for repo markers."""
|
||||
for candidate in (start_path, *start_path.parents):
|
||||
if (candidate / "AGENTS.md").exists() and (candidate / ".ai/environment/tools.ai.yaml").exists():
|
||||
return candidate
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def resolve_worktree_git_dir(repository_root: Path) -> Path | None:
|
||||
"""Resolve the main-repository worktree gitdir for this WSL worktree layout."""
|
||||
if repository_root.parent.name != WORKTREE_ROOT_DIRECTORY_NAME:
|
||||
return None
|
||||
|
||||
primary_repository_root = repository_root.parent.parent / REPO
|
||||
candidate_git_dir = primary_repository_root / ".git" / "worktrees" / repository_root.name
|
||||
return candidate_git_dir if candidate_git_dir.exists() else None
|
||||
|
||||
|
||||
def resolve_git_invocation() -> list[str]:
|
||||
"""Resolve the git command arguments, preferring explicit WSL worktree binding."""
|
||||
configured_git_dir = os.environ.get(GIT_DIR_ENVIRONMENT_KEY)
|
||||
configured_work_tree = os.environ.get(WORK_TREE_ENVIRONMENT_KEY)
|
||||
linux_git = shutil.which("git")
|
||||
|
||||
if configured_git_dir and configured_work_tree and linux_git:
|
||||
return [linux_git, f"--git-dir={configured_git_dir}", f"--work-tree={configured_work_tree}"]
|
||||
|
||||
repository_root = find_repository_root(Path.cwd())
|
||||
if repository_root is not None and linux_git:
|
||||
worktree_git_dir = resolve_worktree_git_dir(repository_root)
|
||||
if worktree_git_dir is not None:
|
||||
return [linux_git, f"--git-dir={worktree_git_dir}", f"--work-tree={repository_root}"]
|
||||
|
||||
root_git_dir = repository_root / ".git"
|
||||
if root_git_dir.exists():
|
||||
return [linux_git, f"--git-dir={root_git_dir}", f"--work-tree={repository_root}"]
|
||||
|
||||
return [resolve_git_command()]
|
||||
|
||||
|
||||
def resolve_request_timeout_seconds() -> int:
|
||||
"""Return the GitHub request timeout in seconds."""
|
||||
configured_timeout = os.environ.get(REQUEST_TIMEOUT_ENVIRONMENT_KEY)
|
||||
if not configured_timeout:
|
||||
return DEFAULT_REQUEST_TIMEOUT_SECONDS
|
||||
|
||||
try:
|
||||
parsed_timeout = int(configured_timeout)
|
||||
except ValueError as error:
|
||||
raise RuntimeError(
|
||||
f"{REQUEST_TIMEOUT_ENVIRONMENT_KEY} must be an integer number of seconds."
|
||||
) from error
|
||||
|
||||
if parsed_timeout <= 0:
|
||||
raise RuntimeError(f"{REQUEST_TIMEOUT_ENVIRONMENT_KEY} must be greater than zero.")
|
||||
|
||||
return parsed_timeout
|
||||
|
||||
|
||||
def run_command(args: list[str]) -> str:
|
||||
"""Run a command and return stdout, raising on failure."""
|
||||
process = subprocess.run(args, capture_output=True, text=True, check=False)
|
||||
if process.returncode != 0:
|
||||
stderr = process.stderr.strip()
|
||||
raise RuntimeError(f"Command failed: {' '.join(args)}\n{stderr}")
|
||||
return process.stdout.strip()
|
||||
|
||||
|
||||
def get_current_branch() -> str:
|
||||
"""Return the current git branch name."""
|
||||
return run_command([*resolve_git_invocation(), "rev-parse", "--abbrev-ref", "HEAD"])
|
||||
|
||||
|
||||
def resolve_github_token() -> str | None:
|
||||
"""Return the first configured GitHub token for authenticated API requests."""
|
||||
for environment_key in GITHUB_TOKEN_ENVIRONMENT_KEYS:
|
||||
token = os.environ.get(environment_key)
|
||||
if token:
|
||||
return token
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def build_request_headers(accept: str) -> dict[str, str]:
|
||||
"""Build GitHub request headers and include auth when a token is available."""
|
||||
headers = {"Accept": accept, "User-Agent": USER_AGENT}
|
||||
token = resolve_github_token()
|
||||
if token:
|
||||
headers["Authorization"] = f"Bearer {token}"
|
||||
|
||||
return headers
|
||||
|
||||
|
||||
def has_proxy_environment() -> bool:
|
||||
"""Return whether the current process is configured to use an outbound proxy."""
|
||||
return any(os.environ.get(environment_key) for environment_key in PROXY_ENVIRONMENT_KEYS)
|
||||
|
||||
|
||||
def perform_request(url: str, headers: dict[str, str], *, disable_proxy: bool) -> tuple[str, Any]:
|
||||
"""Execute a single HTTP request and return decoded text plus response headers."""
|
||||
opener = (
|
||||
urllib.request.build_opener(urllib.request.ProxyHandler({}))
|
||||
if disable_proxy
|
||||
else urllib.request.build_opener()
|
||||
)
|
||||
request = urllib.request.Request(url, headers=headers)
|
||||
with opener.open(request, timeout=resolve_request_timeout_seconds()) as response:
|
||||
return response.read().decode("utf-8", "replace"), response.headers
|
||||
|
||||
|
||||
def open_url(url: str, accept: str) -> tuple[str, Any]:
|
||||
"""Open a URL, retrying without proxies only when the configured proxy path fails."""
|
||||
headers = build_request_headers(accept)
|
||||
|
||||
try:
|
||||
return perform_request(url, headers, disable_proxy=False)
|
||||
except urllib.error.HTTPError:
|
||||
raise
|
||||
except (urllib.error.URLError, TimeoutError, OSError):
|
||||
if not has_proxy_environment():
|
||||
raise
|
||||
|
||||
return perform_request(url, headers, disable_proxy=True)
|
||||
|
||||
|
||||
def fetch_json(url: str, accept: str = "application/vnd.github+json") -> tuple[Any, Any]:
|
||||
"""Fetch a JSON payload and its response headers from GitHub."""
|
||||
text, headers = open_url(url, accept=accept)
|
||||
return json.loads(text), headers
|
||||
|
||||
|
||||
def extract_next_link(headers: Any) -> str | None:
|
||||
"""Extract the next-page link from GitHub pagination headers."""
|
||||
link_header = headers.get("Link")
|
||||
if not link_header:
|
||||
return None
|
||||
|
||||
match = re.search(r'<([^>]+)>;\s*rel="next"', link_header)
|
||||
return match.group(1) if match else None
|
||||
|
||||
|
||||
def fetch_paged_json(url: str, accept: str = "application/vnd.github+json") -> list[dict[str, Any]]:
|
||||
"""Fetch every page from a paginated GitHub API endpoint."""
|
||||
items: list[dict[str, Any]] = []
|
||||
next_url: str | None = url
|
||||
while next_url:
|
||||
payload, headers = fetch_json(next_url, accept=accept)
|
||||
if not isinstance(payload, list):
|
||||
raise RuntimeError(f"Expected list payload from GitHub API, got {type(payload).__name__}.")
|
||||
|
||||
items.extend(payload)
|
||||
next_url = extract_next_link(headers)
|
||||
|
||||
return items
|
||||
|
||||
|
||||
def collapse_whitespace(text: str) -> str:
|
||||
"""Collapse repeated whitespace into single spaces while preserving paragraph intent."""
|
||||
normalized = text.replace("\r\n", "\n").replace("\r", "\n")
|
||||
normalized = LINE_BREAK_NORMALIZER.sub("\n\n", normalized)
|
||||
normalized = re.sub(r"[ \t]+", " ", normalized)
|
||||
normalized = re.sub(r" *\n *", "\n", normalized)
|
||||
return normalized.strip()
|
||||
|
||||
|
||||
def truncate_text(text: str, max_length: int) -> str:
|
||||
"""Collapse whitespace and truncate long text for CLI display."""
|
||||
collapsed = collapse_whitespace(text)
|
||||
if max_length <= 0 or len(collapsed) <= max_length:
|
||||
return collapsed
|
||||
|
||||
return collapsed[: max_length - 3].rstrip() + "..."
|
||||
|
||||
|
||||
def filter_open_issue_candidates(items: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""Filter GitHub issue list responses down to non-PR issue items."""
|
||||
return [item for item in items if not item.get("pull_request")]
|
||||
|
||||
|
||||
def select_single_open_issue_number(items: list[dict[str, Any]]) -> int:
|
||||
"""Resolve the target issue number when the repository has exactly one open issue."""
|
||||
issues = filter_open_issue_candidates(items)
|
||||
if not issues:
|
||||
raise RuntimeError("No open GitHub issues found for this repository. Pass --issue <number> to inspect one.")
|
||||
|
||||
if len(issues) > 1:
|
||||
numbers = ", ".join(str(item.get("number")) for item in issues[:5])
|
||||
suffix = "" if len(issues) <= 5 else ", ..."
|
||||
raise RuntimeError(
|
||||
"Multiple open GitHub issues found for this repository "
|
||||
f"({len(issues)} total: {numbers}{suffix}). Pass --issue <number> to inspect one."
|
||||
)
|
||||
|
||||
return int(issues[0]["number"])
|
||||
|
||||
|
||||
def resolve_issue_number(issue_number: int | None) -> tuple[int, str]:
|
||||
"""Resolve the issue number, auto-selecting only when exactly one open issue exists."""
|
||||
if issue_number is not None:
|
||||
return issue_number, "explicit"
|
||||
|
||||
open_items = fetch_paged_json(f"https://api.github.com/repos/{OWNER}/{REPO}/issues?state=open&per_page=100")
|
||||
return select_single_open_issue_number(open_items), "auto-single-open-issue"
|
||||
|
||||
|
||||
def fetch_issue_metadata(issue_number: int) -> dict[str, Any]:
|
||||
"""Fetch normalized metadata for a GitHub issue."""
|
||||
payload, _ = fetch_json(f"https://api.github.com/repos/{OWNER}/{REPO}/issues/{issue_number}")
|
||||
if not isinstance(payload, dict):
|
||||
raise RuntimeError("Failed to fetch GitHub issue metadata.")
|
||||
|
||||
if payload.get("pull_request"):
|
||||
raise RuntimeError(f"Item #{issue_number} is a pull request, not a plain issue.")
|
||||
|
||||
labels = []
|
||||
for label in payload.get("labels", []):
|
||||
if isinstance(label, dict) and label.get("name"):
|
||||
labels.append(str(label["name"]))
|
||||
|
||||
assignees = []
|
||||
for assignee in payload.get("assignees", []):
|
||||
login = assignee.get("login")
|
||||
if login:
|
||||
assignees.append(str(login))
|
||||
|
||||
milestone_title = None
|
||||
milestone = payload.get("milestone")
|
||||
if isinstance(milestone, dict) and milestone.get("title"):
|
||||
milestone_title = str(milestone["title"])
|
||||
|
||||
return {
|
||||
"number": int(payload["number"]),
|
||||
"title": str(payload["title"]),
|
||||
"state": str(payload["state"]).upper(),
|
||||
"url": str(payload["html_url"]),
|
||||
"author": str(payload.get("user", {}).get("login") or ""),
|
||||
"created_at": str(payload.get("created_at") or ""),
|
||||
"updated_at": str(payload.get("updated_at") or ""),
|
||||
"labels": labels,
|
||||
"assignees": assignees,
|
||||
"milestone": milestone_title,
|
||||
"body": str(payload.get("body") or ""),
|
||||
}
|
||||
|
||||
|
||||
def fetch_issue_comments(issue_number: int) -> list[dict[str, Any]]:
|
||||
"""Fetch issue comments for the selected issue."""
|
||||
return fetch_paged_json(f"https://api.github.com/repos/{OWNER}/{REPO}/issues/{issue_number}/comments?per_page=100")
|
||||
|
||||
|
||||
def fetch_issue_timeline(issue_number: int) -> list[dict[str, Any]]:
|
||||
"""Fetch issue timeline events when GitHub exposes them to the current client."""
|
||||
return fetch_paged_json(
|
||||
f"https://api.github.com/repos/{OWNER}/{REPO}/issues/{issue_number}/timeline?per_page=100",
|
||||
accept="application/vnd.github+json",
|
||||
)
|
||||
|
||||
|
||||
def normalize_comment(comment: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Normalize an issue comment for structured output."""
|
||||
return {
|
||||
"id": int(comment.get("id") or 0),
|
||||
"author": str(comment.get("user", {}).get("login") or ""),
|
||||
"created_at": str(comment.get("created_at") or ""),
|
||||
"updated_at": str(comment.get("updated_at") or ""),
|
||||
"body": str(comment.get("body") or ""),
|
||||
}
|
||||
|
||||
|
||||
def normalize_timeline_event(event: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Normalize the GitHub timeline event fields used by triage output."""
|
||||
actor = str(event.get("actor", {}).get("login") or "")
|
||||
created_at = str(event.get("created_at") or event.get("submitted_at") or "")
|
||||
event_type = str(event.get("event") or event.get("__typename") or "unknown")
|
||||
label_name = ""
|
||||
assignee = ""
|
||||
source_issue_number: int | None = None
|
||||
source_issue_url = ""
|
||||
commit_id = ""
|
||||
|
||||
label = event.get("label")
|
||||
if isinstance(label, dict) and label.get("name"):
|
||||
label_name = str(label["name"])
|
||||
|
||||
assignee_payload = event.get("assignee")
|
||||
if isinstance(assignee_payload, dict) and assignee_payload.get("login"):
|
||||
assignee = str(assignee_payload["login"])
|
||||
|
||||
source = event.get("source")
|
||||
if isinstance(source, dict):
|
||||
issue_payload = source.get("issue")
|
||||
if isinstance(issue_payload, dict):
|
||||
if issue_payload.get("number"):
|
||||
source_issue_number = int(issue_payload["number"])
|
||||
if issue_payload.get("html_url"):
|
||||
source_issue_url = str(issue_payload["html_url"])
|
||||
|
||||
commit_id_value = event.get("commit_id")
|
||||
if isinstance(commit_id_value, str):
|
||||
commit_id = commit_id_value
|
||||
|
||||
return {
|
||||
"event": event_type,
|
||||
"actor": actor,
|
||||
"created_at": created_at,
|
||||
"label": label_name,
|
||||
"assignee": assignee,
|
||||
"commit_id": commit_id,
|
||||
"source_issue_number": source_issue_number,
|
||||
"source_issue_url": source_issue_url,
|
||||
}
|
||||
|
||||
|
||||
def gather_text_blocks(issue: dict[str, Any], comments: list[dict[str, Any]]) -> list[str]:
|
||||
"""Return the issue body plus discussion comment bodies for heuristic parsing."""
|
||||
blocks = [issue.get("body", "")]
|
||||
blocks.extend(comment.get("body", "") for comment in comments)
|
||||
return [block for block in blocks if block]
|
||||
|
||||
|
||||
def has_any_pattern(text_blocks: list[str], patterns: tuple[str, ...]) -> bool:
|
||||
"""Return whether any normalized text block contains any requested pattern."""
|
||||
lowered_blocks = [collapse_whitespace(block).lower() for block in text_blocks]
|
||||
return any(pattern in block for block in lowered_blocks for pattern in patterns)
|
||||
|
||||
|
||||
def choose_issue_type_candidates(issue: dict[str, Any], text_blocks: list[str]) -> list[str]:
|
||||
"""Infer lightweight issue-type candidates from labels and discussion text."""
|
||||
labels = [label.lower() for label in issue.get("labels", [])]
|
||||
text = "\n".join(text_blocks).lower()
|
||||
candidates: list[str] = []
|
||||
|
||||
if any(label in {"bug", "regression"} for label in labels) or "bug" in text or "error" in text or "fails" in text:
|
||||
candidates.append("bug")
|
||||
if any(label in {"feature", "enhancement"} for label in labels) or "feature" in text or "support" in text:
|
||||
candidates.append("feature")
|
||||
if any(label in {"documentation", "docs"} for label in labels) or "documentation" in text or "readme" in text:
|
||||
candidates.append("docs")
|
||||
if any(label in {"question", "help wanted"} for label in labels) or "?" in issue.get("title", ""):
|
||||
candidates.append("question")
|
||||
if any(label in {"chore", "maintenance", "refactor"} for label in labels) or "cleanup" in text or "refactor" in text:
|
||||
candidates.append("maintenance")
|
||||
|
||||
if not candidates:
|
||||
candidates.append("question" if issue.get("body", "").strip().endswith("?") else "bug")
|
||||
|
||||
ordered_candidates: list[str] = []
|
||||
for candidate in ISSUE_TYPE_CANDIDATES:
|
||||
if candidate in candidates:
|
||||
ordered_candidates.append(candidate)
|
||||
|
||||
return ordered_candidates
|
||||
|
||||
|
||||
def extract_references_from_text(text: str) -> dict[str, list[str]]:
|
||||
"""Extract issue, commit, and file-path references from one text block."""
|
||||
issue_numbers = sorted({match.group(1) for match in ISSUE_REFERENCE_PATTERN.finditer(text)}, key=int)
|
||||
commit_shas = sorted({match.group(0) for match in COMMIT_REFERENCE_PATTERN.finditer(text)})
|
||||
file_paths = sorted({match.group(0) for match in FILE_PATH_PATTERN.finditer(text)})
|
||||
|
||||
return {
|
||||
"issues": [f"#{number}" for number in issue_numbers],
|
||||
"commit_shas": commit_shas,
|
||||
"file_paths": file_paths,
|
||||
}
|
||||
|
||||
|
||||
def merge_reference_values(values: list[dict[str, list[str]]]) -> dict[str, list[str]]:
|
||||
"""Merge extracted reference lists while preserving sorted unique output."""
|
||||
merged: dict[str, set[str]] = {"issues": set(), "commit_shas": set(), "file_paths": set()}
|
||||
for value in values:
|
||||
for key in merged:
|
||||
merged[key].update(value.get(key, []))
|
||||
|
||||
return {
|
||||
"issues": sorted(merged["issues"], key=lambda item: int(item[1:])),
|
||||
"commit_shas": sorted(merged["commit_shas"]),
|
||||
"file_paths": sorted(merged["file_paths"]),
|
||||
}
|
||||
|
||||
|
||||
def build_references(issue: dict[str, Any], comments: list[dict[str, Any]], events: list[dict[str, Any]]) -> dict[str, Any]:
|
||||
"""Build structured references from issue text and timeline context."""
|
||||
extracted = [extract_references_from_text(issue.get("body", ""))]
|
||||
extracted.extend(extract_references_from_text(comment.get("body", "")) for comment in comments)
|
||||
merged = merge_reference_values(extracted)
|
||||
referenced_by_timeline = sorted(
|
||||
{
|
||||
f"#{event['source_issue_number']}"
|
||||
for event in events
|
||||
if event.get("source_issue_number") is not None
|
||||
},
|
||||
key=lambda item: int(item[1:]),
|
||||
)
|
||||
|
||||
pull_request_references = sorted(
|
||||
{
|
||||
issue_reference
|
||||
for issue_reference in merged["issues"]
|
||||
if issue_reference != f"#{issue['number']}"
|
||||
},
|
||||
key=lambda item: int(item[1:]),
|
||||
)
|
||||
|
||||
return {
|
||||
"issues": merged["issues"],
|
||||
"pull_requests_or_issues": pull_request_references,
|
||||
"commit_shas": merged["commit_shas"],
|
||||
"file_paths": merged["file_paths"],
|
||||
"timeline_cross_references": referenced_by_timeline,
|
||||
}
|
||||
|
||||
|
||||
def build_information_flags(
|
||||
issue: dict[str, Any],
|
||||
comments: list[dict[str, Any]],
|
||||
issue_type_candidates: list[str],
|
||||
) -> dict[str, bool]:
|
||||
"""Derive missing-information and readiness flags with issue-type-aware heuristics."""
|
||||
text_blocks = gather_text_blocks(issue, comments)
|
||||
has_reproduction_steps = has_any_pattern(text_blocks, REPRODUCTION_PATTERNS)
|
||||
has_expected_behavior = has_any_pattern(text_blocks, EXPECTED_BEHAVIOR_PATTERNS)
|
||||
has_actual_behavior = has_any_pattern(text_blocks, ACTUAL_BEHAVIOR_PATTERNS)
|
||||
has_environment_details = has_any_pattern(text_blocks, ENVIRONMENT_PATTERNS)
|
||||
has_acceptance_signals = has_any_pattern(text_blocks, ACCEPTANCE_PATTERNS)
|
||||
primary_issue_type = issue_type_candidates[0] if issue_type_candidates else "bug"
|
||||
|
||||
if primary_issue_type == "bug":
|
||||
needs_clarification = not (
|
||||
(has_actual_behavior and (has_reproduction_steps or has_environment_details))
|
||||
or has_acceptance_signals
|
||||
)
|
||||
elif primary_issue_type in {"feature", "docs"}:
|
||||
needs_clarification = not (has_expected_behavior or has_acceptance_signals)
|
||||
elif primary_issue_type == "maintenance":
|
||||
needs_clarification = not (has_expected_behavior or has_actual_behavior or has_acceptance_signals)
|
||||
else:
|
||||
needs_clarification = not (has_expected_behavior or has_actual_behavior or has_acceptance_signals)
|
||||
|
||||
return {
|
||||
"has_reproduction_steps": has_reproduction_steps,
|
||||
"has_expected_behavior": has_expected_behavior,
|
||||
"has_actual_behavior": has_actual_behavior,
|
||||
"has_environment_details": has_environment_details,
|
||||
"has_acceptance_signals": has_acceptance_signals,
|
||||
"needs_clarification": needs_clarification,
|
||||
}
|
||||
|
||||
|
||||
def choose_affected_topics(issue: dict[str, Any], comments: list[dict[str, Any]]) -> list[str]:
|
||||
"""Map the issue discussion to likely active topics when obvious keyword matches exist."""
|
||||
text = "\n".join(gather_text_blocks(issue, comments)).lower()
|
||||
matches: list[str] = []
|
||||
for topic, keywords in ACTIVE_TOPIC_KEYWORDS.items():
|
||||
if any(keyword in text for keyword in keywords):
|
||||
matches.append(topic)
|
||||
|
||||
return matches
|
||||
|
||||
|
||||
def choose_next_action(
|
||||
information_flags: dict[str, bool],
|
||||
issue_type_candidates: list[str],
|
||||
affected_topics: list[str],
|
||||
) -> str:
|
||||
"""Choose the next handling mode for boot handoff."""
|
||||
if information_flags["needs_clarification"]:
|
||||
return "clarify-issue-before-code"
|
||||
if affected_topics:
|
||||
return "resume-existing-topic-with-boot"
|
||||
if "docs" in issue_type_candidates and issue_type_candidates[0] == "docs":
|
||||
return "start-new-docs-topic-with-boot"
|
||||
return "start-new-topic-with-boot"
|
||||
|
||||
|
||||
def build_triage_hints(issue: dict[str, Any], comments: list[dict[str, Any]]) -> dict[str, Any]:
|
||||
"""Build lightweight, reviewable triage hints for boot follow-up."""
|
||||
text_blocks = gather_text_blocks(issue, comments)
|
||||
issue_type_candidates = choose_issue_type_candidates(issue, text_blocks)
|
||||
information_flags = build_information_flags(issue, comments, issue_type_candidates)
|
||||
affected_topics = choose_affected_topics(issue, comments)
|
||||
next_action = choose_next_action(information_flags, issue_type_candidates, affected_topics)
|
||||
|
||||
return {
|
||||
"issue_type_candidates": issue_type_candidates,
|
||||
"information_flags": information_flags,
|
||||
"affected_active_topics": affected_topics,
|
||||
"next_action": next_action,
|
||||
"boot_handoff": {
|
||||
"recommended_skill": "gframework-boot",
|
||||
"mode": "resume" if affected_topics else "new",
|
||||
"notes": (
|
||||
"Use gframework-boot to verify the issue against local code and active ai-plan topics."
|
||||
if not information_flags["needs_clarification"]
|
||||
else "Use gframework-boot to record a clarification-first task before changing code."
|
||||
),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def build_result(issue_number: int, branch: str, resolution_mode: str) -> dict[str, Any]:
|
||||
"""Build the full issue review payload for the selected issue."""
|
||||
parse_warnings: list[str] = []
|
||||
issue = fetch_issue_metadata(issue_number)
|
||||
raw_comments = fetch_issue_comments(issue_number)
|
||||
comments = [normalize_comment(comment) for comment in raw_comments]
|
||||
|
||||
events: list[dict[str, Any]] = []
|
||||
try:
|
||||
raw_events = fetch_issue_timeline(issue_number)
|
||||
events = [normalize_timeline_event(event) for event in raw_events]
|
||||
except Exception as error: # noqa: BLE001
|
||||
parse_warnings.append(f"Issue timeline could not be fetched or parsed: {error}")
|
||||
|
||||
references = build_references(issue, comments, events)
|
||||
triage_hints = build_triage_hints(issue, comments)
|
||||
|
||||
return {
|
||||
"issue": {
|
||||
**issue,
|
||||
"resolved_from_branch": branch,
|
||||
"resolution_mode": resolution_mode,
|
||||
},
|
||||
"discussion": {
|
||||
"comment_count": len(comments),
|
||||
"comments": comments,
|
||||
},
|
||||
"events": {
|
||||
"count": len(events),
|
||||
"items": events,
|
||||
},
|
||||
"references": references,
|
||||
"triage_hints": triage_hints,
|
||||
"parse_warnings": parse_warnings,
|
||||
}
|
||||
|
||||
|
||||
def write_json_output(result: dict[str, Any], output_path: str) -> str:
|
||||
"""Write the full JSON result to disk and return the destination path."""
|
||||
destination_path = Path(output_path).expanduser()
|
||||
destination_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
destination_path.write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
return str(destination_path)
|
||||
|
||||
|
||||
def summarize_events(events: list[dict[str, Any]]) -> list[str]:
|
||||
"""Convert normalized events into concise text lines."""
|
||||
lines: list[str] = []
|
||||
for event in events:
|
||||
summary = f"- {event['event']}"
|
||||
details: list[str] = []
|
||||
if event.get("actor"):
|
||||
details.append(f"actor={event['actor']}")
|
||||
if event.get("label"):
|
||||
details.append(f"label={event['label']}")
|
||||
if event.get("assignee"):
|
||||
details.append(f"assignee={event['assignee']}")
|
||||
if event.get("source_issue_number") is not None:
|
||||
details.append(f"source_issue=#{event['source_issue_number']}")
|
||||
if event.get("commit_id"):
|
||||
details.append(f"commit={event['commit_id'][:12]}")
|
||||
if event.get("created_at"):
|
||||
details.append(f"at={event['created_at']}")
|
||||
if details:
|
||||
summary += " (" + ", ".join(details) + ")"
|
||||
lines.append(summary)
|
||||
return lines
|
||||
|
||||
|
||||
def format_text(
|
||||
result: dict[str, Any],
|
||||
*,
|
||||
sections: list[str] | None = None,
|
||||
max_description_length: int = 400,
|
||||
json_output_path: str | None = None,
|
||||
) -> str:
|
||||
"""Format the result payload into concise text output."""
|
||||
lines: list[str] = []
|
||||
selected_sections = set(sections or DISPLAY_SECTION_CHOICES)
|
||||
issue = result["issue"]
|
||||
triage_hints = result["triage_hints"]
|
||||
discussion = result["discussion"]
|
||||
events = result["events"]
|
||||
references = result["references"]
|
||||
|
||||
if "issue" in selected_sections:
|
||||
lines.append(f"Issue #{issue['number']}: {issue['title']}")
|
||||
lines.append(f"State: {issue['state']}")
|
||||
lines.append(f"Author: {issue['author']}")
|
||||
lines.append(f"Labels: {', '.join(issue['labels']) if issue['labels'] else '(none)'}")
|
||||
lines.append(f"Assignees: {', '.join(issue['assignees']) if issue['assignees'] else '(none)'}")
|
||||
lines.append(f"Milestone: {issue['milestone'] or '(none)'}")
|
||||
lines.append(f"Created: {issue['created_at']}")
|
||||
lines.append(f"Updated: {issue['updated_at']}")
|
||||
lines.append(f"Resolved from branch: {issue['resolved_from_branch'] or '(not branch-based)'}")
|
||||
lines.append(f"Resolution mode: {issue['resolution_mode']}")
|
||||
lines.append(f"URL: {issue['url']}")
|
||||
if issue["body"]:
|
||||
lines.append("Body:")
|
||||
lines.append(truncate_text(issue["body"], max_description_length))
|
||||
|
||||
if "summary" in selected_sections:
|
||||
lines.append("")
|
||||
lines.append("Triage summary:")
|
||||
lines.append("- Issue type candidates: " + ", ".join(triage_hints["issue_type_candidates"]))
|
||||
information_flags = triage_hints["information_flags"]
|
||||
lines.append(
|
||||
"- Information flags: "
|
||||
+ ", ".join(
|
||||
[
|
||||
f"repro={'yes' if information_flags['has_reproduction_steps'] else 'no'}",
|
||||
f"expected={'yes' if information_flags['has_expected_behavior'] else 'no'}",
|
||||
f"actual={'yes' if information_flags['has_actual_behavior'] else 'no'}",
|
||||
f"environment={'yes' if information_flags['has_environment_details'] else 'no'}",
|
||||
f"acceptance={'yes' if information_flags['has_acceptance_signals'] else 'no'}",
|
||||
f"needs_clarification={'yes' if information_flags['needs_clarification'] else 'no'}",
|
||||
]
|
||||
)
|
||||
)
|
||||
lines.append(
|
||||
"- Affected active topics: "
|
||||
+ (", ".join(triage_hints["affected_active_topics"]) if triage_hints["affected_active_topics"] else "(none)")
|
||||
)
|
||||
lines.append(f"- Next action: {triage_hints['next_action']}")
|
||||
lines.append(f"- Boot handoff: {triage_hints['boot_handoff']['notes']}")
|
||||
|
||||
if "comments" in selected_sections:
|
||||
lines.append("")
|
||||
lines.append(f"Discussion comments: {discussion['comment_count']}")
|
||||
for comment in discussion["comments"]:
|
||||
lines.append(f"- {comment['author']} at {comment['created_at']}")
|
||||
lines.append(f" {truncate_text(comment['body'], max_description_length)}")
|
||||
|
||||
if "events" in selected_sections:
|
||||
lines.append("")
|
||||
lines.append(f"Timeline events: {events['count']}")
|
||||
lines.extend(summarize_events(events["items"]))
|
||||
|
||||
if "references" in selected_sections:
|
||||
lines.append("")
|
||||
lines.append("References:")
|
||||
lines.append("- Mentioned issues: " + (", ".join(references["issues"]) if references["issues"] else "(none)"))
|
||||
lines.append(
|
||||
"- Cross references: "
|
||||
+ (
|
||||
", ".join(references["timeline_cross_references"])
|
||||
if references["timeline_cross_references"]
|
||||
else "(none)"
|
||||
)
|
||||
)
|
||||
lines.append(
|
||||
"- Related issue/PR mentions: "
|
||||
+ (
|
||||
", ".join(references["pull_requests_or_issues"])
|
||||
if references["pull_requests_or_issues"]
|
||||
else "(none)"
|
||||
)
|
||||
)
|
||||
lines.append("- Commit SHAs: " + (", ".join(references["commit_shas"]) if references["commit_shas"] else "(none)"))
|
||||
lines.append("- File paths: " + (", ".join(references["file_paths"]) if references["file_paths"] else "(none)"))
|
||||
|
||||
if result["parse_warnings"] and "warnings" in selected_sections:
|
||||
lines.append("")
|
||||
lines.append("Warnings:")
|
||||
for warning in result["parse_warnings"]:
|
||||
lines.append(f"- {truncate_text(warning, max_description_length)}")
|
||||
|
||||
if json_output_path:
|
||||
lines.append("")
|
||||
lines.append(f"Full JSON written to: {json_output_path}")
|
||||
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def parse_args() -> argparse.Namespace:
|
||||
"""Parse CLI arguments."""
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--branch", help="Override the current branch name.")
|
||||
parser.add_argument("--issue", type=int, help="Fetch a specific issue number instead of auto-selecting one.")
|
||||
parser.add_argument("--format", choices=("text", "json"), default="text")
|
||||
parser.add_argument(
|
||||
"--json-output",
|
||||
help="Write the full JSON result to a file. When used with --format text, stdout stays concise and points to the file.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--section",
|
||||
action="append",
|
||||
choices=DISPLAY_SECTION_CHOICES,
|
||||
help="Limit text output to specific sections. Can be passed multiple times.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--max-description-length",
|
||||
type=int,
|
||||
default=400,
|
||||
help="Truncate long text bodies in text output to this many characters.",
|
||||
)
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""Run the CLI entry point."""
|
||||
args = parse_args()
|
||||
branch = args.branch or get_current_branch()
|
||||
issue_number, resolution_mode = resolve_issue_number(args.issue)
|
||||
result = build_result(issue_number, branch, resolution_mode)
|
||||
|
||||
json_output_path: str | None = None
|
||||
if args.json_output:
|
||||
json_output_path = write_json_output(result, args.json_output)
|
||||
|
||||
if args.format == "json":
|
||||
print(json.dumps(result, ensure_ascii=False, indent=2))
|
||||
return
|
||||
|
||||
print(
|
||||
format_text(
|
||||
result,
|
||||
sections=args.section,
|
||||
max_description_length=args.max_description_length,
|
||||
json_output_path=json_output_path,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except Exception as error: # noqa: BLE001
|
||||
print(str(error), file=sys.stderr)
|
||||
sys.exit(1)
|
||||
@ -0,0 +1,94 @@
|
||||
#!/usr/bin/env python3
|
||||
# Copyright (c) 2025-2026 GeWuYou
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
"""Regression tests for the GFramework issue review fetch helper."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
import unittest
|
||||
|
||||
|
||||
SCRIPT_PATH = Path(__file__).with_name("fetch_current_issue_review.py")
|
||||
MODULE_SPEC = importlib.util.spec_from_file_location("fetch_current_issue_review", SCRIPT_PATH)
|
||||
if MODULE_SPEC is None or MODULE_SPEC.loader is None:
|
||||
raise RuntimeError(f"Unable to load module from {SCRIPT_PATH}.")
|
||||
|
||||
MODULE = importlib.util.module_from_spec(MODULE_SPEC)
|
||||
MODULE_SPEC.loader.exec_module(MODULE)
|
||||
|
||||
|
||||
class SelectSingleOpenIssueNumberTests(unittest.TestCase):
|
||||
"""Cover auto-resolution rules for open GitHub issues."""
|
||||
|
||||
def test_select_single_open_issue_number_filters_pull_requests(self) -> None:
|
||||
"""Pull requests in the issues API must not block the single-open-issue path."""
|
||||
selected = MODULE.select_single_open_issue_number(
|
||||
[
|
||||
{"number": 10, "pull_request": {"url": "https://example.test/pr/10"}},
|
||||
{"number": 11},
|
||||
]
|
||||
)
|
||||
|
||||
self.assertEqual(selected, 11)
|
||||
|
||||
def test_select_single_open_issue_number_rejects_multiple_plain_issues(self) -> None:
|
||||
"""Auto-resolution must stop when more than one plain issue is open."""
|
||||
with self.assertRaisesRegex(RuntimeError, "Multiple open GitHub issues found"):
|
||||
MODULE.select_single_open_issue_number([{"number": 11}, {"number": 12}])
|
||||
|
||||
|
||||
class ExtractReferencesFromTextTests(unittest.TestCase):
|
||||
"""Cover lightweight reference extraction used by the text and JSON output."""
|
||||
|
||||
def test_extract_references_from_text_finds_issue_commit_and_path_mentions(self) -> None:
|
||||
"""The helper should retain the high-signal references needed for follow-up triage."""
|
||||
references = MODULE.extract_references_from_text(
|
||||
"See #123, commit abcdef1234567890, and GFramework.Core/Systems/Runner.cs for the failing path."
|
||||
)
|
||||
|
||||
self.assertEqual(references["issues"], ["#123"])
|
||||
self.assertEqual(references["commit_shas"], ["abcdef1234567890"])
|
||||
self.assertEqual(references["file_paths"], ["GFramework.Core/Systems/Runner.cs"])
|
||||
|
||||
|
||||
class BuildTriageHintsTests(unittest.TestCase):
|
||||
"""Cover next-action classification for non-bug issue flows."""
|
||||
|
||||
def test_build_triage_hints_routes_docs_issue_to_docs_topic_without_bug_style_clarification(self) -> None:
|
||||
"""Docs issues with a clear requested change should not be forced through bug-style clarification."""
|
||||
triage_hints = MODULE.build_triage_hints(
|
||||
{
|
||||
"title": "Update documentation landing page",
|
||||
"labels": ["docs"],
|
||||
"body": "The guide should explain the landing-page layout for new contributors.",
|
||||
},
|
||||
[],
|
||||
)
|
||||
|
||||
self.assertEqual(triage_hints["issue_type_candidates"][0], "docs")
|
||||
self.assertEqual(triage_hints["affected_active_topics"], [])
|
||||
self.assertFalse(triage_hints["information_flags"]["needs_clarification"])
|
||||
self.assertEqual(triage_hints["next_action"], "start-new-docs-topic-with-boot")
|
||||
|
||||
def test_build_triage_hints_routes_feature_issue_to_new_topic_when_request_is_clear(self) -> None:
|
||||
"""Feature requests with explicit desired behavior should stay actionable without fake bug repro gates."""
|
||||
triage_hints = MODULE.build_triage_hints(
|
||||
{
|
||||
"title": "Support release note previews",
|
||||
"labels": ["enhancement"],
|
||||
"body": "The workflow should support previewing generated notes before completion.",
|
||||
},
|
||||
[],
|
||||
)
|
||||
|
||||
self.assertEqual(triage_hints["issue_type_candidates"][0], "feature")
|
||||
self.assertEqual(triage_hints["affected_active_topics"], [])
|
||||
self.assertFalse(triage_hints["information_flags"]["needs_clarification"])
|
||||
self.assertEqual(triage_hints["next_action"], "start-new-topic-with-boot")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
71
.github/workflows/benchmark.yml
vendored
Normal file
71
.github/workflows/benchmark.yml
vendored
Normal file
@ -0,0 +1,71 @@
|
||||
# Copyright (c) 2025-2026 GeWuYou
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
name: Benchmark
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
benchmark_filter:
|
||||
description: '可选的 BenchmarkDotNet 过滤器;留空时仅执行 benchmark 项目 Release build'
|
||||
required: false
|
||||
default: ''
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
benchmark:
|
||||
name: Benchmark Build Or Run
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup .NET 10
|
||||
uses: actions/setup-dotnet@v5
|
||||
with:
|
||||
dotnet-version: 10.0.x
|
||||
|
||||
- name: Cache NuGet packages
|
||||
uses: actions/cache@v5
|
||||
with:
|
||||
path: |
|
||||
~/.nuget/packages
|
||||
~/.local/share/NuGet
|
||||
key: ${{ runner.os }}-nuget-benchmarks-${{ hashFiles('GFramework.Cqrs.Benchmarks/*.csproj', 'GFramework.Cqrs/*.csproj', 'GFramework.Cqrs.Abstractions/*.csproj', 'GFramework.Core/*.csproj', 'GFramework.Core.Abstractions/*.csproj', '**/nuget.config') }}
|
||||
|
||||
- name: Restore benchmark project
|
||||
run: dotnet restore GFramework.Cqrs.Benchmarks/GFramework.Cqrs.Benchmarks.csproj
|
||||
|
||||
- name: Build benchmark project
|
||||
run: dotnet build GFramework.Cqrs.Benchmarks/GFramework.Cqrs.Benchmarks.csproj -c Release --no-restore
|
||||
|
||||
- name: Report build-only mode
|
||||
if: ${{ inputs.benchmark_filter == '' }}
|
||||
run: |
|
||||
echo "No benchmark filter provided."
|
||||
echo "Workflow completed after validating the benchmark project build."
|
||||
|
||||
- name: Run filtered benchmarks
|
||||
if: ${{ inputs.benchmark_filter != '' }}
|
||||
env:
|
||||
BENCHMARK_FILTER: ${{ inputs.benchmark_filter }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
dotnet run --project GFramework.Cqrs.Benchmarks/GFramework.Cqrs.Benchmarks.csproj -c Release --no-build -- \
|
||||
--filter "$BENCHMARK_FILTER"
|
||||
|
||||
- name: Upload BenchmarkDotNet artifacts
|
||||
if: ${{ always() && inputs.benchmark_filter != '' }}
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: benchmark-artifacts
|
||||
path: |
|
||||
BenchmarkDotNet.Artifacts/**
|
||||
GFramework.Cqrs.Benchmarks/bin/Release/net10.0/BenchmarkDotNet.Artifacts/**
|
||||
if-no-files-found: ignore
|
||||
13
.github/workflows/ci.yml
vendored
13
.github/workflows/ci.yml
vendored
@ -155,6 +155,19 @@ jobs:
|
||||
- name: Build
|
||||
run: dotnet build GFramework.sln -c Release --no-restore
|
||||
|
||||
- name: Pack published modules
|
||||
run: |
|
||||
rm -rf ./packages
|
||||
dotnet pack GFramework.sln \
|
||||
-c Release \
|
||||
--no-build \
|
||||
--no-restore \
|
||||
-o ./packages \
|
||||
-p:IncludeSymbols=false
|
||||
|
||||
- name: Validate packed modules
|
||||
run: bash scripts/validate-packed-modules.sh ./packages
|
||||
|
||||
# 运行单元测试,输出TRX格式结果到TestResults目录
|
||||
# 顺序执行各测试项目,避免并发 dotnet test 进程导致“TRX 全绿但 step 仍返回失败”的假红状态
|
||||
- name: Test All Projects
|
||||
|
||||
36
.github/workflows/publish.yml
vendored
36
.github/workflows/publish.yml
vendored
@ -82,41 +82,7 @@ jobs:
|
||||
-p:IncludeSymbols=false
|
||||
|
||||
- name: Validate packed modules
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
expected_packages=(
|
||||
"GeWuYou.GFramework"
|
||||
"GeWuYou.GFramework.Core"
|
||||
"GeWuYou.GFramework.Core.Abstractions"
|
||||
"GeWuYou.GFramework.Core.SourceGenerators"
|
||||
"GeWuYou.GFramework.Cqrs"
|
||||
"GeWuYou.GFramework.Cqrs.Abstractions"
|
||||
"GeWuYou.GFramework.Cqrs.SourceGenerators"
|
||||
"GeWuYou.GFramework.Ecs.Arch"
|
||||
"GeWuYou.GFramework.Ecs.Arch.Abstractions"
|
||||
"GeWuYou.GFramework.Game"
|
||||
"GeWuYou.GFramework.Game.Abstractions"
|
||||
"GeWuYou.GFramework.Game.SourceGenerators"
|
||||
"GeWuYou.GFramework.Godot"
|
||||
"GeWuYou.GFramework.Godot.SourceGenerators"
|
||||
)
|
||||
|
||||
mapfile -t actual_packages < <(
|
||||
find ./packages -maxdepth 1 -type f -name '*.nupkg' -printf '%f\n' \
|
||||
| sed -E 's/\.[0-9][0-9A-Za-z.-]*\.nupkg$//' \
|
||||
| sort -u
|
||||
)
|
||||
|
||||
printf '%s\n' "${expected_packages[@]}" | sort > expected-packages.txt
|
||||
printf '%s\n' "${actual_packages[@]}" | sort > actual-packages.txt
|
||||
|
||||
echo "Expected packages:"
|
||||
cat expected-packages.txt
|
||||
echo "Actual packages:"
|
||||
cat actual-packages.txt
|
||||
|
||||
diff -u expected-packages.txt actual-packages.txt
|
||||
run: bash scripts/validate-packed-modules.sh ./packages
|
||||
|
||||
- name: Validate runtime-generator package boundaries
|
||||
run: python3 scripts/validate-runtime-generator-boundaries.py --package-dir ./packages
|
||||
|
||||
@ -8,9 +8,15 @@ using GFramework.Core.Abstractions.Systems;
|
||||
namespace GFramework.Core.Abstractions.Ioc;
|
||||
|
||||
/// <summary>
|
||||
/// 依赖注入容器接口,定义了服务注册、解析和管理的基本操作
|
||||
/// 依赖注入容器接口,定义服务注册、解析与生命周期管理的统一入口。
|
||||
/// </summary>
|
||||
public interface IIocContainer : IContextAware
|
||||
/// <remarks>
|
||||
/// 实现者必须在 <see cref="IDisposable.Dispose" /> 中释放容器拥有的根 <see cref="IServiceProvider" /> 及其
|
||||
/// 关联同步资源,并保证释放操作幂等。
|
||||
/// 容器一旦释放,后续任何注册、解析、查询或作用域创建调用都必须抛出
|
||||
/// <see cref="ObjectDisposedException" />,避免消费者继续访问失效的运行时状态。
|
||||
/// </remarks>
|
||||
public interface IIocContainer : IContextAware, IDisposable
|
||||
{
|
||||
#region Register Methods
|
||||
|
||||
|
||||
@ -3,6 +3,9 @@
|
||||
|
||||
using GFramework.Core.Ioc;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System.Reflection;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace GFramework.Core.Tests.Ioc;
|
||||
|
||||
@ -22,6 +25,18 @@ public class IocContainerLifetimeTests
|
||||
public Guid Id { get; } = Guid.NewGuid();
|
||||
}
|
||||
|
||||
private sealed class DisposableTestService : ITestService, IDisposable
|
||||
{
|
||||
public Guid Id { get; } = Guid.NewGuid();
|
||||
|
||||
public bool IsDisposed { get; private set; }
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
IsDisposed = true;
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void RegisterSingleton_Should_Return_Same_Instance()
|
||||
{
|
||||
@ -207,4 +222,112 @@ public class IocContainerLifetimeTests
|
||||
scope2.Dispose();
|
||||
scope3.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Dispose_Should_Dispose_Resolved_Singleton_And_Block_Further_Use()
|
||||
{
|
||||
// Arrange
|
||||
var container = new MicrosoftDiContainer();
|
||||
container.RegisterSingleton<DisposableTestService, DisposableTestService>();
|
||||
container.Freeze();
|
||||
var service = container.GetRequired<DisposableTestService>();
|
||||
|
||||
// Act
|
||||
container.Dispose();
|
||||
|
||||
// Assert
|
||||
Assert.That(service.IsDisposed, Is.True);
|
||||
Assert.Throws<ObjectDisposedException>(() => container.Get<DisposableTestService>());
|
||||
Assert.Throws<ObjectDisposedException>(() => container.CreateScope());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Dispose_Should_Be_Idempotent()
|
||||
{
|
||||
var container = new MicrosoftDiContainer();
|
||||
|
||||
Assert.DoesNotThrow(container.Dispose);
|
||||
Assert.DoesNotThrow(container.Dispose);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Dispose_Should_Be_Idempotent_When_Called_Concurrently()
|
||||
{
|
||||
var container = new MicrosoftDiContainer();
|
||||
var containerLock = GetContainerLock(container);
|
||||
var releasedGate = false;
|
||||
|
||||
containerLock.EnterWriteLock();
|
||||
try
|
||||
{
|
||||
var firstDisposeTask = Task.Run(container.Dispose);
|
||||
Thread.Sleep(50);
|
||||
var secondDisposeTask = Task.Run(container.Dispose);
|
||||
Thread.Sleep(50);
|
||||
|
||||
containerLock.ExitWriteLock();
|
||||
releasedGate = true;
|
||||
|
||||
Assert.That(async () => await Task.WhenAll(firstDisposeTask, secondDisposeTask).ConfigureAwait(false), Throws.Nothing);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (!releasedGate)
|
||||
{
|
||||
containerLock.ExitWriteLock();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Dispose_Should_Only_Attempt_Lock_Disposal_Once_When_Called_Concurrently()
|
||||
{
|
||||
var container = new MicrosoftDiContainer();
|
||||
var containerLock = GetContainerLock(container);
|
||||
var releasedGate = false;
|
||||
|
||||
containerLock.EnterWriteLock();
|
||||
try
|
||||
{
|
||||
var firstDisposeTask = Task.Run(container.Dispose);
|
||||
Thread.Sleep(50);
|
||||
var secondDisposeTask = Task.Run(container.Dispose);
|
||||
Thread.Sleep(50);
|
||||
|
||||
containerLock.ExitWriteLock();
|
||||
releasedGate = true;
|
||||
|
||||
Assert.That(async () => await Task.WhenAll(firstDisposeTask, secondDisposeTask).ConfigureAwait(false), Throws.Nothing);
|
||||
Assert.That(GetLockDisposalStarted(container), Is.EqualTo(1));
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (!releasedGate)
|
||||
{
|
||||
containerLock.ExitWriteLock();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 通过反射获取容器内部锁,用于构造可重复的并发释放竞态回归。
|
||||
/// </summary>
|
||||
private static ReaderWriterLockSlim GetContainerLock(MicrosoftDiContainer container)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(container);
|
||||
var lockField = typeof(MicrosoftDiContainer).GetField("_lock", BindingFlags.NonPublic | BindingFlags.Instance);
|
||||
Assert.That(lockField, Is.Not.Null);
|
||||
return (ReaderWriterLockSlim)lockField!.GetValue(container)!;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 读取锁销毁启动标记,验证并发释放路径不会重复执行底层锁销毁。
|
||||
/// </summary>
|
||||
private static int GetLockDisposalStarted(MicrosoftDiContainer container)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(container);
|
||||
var flagField = typeof(MicrosoftDiContainer).GetField("_lockDisposalStarted", BindingFlags.NonPublic | BindingFlags.Instance);
|
||||
Assert.That(flagField, Is.Not.Null);
|
||||
return (int)flagField!.GetValue(container)!;
|
||||
}
|
||||
}
|
||||
|
||||
@ -2,6 +2,8 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
using System.Reflection;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using GFramework.Core.Abstractions.Logging;
|
||||
using GFramework.Core.Ioc;
|
||||
using GFramework.Core.Logging;
|
||||
@ -760,4 +762,73 @@ public class MicrosoftDiContainerTests
|
||||
Assert.That(((IPrioritizedService)services[0]).Priority, Is.EqualTo(10));
|
||||
Assert.That(((IPrioritizedService)services[1]).Priority, Is.EqualTo(30));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 测试容器释放后会阻止后续注册与解析,避免 benchmark 或短生命周期宿主继续使用已回收状态。
|
||||
/// </summary>
|
||||
[Test]
|
||||
public void Dispose_Should_Block_Subsequent_Registration_And_Query_Operations()
|
||||
{
|
||||
_container.Dispose();
|
||||
|
||||
Assert.Throws<ObjectDisposedException>(() => _container.Register(new TestService()));
|
||||
Assert.Throws<ObjectDisposedException>(() => _container.Contains<TestService>());
|
||||
Assert.Throws<ObjectDisposedException>(() => _container.GetAll<TestService>());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 测试等待中的读取线程在容器释放后也会收到稳定的容器级释放异常,而不是底层锁异常。
|
||||
/// </summary>
|
||||
[Test]
|
||||
public async Task Dispose_Should_Translate_Waiting_Readers_To_Container_ObjectDisposedException()
|
||||
{
|
||||
_container.RegisterSingleton(new TestService());
|
||||
_container.Freeze();
|
||||
|
||||
var containerLock = GetContainerLock(_container);
|
||||
var releasedGate = false;
|
||||
using var queryStarted = new ManualResetEventSlim(false);
|
||||
|
||||
containerLock.EnterWriteLock();
|
||||
try
|
||||
{
|
||||
var queryTask = Task.Run(() =>
|
||||
{
|
||||
queryStarted.Set();
|
||||
return _container.Get<TestService>();
|
||||
});
|
||||
|
||||
Assert.That(queryStarted.Wait(TimeSpan.FromSeconds(1)), Is.True);
|
||||
|
||||
var disposeTask = Task.Run(_container.Dispose);
|
||||
Thread.Sleep(50);
|
||||
|
||||
containerLock.ExitWriteLock();
|
||||
releasedGate = true;
|
||||
|
||||
await disposeTask.ConfigureAwait(false);
|
||||
|
||||
var exception = Assert.ThrowsAsync<ObjectDisposedException>(async () => await queryTask.ConfigureAwait(false));
|
||||
Assert.That(exception, Is.Not.Null);
|
||||
Assert.That(exception!.ObjectName, Is.EqualTo(nameof(MicrosoftDiContainer)));
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (!releasedGate)
|
||||
{
|
||||
containerLock.ExitWriteLock();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 通过反射获取容器内部锁,用于构造可重复的并发释放竞态回归。
|
||||
/// </summary>
|
||||
private static ReaderWriterLockSlim GetContainerLock(MicrosoftDiContainer container)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(container);
|
||||
var lockField = typeof(MicrosoftDiContainer).GetField("_lock", BindingFlags.NonPublic | BindingFlags.Instance);
|
||||
Assert.That(lockField, Is.Not.Null);
|
||||
return (ReaderWriterLockSlim)lockField!.GetValue(container)!;
|
||||
}
|
||||
}
|
||||
|
||||
@ -2,6 +2,7 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
using System.Reflection;
|
||||
using System.Threading;
|
||||
using GFramework.Core.Abstractions.Bases;
|
||||
using GFramework.Core.Abstractions.Ioc;
|
||||
using GFramework.Core.Abstractions.Logging;
|
||||
@ -17,11 +18,143 @@ namespace GFramework.Core.Ioc;
|
||||
/// 将 Microsoft DI 包装为 IIocContainer 接口实现
|
||||
/// 提供线程安全的依赖注入容器功能
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 该适配器负责维护服务注册表、冻结后的根 <see cref="IServiceProvider" /> 以及并发访问控制。
|
||||
/// 容器释放后会阻止任何进一步访问,并统一抛出 <see cref="ObjectDisposedException" />,
|
||||
/// 以避免 benchmark、测试宿主或短生命周期架构误用失效的 DI 状态。
|
||||
/// </remarks>
|
||||
/// <param name="serviceCollection">可选的IServiceCollection实例,默认创建新的ServiceCollection</param>
|
||||
public class MicrosoftDiContainer(IServiceCollection? serviceCollection = null) : ContextAwareBase, IIocContainer
|
||||
{
|
||||
#region Helper Methods
|
||||
|
||||
/// <summary>
|
||||
/// 抛出统一的容器释放异常,避免并发路径泄露底层锁类型的实现细节。
|
||||
/// </summary>
|
||||
/// <exception cref="ObjectDisposedException">始终抛出,且对象名固定为当前容器类型。</exception>
|
||||
private void ThrowDisposedException()
|
||||
{
|
||||
const string objectName = nameof(MicrosoftDiContainer);
|
||||
_logger.Warn("Attempted to use a disposed MicrosoftDiContainer.");
|
||||
throw new ObjectDisposedException(objectName);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 检查容器是否已释放,避免访问已经失效的服务提供者与同步原语。
|
||||
/// </summary>
|
||||
/// <exception cref="ObjectDisposedException">当容器已释放时抛出。</exception>
|
||||
private void ThrowIfDisposed()
|
||||
{
|
||||
if (!_disposed) return;
|
||||
ThrowDisposedException();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 进入读锁,并在获取锁前后都复核释放状态,确保等待中的线程也能稳定得到容器级异常。
|
||||
/// </summary>
|
||||
/// <exception cref="ObjectDisposedException">当容器已释放,或等待期间被其他线程释放时抛出。</exception>
|
||||
private void EnterReadLockOrThrowDisposed()
|
||||
{
|
||||
var lockTaken = false;
|
||||
|
||||
try
|
||||
{
|
||||
_lock.EnterReadLock();
|
||||
lockTaken = true;
|
||||
}
|
||||
catch (ObjectDisposedException) when (_disposed)
|
||||
{
|
||||
ThrowDisposedException();
|
||||
}
|
||||
|
||||
if (!_disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (lockTaken)
|
||||
{
|
||||
_lock.ExitReadLock();
|
||||
}
|
||||
|
||||
ThrowDisposedException();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 进入写锁,并在获取锁前后都复核释放状态,确保等待中的线程不会泄露底层锁异常。
|
||||
/// </summary>
|
||||
/// <exception cref="ObjectDisposedException">当容器已释放,或等待期间被其他线程释放时抛出。</exception>
|
||||
private void EnterWriteLockOrThrowDisposed()
|
||||
{
|
||||
var lockTaken = false;
|
||||
|
||||
try
|
||||
{
|
||||
_lock.EnterWriteLock();
|
||||
lockTaken = true;
|
||||
}
|
||||
catch (ObjectDisposedException) when (_disposed)
|
||||
{
|
||||
ThrowDisposedException();
|
||||
}
|
||||
|
||||
if (!_disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (lockTaken)
|
||||
{
|
||||
_lock.ExitWriteLock();
|
||||
}
|
||||
|
||||
ThrowDisposedException();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 在释放标志已经对外可见后,等待遗留 waiter 退场,再尝试释放底层锁。
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 容器会先把 <see cref="_disposed" /> 置为 <see langword="true" /> 并退出写锁,
|
||||
/// 这样所有已在等待队列中的线程都能醒来并通过统一路径抛出容器级
|
||||
/// <see cref="ObjectDisposedException" />。只有当这些线程退场后,底层锁才可安全释放。
|
||||
/// 该步骤只允许一个释放调用者执行,避免并发 <see cref="Dispose" /> 重复销毁同一个
|
||||
/// <see cref="ReaderWriterLockSlim" /> 并破坏幂等契约。
|
||||
/// </remarks>
|
||||
private void DisposeLockWhenQuiescent()
|
||||
{
|
||||
if (Interlocked.CompareExchange(ref _lockDisposalStarted, 1, 0) != 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
const int maxDisposeSpinAttempts = 512;
|
||||
var spinWait = new SpinWait();
|
||||
|
||||
for (var attempt = 0; attempt < maxDisposeSpinAttempts; attempt++)
|
||||
{
|
||||
if (_lock.CurrentReadCount == 0 &&
|
||||
_lock.WaitingReadCount == 0 &&
|
||||
_lock.WaitingWriteCount == 0 &&
|
||||
_lock.WaitingUpgradeCount == 0)
|
||||
{
|
||||
try
|
||||
{
|
||||
_lock.Dispose();
|
||||
return;
|
||||
}
|
||||
catch (SynchronizationLockException)
|
||||
{
|
||||
// 等待中的线程刚好在本轮检查后切换状态;继续自旋直到锁真正静默。
|
||||
}
|
||||
}
|
||||
|
||||
spinWait.SpinOnce();
|
||||
}
|
||||
|
||||
_logger.Warn("MicrosoftDiContainer lock disposal was skipped because waiters did not quiesce in time.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 检查容器是否已冻结,如果已冻结则抛出异常
|
||||
/// 用于保护注册操作的安全性
|
||||
@ -57,6 +190,16 @@ public class MicrosoftDiContainer(IServiceCollection? serviceCollection = null)
|
||||
/// </summary>
|
||||
private volatile bool _frozen;
|
||||
|
||||
/// <summary>
|
||||
/// 容器释放状态标志,true 表示容器已释放,不允许继续访问。
|
||||
/// </summary>
|
||||
private volatile bool _disposed;
|
||||
|
||||
/// <summary>
|
||||
/// 标记底层读写锁的销毁流程是否已经启动,确保并发释放时最多只有一个线程尝试销毁锁实例。
|
||||
/// </summary>
|
||||
private int _lockDisposalStarted;
|
||||
|
||||
/// <summary>
|
||||
/// 读写锁,确保多线程环境下的线程安全操作
|
||||
/// </summary>
|
||||
@ -85,8 +228,9 @@ public class MicrosoftDiContainer(IServiceCollection? serviceCollection = null)
|
||||
/// <exception cref="InvalidOperationException">当容器已冻结或类型已被注册时抛出</exception>
|
||||
public void RegisterSingleton<T>(T instance)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
var type = typeof(T);
|
||||
_lock.EnterWriteLock();
|
||||
EnterWriteLockOrThrowDisposed();
|
||||
try
|
||||
{
|
||||
ThrowIfFrozen();
|
||||
@ -119,7 +263,8 @@ public class MicrosoftDiContainer(IServiceCollection? serviceCollection = null)
|
||||
where TImpl : class, TService
|
||||
where TService : class
|
||||
{
|
||||
_lock.EnterWriteLock();
|
||||
ThrowIfDisposed();
|
||||
EnterWriteLockOrThrowDisposed();
|
||||
try
|
||||
{
|
||||
ThrowIfFrozen();
|
||||
@ -142,7 +287,8 @@ public class MicrosoftDiContainer(IServiceCollection? serviceCollection = null)
|
||||
where TImpl : class, TService
|
||||
where TService : class
|
||||
{
|
||||
_lock.EnterWriteLock();
|
||||
ThrowIfDisposed();
|
||||
EnterWriteLockOrThrowDisposed();
|
||||
try
|
||||
{
|
||||
ThrowIfFrozen();
|
||||
@ -165,7 +311,8 @@ public class MicrosoftDiContainer(IServiceCollection? serviceCollection = null)
|
||||
where TImpl : class, TService
|
||||
where TService : class
|
||||
{
|
||||
_lock.EnterWriteLock();
|
||||
ThrowIfDisposed();
|
||||
EnterWriteLockOrThrowDisposed();
|
||||
try
|
||||
{
|
||||
ThrowIfFrozen();
|
||||
@ -187,10 +334,11 @@ public class MicrosoftDiContainer(IServiceCollection? serviceCollection = null)
|
||||
/// <exception cref="InvalidOperationException">当容器已冻结时抛出</exception>
|
||||
public void RegisterPlurality(object instance)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
var concreteType = instance.GetType();
|
||||
var interfaces = concreteType.GetInterfaces();
|
||||
|
||||
_lock.EnterWriteLock();
|
||||
EnterWriteLockOrThrowDisposed();
|
||||
try
|
||||
{
|
||||
ThrowIfFrozen();
|
||||
@ -219,7 +367,8 @@ public class MicrosoftDiContainer(IServiceCollection? serviceCollection = null)
|
||||
/// </summary>
|
||||
public void RegisterPlurality<T>() where T : class
|
||||
{
|
||||
_lock.EnterWriteLock();
|
||||
ThrowIfDisposed();
|
||||
EnterWriteLockOrThrowDisposed();
|
||||
try
|
||||
{
|
||||
ThrowIfFrozen();
|
||||
@ -262,7 +411,8 @@ public class MicrosoftDiContainer(IServiceCollection? serviceCollection = null)
|
||||
/// <exception cref="InvalidOperationException">当容器已冻结时抛出</exception>
|
||||
public void Register<T>(T instance)
|
||||
{
|
||||
_lock.EnterWriteLock();
|
||||
ThrowIfDisposed();
|
||||
EnterWriteLockOrThrowDisposed();
|
||||
try
|
||||
{
|
||||
ThrowIfFrozen();
|
||||
@ -284,7 +434,8 @@ public class MicrosoftDiContainer(IServiceCollection? serviceCollection = null)
|
||||
/// <exception cref="InvalidOperationException">当容器已冻结时抛出</exception>
|
||||
public void Register(Type type, object instance)
|
||||
{
|
||||
_lock.EnterWriteLock();
|
||||
ThrowIfDisposed();
|
||||
EnterWriteLockOrThrowDisposed();
|
||||
try
|
||||
{
|
||||
ThrowIfFrozen();
|
||||
@ -307,7 +458,8 @@ public class MicrosoftDiContainer(IServiceCollection? serviceCollection = null)
|
||||
public void RegisterFactory<TService>(
|
||||
Func<IServiceProvider, TService> factory) where TService : class
|
||||
{
|
||||
_lock.EnterWriteLock();
|
||||
ThrowIfDisposed();
|
||||
EnterWriteLockOrThrowDisposed();
|
||||
try
|
||||
{
|
||||
ThrowIfFrozen();
|
||||
@ -328,7 +480,8 @@ public class MicrosoftDiContainer(IServiceCollection? serviceCollection = null)
|
||||
/// <typeparam name="TBehavior">行为类型,必须是引用类型</typeparam>
|
||||
public void RegisterCqrsPipelineBehavior<TBehavior>() where TBehavior : class
|
||||
{
|
||||
_lock.EnterWriteLock();
|
||||
ThrowIfDisposed();
|
||||
EnterWriteLockOrThrowDisposed();
|
||||
try
|
||||
{
|
||||
ThrowIfFrozen();
|
||||
@ -392,6 +545,7 @@ public class MicrosoftDiContainer(IServiceCollection? serviceCollection = null)
|
||||
public void RegisterCqrsHandlersFromAssemblies(IEnumerable<Assembly> assemblies)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(assemblies);
|
||||
ThrowIfDisposed();
|
||||
var assemblyArray = assemblies.ToArray();
|
||||
foreach (var assembly in assemblyArray)
|
||||
{
|
||||
@ -401,7 +555,7 @@ public class MicrosoftDiContainer(IServiceCollection? serviceCollection = null)
|
||||
}
|
||||
}
|
||||
|
||||
_lock.EnterWriteLock();
|
||||
EnterWriteLockOrThrowDisposed();
|
||||
try
|
||||
{
|
||||
ThrowIfFrozen();
|
||||
@ -419,7 +573,8 @@ public class MicrosoftDiContainer(IServiceCollection? serviceCollection = null)
|
||||
/// <param name="configurator">服务配置委托</param>
|
||||
public void ExecuteServicesHook(Action<IServiceCollection>? configurator = null)
|
||||
{
|
||||
_lock.EnterWriteLock();
|
||||
ThrowIfDisposed();
|
||||
EnterWriteLockOrThrowDisposed();
|
||||
try
|
||||
{
|
||||
ThrowIfFrozen();
|
||||
@ -464,7 +619,8 @@ public class MicrosoftDiContainer(IServiceCollection? serviceCollection = null)
|
||||
/// <returns>服务实例或null</returns>
|
||||
public T? Get<T>() where T : class
|
||||
{
|
||||
_lock.EnterReadLock();
|
||||
ThrowIfDisposed();
|
||||
EnterReadLockOrThrowDisposed();
|
||||
try
|
||||
{
|
||||
if (_provider == null)
|
||||
@ -503,7 +659,8 @@ public class MicrosoftDiContainer(IServiceCollection? serviceCollection = null)
|
||||
/// <returns>服务实例或null</returns>
|
||||
public object? Get(Type type)
|
||||
{
|
||||
_lock.EnterReadLock();
|
||||
ThrowIfDisposed();
|
||||
EnterReadLockOrThrowDisposed();
|
||||
try
|
||||
{
|
||||
if (_provider == null)
|
||||
@ -593,7 +750,8 @@ public class MicrosoftDiContainer(IServiceCollection? serviceCollection = null)
|
||||
/// <returns>只读的服务实例列表</returns>
|
||||
public IReadOnlyList<T> GetAll<T>() where T : class
|
||||
{
|
||||
_lock.EnterReadLock();
|
||||
ThrowIfDisposed();
|
||||
EnterReadLockOrThrowDisposed();
|
||||
try
|
||||
{
|
||||
if (_provider == null)
|
||||
@ -620,8 +778,9 @@ public class MicrosoftDiContainer(IServiceCollection? serviceCollection = null)
|
||||
public IReadOnlyList<object> GetAll(Type type)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(type);
|
||||
ThrowIfDisposed();
|
||||
|
||||
_lock.EnterReadLock();
|
||||
EnterReadLockOrThrowDisposed();
|
||||
try
|
||||
{
|
||||
if (_provider == null)
|
||||
@ -750,6 +909,7 @@ public class MicrosoftDiContainer(IServiceCollection? serviceCollection = null)
|
||||
/// <returns>排序后的只读服务实例列表</returns>
|
||||
public IReadOnlyList<T> GetAllSorted<T>(Comparison<T> comparison) where T : class
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
var list = GetAll<T>().ToList();
|
||||
list.Sort(comparison);
|
||||
return list;
|
||||
@ -816,7 +976,8 @@ public class MicrosoftDiContainer(IServiceCollection? serviceCollection = null)
|
||||
/// <returns>true表示包含该类型实例,false表示不包含</returns>
|
||||
public bool Contains<T>() where T : class
|
||||
{
|
||||
_lock.EnterReadLock();
|
||||
ThrowIfDisposed();
|
||||
EnterReadLockOrThrowDisposed();
|
||||
try
|
||||
{
|
||||
if (_provider == null)
|
||||
@ -838,7 +999,8 @@ public class MicrosoftDiContainer(IServiceCollection? serviceCollection = null)
|
||||
/// <returns>true表示包含该实例,false表示不包含</returns>
|
||||
public bool ContainsInstance(object instance)
|
||||
{
|
||||
_lock.EnterReadLock();
|
||||
ThrowIfDisposed();
|
||||
EnterReadLockOrThrowDisposed();
|
||||
try
|
||||
{
|
||||
return _registeredInstances.Contains(instance);
|
||||
@ -855,7 +1017,8 @@ public class MicrosoftDiContainer(IServiceCollection? serviceCollection = null)
|
||||
/// </summary>
|
||||
public void Clear()
|
||||
{
|
||||
_lock.EnterWriteLock();
|
||||
ThrowIfDisposed();
|
||||
EnterWriteLockOrThrowDisposed();
|
||||
try
|
||||
{
|
||||
// 冻结的容器不允许清空操作
|
||||
@ -865,9 +1028,11 @@ public class MicrosoftDiContainer(IServiceCollection? serviceCollection = null)
|
||||
return;
|
||||
}
|
||||
|
||||
// 未冻结的容器不会构建根 ServiceProvider,因此这里仅重置注册状态即可。
|
||||
GetServicesUnsafe.Clear();
|
||||
_registeredInstances.Clear();
|
||||
_provider = null;
|
||||
_frozen = false;
|
||||
_logger.Info("Container cleared");
|
||||
}
|
||||
finally
|
||||
@ -882,7 +1047,8 @@ public class MicrosoftDiContainer(IServiceCollection? serviceCollection = null)
|
||||
/// </summary>
|
||||
public void Freeze()
|
||||
{
|
||||
_lock.EnterWriteLock();
|
||||
ThrowIfDisposed();
|
||||
EnterWriteLockOrThrowDisposed();
|
||||
try
|
||||
{
|
||||
// 防止重复冻结
|
||||
@ -917,7 +1083,8 @@ public class MicrosoftDiContainer(IServiceCollection? serviceCollection = null)
|
||||
/// <exception cref="InvalidOperationException">当容器未冻结时抛出</exception>
|
||||
public IServiceScope CreateScope()
|
||||
{
|
||||
_lock.EnterReadLock();
|
||||
ThrowIfDisposed();
|
||||
EnterReadLockOrThrowDisposed();
|
||||
try
|
||||
{
|
||||
// 在锁内检查,避免竞态条件
|
||||
@ -938,5 +1105,58 @@ public class MicrosoftDiContainer(IServiceCollection? serviceCollection = null)
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 释放容器持有的服务提供者、注册状态和同步原语。
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 冻结后的根 <see cref="IServiceProvider" /> 会拥有 DI 创建的单例与作用域根缓存,因此 benchmark、
|
||||
/// 测试宿主或短生命周期架构在结束时需要显式释放容器,避免这些对象与内部
|
||||
/// <see cref="ReaderWriterLockSlim" /> 一起滞留。
|
||||
/// 释放是幂等的;首次释放后所有后续访问都会抛出 <see cref="ObjectDisposedException" />。
|
||||
/// </remarks>
|
||||
public void Dispose()
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var lockTaken = false;
|
||||
|
||||
try
|
||||
{
|
||||
try
|
||||
{
|
||||
_lock.EnterWriteLock();
|
||||
lockTaken = true;
|
||||
}
|
||||
catch (ObjectDisposedException) when (_disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (_disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_disposed = true;
|
||||
(_provider as IDisposable)?.Dispose();
|
||||
_provider = null;
|
||||
GetServicesUnsafe.Clear();
|
||||
_registeredInstances.Clear();
|
||||
_frozen = false;
|
||||
_logger.Info("IOC Container disposed");
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (lockTaken)
|
||||
{
|
||||
_lock.ExitWriteLock();
|
||||
DisposeLockWhenQuiescent();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
|
||||
71
GFramework.Cqrs.Benchmarks/CustomColumn.cs
Normal file
71
GFramework.Cqrs.Benchmarks/CustomColumn.cs
Normal file
@ -0,0 +1,71 @@
|
||||
// Copyright (c) 2025-2026 GeWuYou
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
using BenchmarkDotNet.Columns;
|
||||
using BenchmarkDotNet.Reports;
|
||||
using BenchmarkDotNet.Running;
|
||||
using System;
|
||||
|
||||
namespace GFramework.Cqrs.Benchmarks;
|
||||
|
||||
/// <summary>
|
||||
/// 为 CQRS benchmark 结果补充可读的场景标签列。
|
||||
/// </summary>
|
||||
/// <param name="columnName">列名。</param>
|
||||
/// <param name="getValue">从 benchmark case 提取列值的委托。</param>
|
||||
public sealed class CustomColumn(string columnName, Func<Summary, BenchmarkCase, string> getValue) : IColumn
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public string Id => $"{nameof(CustomColumn)}.{ColumnName}";
|
||||
|
||||
/// <inheritdoc />
|
||||
public string ColumnName { get; } = columnName;
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool AlwaysShow => true;
|
||||
|
||||
/// <inheritdoc />
|
||||
public ColumnCategory Category => ColumnCategory.Params;
|
||||
|
||||
/// <inheritdoc />
|
||||
public int PriorityInCategory => 0;
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool IsNumeric => false;
|
||||
|
||||
/// <inheritdoc />
|
||||
public UnitType UnitType => UnitType.Dimensionless;
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Legend => $"Custom '{ColumnName}' tag column";
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool IsDefault(Summary summary, BenchmarkCase benchmarkCase)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool IsAvailable(Summary summary)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public string GetValue(Summary summary, BenchmarkCase benchmarkCase)
|
||||
{
|
||||
return getValue(summary, benchmarkCase);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public string GetValue(Summary summary, BenchmarkCase benchmarkCase, SummaryStyle style)
|
||||
{
|
||||
return GetValue(summary, benchmarkCase);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public override string ToString()
|
||||
{
|
||||
return ColumnName;
|
||||
}
|
||||
}
|
||||
33
GFramework.Cqrs.Benchmarks/GFramework.Cqrs.Benchmarks.csproj
Normal file
33
GFramework.Cqrs.Benchmarks/GFramework.Cqrs.Benchmarks.csproj
Normal file
@ -0,0 +1,33 @@
|
||||
<!--
|
||||
Copyright (c) 2025-2026 GeWuYou
|
||||
SPDX-License-Identifier: Apache-2.0
|
||||
-->
|
||||
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>disable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<GenerateDocumentationFile>false</GenerateDocumentationFile>
|
||||
<!-- Keep benchmark infrastructure out of the published NuGet package set. -->
|
||||
<IsPackable>false</IsPackable>
|
||||
<GeneratePackageOnBuild>false</GeneratePackageOnBuild>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="BenchmarkDotNet" Version="0.15.8" />
|
||||
<PackageReference Include="MediatR" Version="13.1.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="10.0.7" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging" Version="10.0.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\GFramework.Cqrs.Abstractions\GFramework.Cqrs.Abstractions.csproj" />
|
||||
<ProjectReference Include="..\GFramework.Cqrs\GFramework.Cqrs.csproj" />
|
||||
<ProjectReference Include="..\GFramework.Core.Abstractions\GFramework.Core.Abstractions.csproj" />
|
||||
<ProjectReference Include="..\GFramework.Core\GFramework.Core.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@ -0,0 +1,57 @@
|
||||
// Copyright (c) 2025-2026 GeWuYou
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Runtime.ExceptionServices;
|
||||
|
||||
namespace GFramework.Cqrs.Benchmarks.Messaging;
|
||||
|
||||
/// <summary>
|
||||
/// 统一处理 benchmark 宿主的资源释放,避免前一个 <see cref="IDisposable" /> 抛错后中断后续清理。
|
||||
/// </summary>
|
||||
internal static class BenchmarkCleanupHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// 按顺序释放一组 benchmark 资源,并在全部资源都尝试释放后再回抛异常。
|
||||
/// </summary>
|
||||
/// <param name="disposables">当前 benchmark 宿主拥有并负责释放的资源。</param>
|
||||
/// <exception cref="Exception">
|
||||
/// 当且仅当至少一个资源释放失败时抛出。
|
||||
/// 单个失败会回抛原始异常,多个失败会聚合为 <see cref="AggregateException" />。
|
||||
/// </exception>
|
||||
public static void DisposeAll(params IDisposable?[] disposables)
|
||||
{
|
||||
List<Exception>? exceptions = null;
|
||||
|
||||
foreach (var disposable in disposables)
|
||||
{
|
||||
if (disposable is null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
disposable.Dispose();
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
exceptions ??= [];
|
||||
exceptions.Add(exception);
|
||||
}
|
||||
}
|
||||
|
||||
if (exceptions is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (exceptions.Count == 1)
|
||||
{
|
||||
ExceptionDispatchInfo.Capture(exceptions[0]).Throw();
|
||||
}
|
||||
|
||||
throw new AggregateException("One or more benchmark resources failed to dispose cleanly.", exceptions);
|
||||
}
|
||||
}
|
||||
17
GFramework.Cqrs.Benchmarks/Messaging/BenchmarkContext.cs
Normal file
17
GFramework.Cqrs.Benchmarks/Messaging/BenchmarkContext.cs
Normal file
@ -0,0 +1,17 @@
|
||||
// Copyright (c) 2025-2026 GeWuYou
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
using GFramework.Cqrs.Abstractions.Cqrs;
|
||||
|
||||
namespace GFramework.Cqrs.Benchmarks.Messaging;
|
||||
|
||||
/// <summary>
|
||||
/// 为纯 runtime benchmark 提供最小 CQRS 上下文标记,避免把完整架构上下文初始化成本混入 steady-state dispatch。
|
||||
/// </summary>
|
||||
internal sealed class BenchmarkContext : ICqrsContext
|
||||
{
|
||||
/// <summary>
|
||||
/// 共享的最小 CQRS 上下文实例。
|
||||
/// </summary>
|
||||
public static BenchmarkContext Instance { get; } = new();
|
||||
}
|
||||
@ -0,0 +1,49 @@
|
||||
// Copyright (c) 2025-2026 GeWuYou
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
using System;
|
||||
using System.Reflection;
|
||||
|
||||
namespace GFramework.Cqrs.Benchmarks.Messaging;
|
||||
|
||||
/// <summary>
|
||||
/// 提供 benchmark 共享的 dispatcher 静态缓存清理入口。
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// `GFramework.Cqrs` runtime 会把反射绑定与 generated invoker 元数据缓存在静态字段中。
|
||||
/// benchmark 需要在同一进程内重复比较 cold-start、reflection 与 generated 路径时,
|
||||
/// 显式清空这些缓存,避免前一组 benchmark 污染后续结果。
|
||||
/// </remarks>
|
||||
internal static class BenchmarkDispatcherCacheHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// 清空 dispatcher 上与 benchmark 对照相关的全部静态缓存。
|
||||
/// </summary>
|
||||
public static void ClearDispatcherCaches()
|
||||
{
|
||||
ClearDispatcherCache("NotificationDispatchBindings");
|
||||
ClearDispatcherCache("RequestDispatchBindings");
|
||||
ClearDispatcherCache("StreamDispatchBindings");
|
||||
ClearDispatcherCache("GeneratedRequestInvokers");
|
||||
ClearDispatcherCache("GeneratedStreamInvokers");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 通过反射定位并清空 dispatcher 的指定缓存字段。
|
||||
/// </summary>
|
||||
/// <param name="fieldName">要清理的静态缓存字段名。</param>
|
||||
/// <exception cref="InvalidOperationException">指定缓存字段不存在、返回空值或未暴露清理方法。</exception>
|
||||
internal static void ClearDispatcherCache(string fieldName)
|
||||
{
|
||||
var field = typeof(GFramework.Cqrs.CqrsRuntimeFactory).Assembly
|
||||
.GetType("GFramework.Cqrs.Internal.CqrsDispatcher", throwOnError: true)!
|
||||
.GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Static)
|
||||
?? throw new InvalidOperationException($"Missing dispatcher cache field {fieldName}.");
|
||||
var cache = field.GetValue(null)
|
||||
?? throw new InvalidOperationException($"Dispatcher cache field {fieldName} returned null.");
|
||||
var clearMethod = cache.GetType().GetMethod("Clear", BindingFlags.Public | BindingFlags.Instance)
|
||||
?? throw new InvalidOperationException(
|
||||
$"Dispatcher cache field {fieldName} does not expose a Clear method.");
|
||||
_ = clearMethod.Invoke(cache, null);
|
||||
}
|
||||
}
|
||||
93
GFramework.Cqrs.Benchmarks/Messaging/BenchmarkHostFactory.cs
Normal file
93
GFramework.Cqrs.Benchmarks/Messaging/BenchmarkHostFactory.cs
Normal file
@ -0,0 +1,93 @@
|
||||
// Copyright (c) 2025-2026 GeWuYou
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
using System;
|
||||
using System.Linq;
|
||||
using GFramework.Core.Ioc;
|
||||
using GFramework.Cqrs.Abstractions.Cqrs;
|
||||
using MediatR;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace GFramework.Cqrs.Benchmarks.Messaging;
|
||||
|
||||
/// <summary>
|
||||
/// 为 benchmark 场景构建最小且可重复的 GFramework / MediatR 对照宿主。
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 基准工程里的对照目标是“相同消息合同下的调度差异”,而不是程序集扫描量或容器生命周期差异。
|
||||
/// 因此这里统一封装两类宿主的最小注册形状,确保:
|
||||
/// 1. GFramework 容器在首次发送前已经冻结,可真实解析按类型注册的 handler;
|
||||
/// 2. MediatR 只扫描当前 benchmark 明确拥有的 handler / behavior 类型,避免整个程序集的额外注册污染结果。
|
||||
/// </remarks>
|
||||
internal static class BenchmarkHostFactory
|
||||
{
|
||||
/// <summary>
|
||||
/// 创建一个已经冻结的 GFramework benchmark 容器。
|
||||
/// </summary>
|
||||
/// <param name="configure">向容器写入 benchmark 所需 handler / pipeline 的注册动作。</param>
|
||||
/// <returns>已冻结、可立即用于 runtime 分发的容器。</returns>
|
||||
internal static MicrosoftDiContainer CreateFrozenGFrameworkContainer(Action<MicrosoftDiContainer> configure)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(configure);
|
||||
|
||||
var container = new MicrosoftDiContainer();
|
||||
configure(container);
|
||||
container.Freeze();
|
||||
return container;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 创建只承载当前 benchmark handler 集合的最小 MediatR 宿主。
|
||||
/// </summary>
|
||||
/// <param name="configure">补充当前场景的显式服务注册,例如手工单例 handler 或 pipeline 行为。</param>
|
||||
/// <param name="handlerAssemblyMarkerType">用于限定扫描程序集的标记类型。</param>
|
||||
/// <param name="handlerTypeFilter">
|
||||
/// 仅允许当前 benchmark 场景需要的 handler / behavior 类型通过扫描;
|
||||
/// 这样可保留 `AddMediatR` 的正常装配路径,同时避免整个基准程序集里的其他 handler 被一并注册。
|
||||
/// </param>
|
||||
/// <param name="lifetime">当前 benchmark 希望 MediatR 使用的默认注册生命周期。</param>
|
||||
/// <returns>只承载当前 benchmark 场景所需服务的 DI 宿主。</returns>
|
||||
internal static ServiceProvider CreateMediatRServiceProvider(
|
||||
Action<IServiceCollection>? configure,
|
||||
Type handlerAssemblyMarkerType,
|
||||
Func<Type, bool> handlerTypeFilter,
|
||||
ServiceLifetime lifetime = ServiceLifetime.Transient)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(handlerAssemblyMarkerType);
|
||||
ArgumentNullException.ThrowIfNull(handlerTypeFilter);
|
||||
|
||||
var services = new ServiceCollection();
|
||||
services.AddLogging(static builder =>
|
||||
Microsoft.Extensions.Logging.FilterLoggingBuilderExtensions.AddFilter(
|
||||
builder,
|
||||
"LuckyPennySoftware.MediatR.License",
|
||||
Microsoft.Extensions.Logging.LogLevel.None));
|
||||
|
||||
configure?.Invoke(services);
|
||||
|
||||
services.AddMediatR(options =>
|
||||
{
|
||||
options.Lifetime = lifetime;
|
||||
options.TypeEvaluator = handlerTypeFilter;
|
||||
options.RegisterServicesFromAssembly(handlerAssemblyMarkerType.Assembly);
|
||||
});
|
||||
|
||||
return services.BuildServiceProvider();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 判断某个类型是否正好实现了指定的闭合或开放 MediatR 合同。
|
||||
/// </summary>
|
||||
/// <param name="candidateType">待判断类型。</param>
|
||||
/// <param name="openGenericContract">目标开放泛型合同,例如 <see cref="MediatR.IRequestHandler{TRequest,TResponse}" />。</param>
|
||||
/// <returns>命中任一实现接口时返回 <see langword="true" />;否则返回 <see langword="false" />。</returns>
|
||||
internal static bool ImplementsOpenGenericContract(Type candidateType, Type openGenericContract)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(candidateType);
|
||||
ArgumentNullException.ThrowIfNull(openGenericContract);
|
||||
|
||||
return candidateType.GetInterfaces().Any(interfaceType =>
|
||||
interfaceType.IsGenericType &&
|
||||
interfaceType.GetGenericTypeDefinition() == openGenericContract);
|
||||
}
|
||||
}
|
||||
35
GFramework.Cqrs.Benchmarks/Messaging/Fixture.cs
Normal file
35
GFramework.Cqrs.Benchmarks/Messaging/Fixture.cs
Normal file
@ -0,0 +1,35 @@
|
||||
// Copyright (c) 2025-2026 GeWuYou
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
using BenchmarkDotNet.Loggers;
|
||||
using System;
|
||||
|
||||
namespace GFramework.Cqrs.Benchmarks.Messaging;
|
||||
|
||||
/// <summary>
|
||||
/// 为 CQRS benchmark 运行打印并验证当前场景配置,避免矩阵配置与实际运行环境漂移。
|
||||
/// </summary>
|
||||
internal static class Fixture
|
||||
{
|
||||
/// <summary>
|
||||
/// 输出当前 benchmark 配置并验证关键环境变量。
|
||||
/// </summary>
|
||||
/// <param name="scenario">当前 benchmark 场景名称。</param>
|
||||
/// <param name="handlerCount">当前场景的处理器数量。</param>
|
||||
/// <param name="pipelineCount">当前场景的 pipeline 行为数量。</param>
|
||||
public static void Setup(string scenario, int handlerCount, int pipelineCount)
|
||||
{
|
||||
ConsoleLogger.Default.WriteLineHeader("GFramework.Cqrs benchmark config");
|
||||
ConsoleLogger.Default.WriteLineInfo($"Scenario = {scenario}");
|
||||
ConsoleLogger.Default.WriteLineInfo($"HandlerCount = {handlerCount}");
|
||||
ConsoleLogger.Default.WriteLineInfo($"PipelineCount = {pipelineCount}");
|
||||
|
||||
var environmentScenario = Environment.GetEnvironmentVariable("GFRAMEWORK_CQRS_BENCHMARK_SCENARIO");
|
||||
if (!string.IsNullOrWhiteSpace(environmentScenario) &&
|
||||
!string.Equals(environmentScenario, scenario, StringComparison.Ordinal))
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
$"Scenario mismatch. Expected '{environmentScenario}', actual '{scenario}'.");
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,98 @@
|
||||
// Copyright (c) 2025-2026 GeWuYou
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Reflection;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using GFramework.Core.Abstractions.Logging;
|
||||
using GFramework.Cqrs.Abstractions.Cqrs;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace GFramework.Cqrs.Benchmarks.Messaging;
|
||||
|
||||
/// <summary>
|
||||
/// 为 benchmark 手写一个“生成后等价物” registry,用于驱动真实的 generated invoker provider 运行时接线路径。
|
||||
/// </summary>
|
||||
public sealed class GeneratedRequestInvokerBenchmarkRegistry :
|
||||
GFramework.Cqrs.ICqrsHandlerRegistry,
|
||||
GFramework.Cqrs.ICqrsRequestInvokerProvider,
|
||||
GFramework.Cqrs.IEnumeratesCqrsRequestInvokerDescriptors
|
||||
{
|
||||
private static readonly GFramework.Cqrs.CqrsRequestInvokerDescriptor Descriptor =
|
||||
new(
|
||||
typeof(IRequestHandler<
|
||||
RequestInvokerBenchmarks.GeneratedBenchmarkRequest,
|
||||
RequestInvokerBenchmarks.GeneratedBenchmarkResponse>),
|
||||
typeof(GeneratedRequestInvokerBenchmarkRegistry).GetMethod(
|
||||
nameof(InvokeGeneratedRequestHandler),
|
||||
BindingFlags.Public | BindingFlags.Static)
|
||||
?? throw new InvalidOperationException("Missing generated request invoker benchmark method."));
|
||||
|
||||
private static readonly IReadOnlyList<GFramework.Cqrs.CqrsRequestInvokerDescriptorEntry> Descriptors =
|
||||
[
|
||||
new GFramework.Cqrs.CqrsRequestInvokerDescriptorEntry(
|
||||
typeof(RequestInvokerBenchmarks.GeneratedBenchmarkRequest),
|
||||
typeof(RequestInvokerBenchmarks.GeneratedBenchmarkResponse),
|
||||
Descriptor)
|
||||
];
|
||||
|
||||
/// <summary>
|
||||
/// 将 generated benchmark request handler 注册到目标服务集合。
|
||||
/// </summary>
|
||||
public void Register(IServiceCollection services, ILogger logger)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(services);
|
||||
ArgumentNullException.ThrowIfNull(logger);
|
||||
|
||||
services.AddTransient(
|
||||
typeof(IRequestHandler<
|
||||
RequestInvokerBenchmarks.GeneratedBenchmarkRequest,
|
||||
RequestInvokerBenchmarks.GeneratedBenchmarkResponse>),
|
||||
typeof(RequestInvokerBenchmarks.GeneratedBenchmarkRequestHandler));
|
||||
logger.Debug("Registered generated request invoker benchmark handler.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 返回当前 provider 暴露的全部 generated request invoker 描述符。
|
||||
/// </summary>
|
||||
public IReadOnlyList<GFramework.Cqrs.CqrsRequestInvokerDescriptorEntry> GetDescriptors()
|
||||
{
|
||||
return Descriptors;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 为目标请求/响应类型对返回 generated request invoker 描述符。
|
||||
/// </summary>
|
||||
public bool TryGetDescriptor(
|
||||
Type requestType,
|
||||
Type responseType,
|
||||
out GFramework.Cqrs.CqrsRequestInvokerDescriptor? descriptor)
|
||||
{
|
||||
if (requestType == typeof(RequestInvokerBenchmarks.GeneratedBenchmarkRequest) &&
|
||||
responseType == typeof(RequestInvokerBenchmarks.GeneratedBenchmarkResponse))
|
||||
{
|
||||
descriptor = Descriptor;
|
||||
return true;
|
||||
}
|
||||
|
||||
descriptor = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 模拟 generated invoker provider 产出的开放静态调用入口。
|
||||
/// </summary>
|
||||
public static ValueTask<RequestInvokerBenchmarks.GeneratedBenchmarkResponse> InvokeGeneratedRequestHandler(
|
||||
object handler,
|
||||
object request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var typedHandler = (IRequestHandler<
|
||||
RequestInvokerBenchmarks.GeneratedBenchmarkRequest,
|
||||
RequestInvokerBenchmarks.GeneratedBenchmarkResponse>)handler;
|
||||
var typedRequest = (RequestInvokerBenchmarks.GeneratedBenchmarkRequest)request;
|
||||
return typedHandler.Handle(typedRequest, cancellationToken);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,94 @@
|
||||
// Copyright (c) 2025-2026 GeWuYou
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Reflection;
|
||||
using System.Threading;
|
||||
using GFramework.Core.Abstractions.Logging;
|
||||
using GFramework.Cqrs.Abstractions.Cqrs;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace GFramework.Cqrs.Benchmarks.Messaging;
|
||||
|
||||
/// <summary>
|
||||
/// 为 benchmark 手写一个“生成后等价物” stream registry,用于驱动真实的 generated stream invoker provider 运行时接线路径。
|
||||
/// </summary>
|
||||
public sealed class GeneratedStreamInvokerBenchmarkRegistry :
|
||||
GFramework.Cqrs.ICqrsHandlerRegistry,
|
||||
GFramework.Cqrs.ICqrsStreamInvokerProvider,
|
||||
GFramework.Cqrs.IEnumeratesCqrsStreamInvokerDescriptors
|
||||
{
|
||||
private static readonly GFramework.Cqrs.CqrsStreamInvokerDescriptor Descriptor =
|
||||
new(
|
||||
typeof(IStreamRequestHandler<
|
||||
StreamInvokerBenchmarks.GeneratedBenchmarkStreamRequest,
|
||||
StreamInvokerBenchmarks.GeneratedBenchmarkResponse>),
|
||||
typeof(GeneratedStreamInvokerBenchmarkRegistry).GetMethod(
|
||||
nameof(InvokeGeneratedStreamHandler),
|
||||
BindingFlags.Public | BindingFlags.Static)
|
||||
?? throw new InvalidOperationException("Missing generated stream invoker benchmark method."));
|
||||
|
||||
private static readonly IReadOnlyList<GFramework.Cqrs.CqrsStreamInvokerDescriptorEntry> Descriptors =
|
||||
[
|
||||
new GFramework.Cqrs.CqrsStreamInvokerDescriptorEntry(
|
||||
typeof(StreamInvokerBenchmarks.GeneratedBenchmarkStreamRequest),
|
||||
typeof(StreamInvokerBenchmarks.GeneratedBenchmarkResponse),
|
||||
Descriptor)
|
||||
];
|
||||
|
||||
/// <summary>
|
||||
/// 将 generated benchmark stream handler 注册到目标服务集合。
|
||||
/// </summary>
|
||||
public void Register(IServiceCollection services, ILogger logger)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(services);
|
||||
ArgumentNullException.ThrowIfNull(logger);
|
||||
|
||||
services.AddTransient(
|
||||
typeof(IStreamRequestHandler<
|
||||
StreamInvokerBenchmarks.GeneratedBenchmarkStreamRequest,
|
||||
StreamInvokerBenchmarks.GeneratedBenchmarkResponse>),
|
||||
typeof(StreamInvokerBenchmarks.GeneratedBenchmarkStreamHandler));
|
||||
logger.Debug("Registered generated stream invoker benchmark handler.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 返回当前 provider 暴露的全部 generated stream invoker 描述符。
|
||||
/// </summary>
|
||||
public IReadOnlyList<GFramework.Cqrs.CqrsStreamInvokerDescriptorEntry> GetDescriptors()
|
||||
{
|
||||
return Descriptors;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 为目标流式请求/响应类型对返回 generated stream invoker 描述符。
|
||||
/// </summary>
|
||||
public bool TryGetDescriptor(
|
||||
Type requestType,
|
||||
Type responseType,
|
||||
out GFramework.Cqrs.CqrsStreamInvokerDescriptor? descriptor)
|
||||
{
|
||||
if (requestType == typeof(StreamInvokerBenchmarks.GeneratedBenchmarkStreamRequest) &&
|
||||
responseType == typeof(StreamInvokerBenchmarks.GeneratedBenchmarkResponse))
|
||||
{
|
||||
descriptor = Descriptor;
|
||||
return true;
|
||||
}
|
||||
|
||||
descriptor = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 模拟 generated stream invoker provider 产出的开放静态调用入口。
|
||||
/// </summary>
|
||||
public static object InvokeGeneratedStreamHandler(object handler, object request, CancellationToken cancellationToken)
|
||||
{
|
||||
var typedHandler = (IStreamRequestHandler<
|
||||
StreamInvokerBenchmarks.GeneratedBenchmarkStreamRequest,
|
||||
StreamInvokerBenchmarks.GeneratedBenchmarkResponse>)handler;
|
||||
var typedRequest = (StreamInvokerBenchmarks.GeneratedBenchmarkStreamRequest)request;
|
||||
return typedHandler.Handle(typedRequest, cancellationToken);
|
||||
}
|
||||
}
|
||||
140
GFramework.Cqrs.Benchmarks/Messaging/NotificationBenchmarks.cs
Normal file
140
GFramework.Cqrs.Benchmarks/Messaging/NotificationBenchmarks.cs
Normal file
@ -0,0 +1,140 @@
|
||||
// Copyright (c) 2025-2026 GeWuYou
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
using BenchmarkDotNet.Attributes;
|
||||
using BenchmarkDotNet.Columns;
|
||||
using BenchmarkDotNet.Configs;
|
||||
using BenchmarkDotNet.Diagnosers;
|
||||
using BenchmarkDotNet.Jobs;
|
||||
using BenchmarkDotNet.Order;
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using GFramework.Core.Abstractions.Logging;
|
||||
using GFramework.Core.Ioc;
|
||||
using GFramework.Core.Logging;
|
||||
using GFramework.Cqrs.Abstractions.Cqrs;
|
||||
using MediatR;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace GFramework.Cqrs.Benchmarks.Messaging;
|
||||
|
||||
/// <summary>
|
||||
/// 对比单处理器 notification 在 GFramework.CQRS 与 MediatR 之间的 publish 开销。
|
||||
/// </summary>
|
||||
[Config(typeof(Config))]
|
||||
public class NotificationBenchmarks
|
||||
{
|
||||
private MicrosoftDiContainer _container = null!;
|
||||
private ICqrsRuntime _runtime = null!;
|
||||
private ServiceProvider _serviceProvider = null!;
|
||||
private IPublisher _publisher = null!;
|
||||
private BenchmarkNotification _notification = null!;
|
||||
|
||||
/// <summary>
|
||||
/// 配置 notification benchmark 的公共输出格式。
|
||||
/// </summary>
|
||||
private sealed class Config : ManualConfig
|
||||
{
|
||||
public Config()
|
||||
{
|
||||
AddJob(Job.Default);
|
||||
AddColumnProvider(DefaultColumnProviders.Instance);
|
||||
AddColumn(new CustomColumn("Scenario", static (_, _) => "Notification"));
|
||||
AddDiagnoser(MemoryDiagnoser.Default);
|
||||
WithOrderer(new DefaultOrderer(SummaryOrderPolicy.FastestToSlowest, MethodOrderPolicy.Declared));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 构建 notification publish 所需的最小 runtime 宿主和对照对象。
|
||||
/// </summary>
|
||||
[GlobalSetup]
|
||||
public void Setup()
|
||||
{
|
||||
LoggerFactoryResolver.Provider = new ConsoleLoggerFactoryProvider
|
||||
{
|
||||
MinLevel = LogLevel.Fatal
|
||||
};
|
||||
Fixture.Setup("Notification", handlerCount: 1, pipelineCount: 0);
|
||||
|
||||
_container = BenchmarkHostFactory.CreateFrozenGFrameworkContainer(container =>
|
||||
{
|
||||
container.RegisterSingleton<GFramework.Cqrs.Abstractions.Cqrs.INotificationHandler<BenchmarkNotification>>(
|
||||
new BenchmarkNotificationHandler());
|
||||
});
|
||||
_runtime = GFramework.Cqrs.CqrsRuntimeFactory.CreateRuntime(
|
||||
_container,
|
||||
LoggerFactoryResolver.Provider.CreateLogger(nameof(NotificationBenchmarks)));
|
||||
|
||||
_serviceProvider = BenchmarkHostFactory.CreateMediatRServiceProvider(
|
||||
services => services.AddSingleton<MediatR.INotificationHandler<BenchmarkNotification>, BenchmarkNotificationHandler>(),
|
||||
typeof(NotificationBenchmarks),
|
||||
static candidateType => candidateType == typeof(BenchmarkNotificationHandler),
|
||||
ServiceLifetime.Singleton);
|
||||
_publisher = _serviceProvider.GetRequiredService<IPublisher>();
|
||||
|
||||
_notification = new BenchmarkNotification(Guid.NewGuid());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 释放 MediatR 对照组使用的 DI 宿主。
|
||||
/// </summary>
|
||||
[GlobalCleanup]
|
||||
public void Cleanup()
|
||||
{
|
||||
BenchmarkCleanupHelper.DisposeAll(_container, _serviceProvider);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 通过 GFramework.CQRS runtime 发布 notification。
|
||||
/// </summary>
|
||||
[Benchmark(Baseline = true)]
|
||||
public ValueTask PublishNotification_GFrameworkCqrs()
|
||||
{
|
||||
return _runtime.PublishAsync(BenchmarkContext.Instance, _notification, CancellationToken.None);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 通过 MediatR 发布 notification,作为外部设计对照。
|
||||
/// </summary>
|
||||
[Benchmark]
|
||||
public Task PublishNotification_MediatR()
|
||||
{
|
||||
return _publisher.Publish(_notification, CancellationToken.None);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Benchmark notification。
|
||||
/// </summary>
|
||||
/// <param name="Id">通知标识。</param>
|
||||
public sealed record BenchmarkNotification(Guid Id) :
|
||||
GFramework.Cqrs.Abstractions.Cqrs.INotification,
|
||||
MediatR.INotification;
|
||||
|
||||
/// <summary>
|
||||
/// 同时实现 GFramework.CQRS 与 MediatR 契约的最小 notification handler。
|
||||
/// </summary>
|
||||
public sealed class BenchmarkNotificationHandler :
|
||||
GFramework.Cqrs.Abstractions.Cqrs.INotificationHandler<BenchmarkNotification>,
|
||||
MediatR.INotificationHandler<BenchmarkNotification>
|
||||
{
|
||||
/// <summary>
|
||||
/// 处理 GFramework.CQRS notification。
|
||||
/// </summary>
|
||||
public ValueTask Handle(BenchmarkNotification notification, CancellationToken cancellationToken)
|
||||
{
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 处理 MediatR notification。
|
||||
/// </summary>
|
||||
Task MediatR.INotificationHandler<BenchmarkNotification>.Handle(
|
||||
BenchmarkNotification notification,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
}
|
||||
157
GFramework.Cqrs.Benchmarks/Messaging/RequestBenchmarks.cs
Normal file
157
GFramework.Cqrs.Benchmarks/Messaging/RequestBenchmarks.cs
Normal file
@ -0,0 +1,157 @@
|
||||
// Copyright (c) 2025-2026 GeWuYou
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
using BenchmarkDotNet.Attributes;
|
||||
using BenchmarkDotNet.Columns;
|
||||
using BenchmarkDotNet.Configs;
|
||||
using BenchmarkDotNet.Diagnosers;
|
||||
using BenchmarkDotNet.Jobs;
|
||||
using BenchmarkDotNet.Order;
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using GFramework.Core.Abstractions.Logging;
|
||||
using GFramework.Core.Ioc;
|
||||
using GFramework.Core.Logging;
|
||||
using GFramework.Cqrs.Abstractions.Cqrs;
|
||||
using MediatR;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace GFramework.Cqrs.Benchmarks.Messaging;
|
||||
|
||||
/// <summary>
|
||||
/// 对比单个 request 在直接调用、GFramework.CQRS runtime 与 MediatR 之间的 steady-state dispatch 开销。
|
||||
/// </summary>
|
||||
[Config(typeof(Config))]
|
||||
public class RequestBenchmarks
|
||||
{
|
||||
private MicrosoftDiContainer _container = null!;
|
||||
private ICqrsRuntime _runtime = null!;
|
||||
private ServiceProvider _serviceProvider = null!;
|
||||
private IMediator _mediatr = null!;
|
||||
private BenchmarkRequestHandler _baselineHandler = null!;
|
||||
private BenchmarkRequest _request = null!;
|
||||
|
||||
/// <summary>
|
||||
/// 配置 request benchmark 的公共输出格式。
|
||||
/// </summary>
|
||||
private sealed class Config : ManualConfig
|
||||
{
|
||||
public Config()
|
||||
{
|
||||
AddJob(Job.Default);
|
||||
AddColumnProvider(DefaultColumnProviders.Instance);
|
||||
AddColumn(new CustomColumn("Scenario", static (_, _) => "Request"));
|
||||
AddDiagnoser(MemoryDiagnoser.Default);
|
||||
WithOrderer(new DefaultOrderer(SummaryOrderPolicy.FastestToSlowest, MethodOrderPolicy.Declared));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 构建 request dispatch 所需的最小 runtime 宿主和对照对象。
|
||||
/// </summary>
|
||||
[GlobalSetup]
|
||||
public void Setup()
|
||||
{
|
||||
LoggerFactoryResolver.Provider = new ConsoleLoggerFactoryProvider
|
||||
{
|
||||
MinLevel = LogLevel.Fatal
|
||||
};
|
||||
Fixture.Setup("Request", handlerCount: 1, pipelineCount: 0);
|
||||
|
||||
_baselineHandler = new BenchmarkRequestHandler();
|
||||
_container = BenchmarkHostFactory.CreateFrozenGFrameworkContainer(container =>
|
||||
{
|
||||
container.RegisterSingleton<GFramework.Cqrs.Abstractions.Cqrs.IRequestHandler<BenchmarkRequest, BenchmarkResponse>>(
|
||||
_baselineHandler);
|
||||
});
|
||||
_runtime = GFramework.Cqrs.CqrsRuntimeFactory.CreateRuntime(
|
||||
_container,
|
||||
LoggerFactoryResolver.Provider.CreateLogger(nameof(RequestBenchmarks)));
|
||||
|
||||
_serviceProvider = BenchmarkHostFactory.CreateMediatRServiceProvider(
|
||||
configure: null,
|
||||
typeof(RequestBenchmarks),
|
||||
static candidateType => candidateType == typeof(BenchmarkRequestHandler),
|
||||
ServiceLifetime.Singleton);
|
||||
_mediatr = _serviceProvider.GetRequiredService<IMediator>();
|
||||
|
||||
_request = new BenchmarkRequest(Guid.NewGuid());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 释放 MediatR 对照组使用的 DI 宿主。
|
||||
/// </summary>
|
||||
[GlobalCleanup]
|
||||
public void Cleanup()
|
||||
{
|
||||
BenchmarkCleanupHelper.DisposeAll(_container, _serviceProvider);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 直接调用 handler,作为 dispatch 额外开销的 baseline。
|
||||
/// </summary>
|
||||
[Benchmark(Baseline = true)]
|
||||
public ValueTask<BenchmarkResponse> SendRequest_Baseline()
|
||||
{
|
||||
return _baselineHandler.Handle(_request, CancellationToken.None);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 通过 GFramework.CQRS runtime 发送 request。
|
||||
/// </summary>
|
||||
[Benchmark]
|
||||
public ValueTask<BenchmarkResponse> SendRequest_GFrameworkCqrs()
|
||||
{
|
||||
return _runtime.SendAsync(BenchmarkContext.Instance, _request, CancellationToken.None);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 通过 MediatR 发送 request,作为外部设计对照。
|
||||
/// </summary>
|
||||
[Benchmark]
|
||||
public Task<BenchmarkResponse> SendRequest_MediatR()
|
||||
{
|
||||
return _mediatr.Send(_request, CancellationToken.None);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Benchmark request。
|
||||
/// </summary>
|
||||
/// <param name="Id">请求标识。</param>
|
||||
public sealed record BenchmarkRequest(Guid Id) :
|
||||
GFramework.Cqrs.Abstractions.Cqrs.IRequest<BenchmarkResponse>,
|
||||
MediatR.IRequest<BenchmarkResponse>;
|
||||
|
||||
/// <summary>
|
||||
/// Benchmark response。
|
||||
/// </summary>
|
||||
/// <param name="Id">响应标识。</param>
|
||||
public sealed record BenchmarkResponse(Guid Id);
|
||||
|
||||
/// <summary>
|
||||
/// 同时实现 GFramework.CQRS 与 MediatR 契约的最小 request handler。
|
||||
/// </summary>
|
||||
public sealed class BenchmarkRequestHandler :
|
||||
GFramework.Cqrs.Abstractions.Cqrs.IRequestHandler<BenchmarkRequest, BenchmarkResponse>,
|
||||
MediatR.IRequestHandler<BenchmarkRequest, BenchmarkResponse>
|
||||
{
|
||||
/// <summary>
|
||||
/// 处理 GFramework.CQRS request。
|
||||
/// </summary>
|
||||
public ValueTask<BenchmarkResponse> Handle(BenchmarkRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
return ValueTask.FromResult(new BenchmarkResponse(request.Id));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 处理 MediatR request。
|
||||
/// </summary>
|
||||
Task<BenchmarkResponse> MediatR.IRequestHandler<BenchmarkRequest, BenchmarkResponse>.Handle(
|
||||
BenchmarkRequest request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
return Task.FromResult(new BenchmarkResponse(request.Id));
|
||||
}
|
||||
}
|
||||
}
|
||||
240
GFramework.Cqrs.Benchmarks/Messaging/RequestInvokerBenchmarks.cs
Normal file
240
GFramework.Cqrs.Benchmarks/Messaging/RequestInvokerBenchmarks.cs
Normal file
@ -0,0 +1,240 @@
|
||||
// Copyright (c) 2025-2026 GeWuYou
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
using BenchmarkDotNet.Attributes;
|
||||
using BenchmarkDotNet.Columns;
|
||||
using BenchmarkDotNet.Configs;
|
||||
using BenchmarkDotNet.Diagnosers;
|
||||
using BenchmarkDotNet.Jobs;
|
||||
using BenchmarkDotNet.Order;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using GFramework.Core.Abstractions.Logging;
|
||||
using GFramework.Core.Ioc;
|
||||
using GFramework.Core.Logging;
|
||||
using GFramework.Cqrs.Abstractions.Cqrs;
|
||||
using MediatR;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
[assembly: GFramework.Cqrs.CqrsHandlerRegistryAttribute(
|
||||
typeof(GFramework.Cqrs.Benchmarks.Messaging.GeneratedRequestInvokerBenchmarkRegistry))]
|
||||
|
||||
namespace GFramework.Cqrs.Benchmarks.Messaging;
|
||||
|
||||
/// <summary>
|
||||
/// 对比 request steady-state dispatch 在 direct handler、GFramework 反射路径、GFramework generated invoker 路径与 MediatR 之间的开销差异。
|
||||
/// </summary>
|
||||
[Config(typeof(Config))]
|
||||
public class RequestInvokerBenchmarks
|
||||
{
|
||||
private MicrosoftDiContainer _reflectionContainer = null!;
|
||||
private ICqrsRuntime _reflectionRuntime = null!;
|
||||
private MicrosoftDiContainer _generatedContainer = null!;
|
||||
private ICqrsRuntime _generatedRuntime = null!;
|
||||
private ServiceProvider _serviceProvider = null!;
|
||||
private IMediator _mediatr = null!;
|
||||
private ReflectionBenchmarkRequestHandler _baselineHandler = null!;
|
||||
private ReflectionBenchmarkRequest _reflectionRequest = null!;
|
||||
private GeneratedBenchmarkRequest _generatedRequest = null!;
|
||||
private MediatRBenchmarkRequest _mediatrRequest = null!;
|
||||
|
||||
/// <summary>
|
||||
/// 配置 request invoker benchmark 的公共输出格式。
|
||||
/// </summary>
|
||||
private sealed class Config : ManualConfig
|
||||
{
|
||||
public Config()
|
||||
{
|
||||
AddJob(Job.Default);
|
||||
AddColumnProvider(DefaultColumnProviders.Instance);
|
||||
AddColumn(new CustomColumn("Scenario", static (_, _) => "RequestInvoker"));
|
||||
AddDiagnoser(MemoryDiagnoser.Default);
|
||||
WithOrderer(new DefaultOrderer(SummaryOrderPolicy.FastestToSlowest, MethodOrderPolicy.Declared));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 构建 reflection / generated / MediatR 三组 request dispatch 对照宿主。
|
||||
/// </summary>
|
||||
[GlobalSetup]
|
||||
public void Setup()
|
||||
{
|
||||
LoggerFactoryResolver.Provider = new ConsoleLoggerFactoryProvider
|
||||
{
|
||||
MinLevel = LogLevel.Fatal
|
||||
};
|
||||
Fixture.Setup("RequestInvoker", handlerCount: 1, pipelineCount: 0);
|
||||
BenchmarkDispatcherCacheHelper.ClearDispatcherCaches();
|
||||
|
||||
_baselineHandler = new ReflectionBenchmarkRequestHandler();
|
||||
_reflectionRequest = new ReflectionBenchmarkRequest(Guid.NewGuid());
|
||||
_generatedRequest = new GeneratedBenchmarkRequest(Guid.NewGuid());
|
||||
_mediatrRequest = new MediatRBenchmarkRequest(Guid.NewGuid());
|
||||
|
||||
_reflectionContainer = BenchmarkHostFactory.CreateFrozenGFrameworkContainer(static container =>
|
||||
{
|
||||
container.RegisterTransient<GFramework.Cqrs.Abstractions.Cqrs.IRequestHandler<ReflectionBenchmarkRequest, ReflectionBenchmarkResponse>, ReflectionBenchmarkRequestHandler>();
|
||||
});
|
||||
_reflectionRuntime = GFramework.Cqrs.CqrsRuntimeFactory.CreateRuntime(
|
||||
_reflectionContainer,
|
||||
LoggerFactoryResolver.Provider.CreateLogger(nameof(RequestInvokerBenchmarks) + ".Reflection"));
|
||||
|
||||
_generatedContainer = BenchmarkHostFactory.CreateFrozenGFrameworkContainer(container =>
|
||||
{
|
||||
container.RegisterCqrsHandlersFromAssembly(typeof(RequestInvokerBenchmarks).Assembly);
|
||||
});
|
||||
_generatedRuntime = GFramework.Cqrs.CqrsRuntimeFactory.CreateRuntime(
|
||||
_generatedContainer,
|
||||
LoggerFactoryResolver.Provider.CreateLogger(nameof(RequestInvokerBenchmarks) + ".Generated"));
|
||||
|
||||
_serviceProvider = BenchmarkHostFactory.CreateMediatRServiceProvider(
|
||||
configure: null,
|
||||
typeof(RequestInvokerBenchmarks),
|
||||
static candidateType => candidateType == typeof(MediatRBenchmarkRequestHandler),
|
||||
ServiceLifetime.Transient);
|
||||
_mediatr = _serviceProvider.GetRequiredService<IMediator>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 释放 MediatR 对照组使用的 DI 宿主,并清理静态 dispatcher 缓存。
|
||||
/// </summary>
|
||||
[GlobalCleanup]
|
||||
public void Cleanup()
|
||||
{
|
||||
try
|
||||
{
|
||||
BenchmarkCleanupHelper.DisposeAll(_reflectionContainer, _generatedContainer, _serviceProvider);
|
||||
}
|
||||
finally
|
||||
{
|
||||
BenchmarkDispatcherCacheHelper.ClearDispatcherCaches();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 直接调用最小 request handler,作为 dispatch 额外开销 baseline。
|
||||
/// </summary>
|
||||
[Benchmark(Baseline = true)]
|
||||
public ValueTask<ReflectionBenchmarkResponse> SendRequest_Baseline()
|
||||
{
|
||||
return _baselineHandler.Handle(_reflectionRequest, CancellationToken.None);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 通过 GFramework.CQRS 反射 request binding 路径发送 request。
|
||||
/// </summary>
|
||||
[Benchmark]
|
||||
public ValueTask<ReflectionBenchmarkResponse> SendRequest_GFrameworkReflection()
|
||||
{
|
||||
return _reflectionRuntime.SendAsync(BenchmarkContext.Instance, _reflectionRequest, CancellationToken.None);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 通过 generated request invoker provider 预热后的 GFramework.CQRS runtime 发送 request。
|
||||
/// </summary>
|
||||
[Benchmark]
|
||||
public ValueTask<GeneratedBenchmarkResponse> SendRequest_GFrameworkGenerated()
|
||||
{
|
||||
return _generatedRuntime.SendAsync(BenchmarkContext.Instance, _generatedRequest, CancellationToken.None);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 通过 MediatR 发送 request,作为外部对照。
|
||||
/// </summary>
|
||||
[Benchmark]
|
||||
public Task<MediatRBenchmarkResponse> SendRequest_MediatR()
|
||||
{
|
||||
return _mediatr.Send(_mediatrRequest, CancellationToken.None);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reflection runtime request。
|
||||
/// </summary>
|
||||
/// <param name="Id">请求标识。</param>
|
||||
public sealed record ReflectionBenchmarkRequest(Guid Id) :
|
||||
GFramework.Cqrs.Abstractions.Cqrs.IRequest<ReflectionBenchmarkResponse>;
|
||||
|
||||
/// <summary>
|
||||
/// Reflection runtime response。
|
||||
/// </summary>
|
||||
/// <param name="Id">响应标识。</param>
|
||||
public sealed record ReflectionBenchmarkResponse(Guid Id);
|
||||
|
||||
/// <summary>
|
||||
/// Generated runtime request。
|
||||
/// </summary>
|
||||
/// <param name="Id">请求标识。</param>
|
||||
public sealed record GeneratedBenchmarkRequest(Guid Id) :
|
||||
GFramework.Cqrs.Abstractions.Cqrs.IRequest<GeneratedBenchmarkResponse>;
|
||||
|
||||
/// <summary>
|
||||
/// Generated runtime response。
|
||||
/// </summary>
|
||||
/// <param name="Id">响应标识。</param>
|
||||
public sealed record GeneratedBenchmarkResponse(Guid Id);
|
||||
|
||||
/// <summary>
|
||||
/// MediatR request。
|
||||
/// </summary>
|
||||
/// <param name="Id">请求标识。</param>
|
||||
public sealed record MediatRBenchmarkRequest(Guid Id) : MediatR.IRequest<MediatRBenchmarkResponse>;
|
||||
|
||||
/// <summary>
|
||||
/// MediatR response。
|
||||
/// </summary>
|
||||
/// <param name="Id">响应标识。</param>
|
||||
public sealed record MediatRBenchmarkResponse(Guid Id);
|
||||
|
||||
/// <summary>
|
||||
/// Reflection runtime 的最小 request handler。
|
||||
/// </summary>
|
||||
public sealed class ReflectionBenchmarkRequestHandler :
|
||||
GFramework.Cqrs.Abstractions.Cqrs.IRequestHandler<ReflectionBenchmarkRequest, ReflectionBenchmarkResponse>
|
||||
{
|
||||
/// <summary>
|
||||
/// 处理 reflection benchmark request。
|
||||
/// </summary>
|
||||
public ValueTask<ReflectionBenchmarkResponse> Handle(
|
||||
ReflectionBenchmarkRequest request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
return ValueTask.FromResult(new ReflectionBenchmarkResponse(request.Id));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Generated runtime 的最小 request handler。
|
||||
/// </summary>
|
||||
public sealed class GeneratedBenchmarkRequestHandler :
|
||||
GFramework.Cqrs.Abstractions.Cqrs.IRequestHandler<GeneratedBenchmarkRequest, GeneratedBenchmarkResponse>
|
||||
{
|
||||
/// <summary>
|
||||
/// 处理 generated benchmark request。
|
||||
/// </summary>
|
||||
public ValueTask<GeneratedBenchmarkResponse> Handle(
|
||||
GeneratedBenchmarkRequest request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
return ValueTask.FromResult(new GeneratedBenchmarkResponse(request.Id));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// MediatR 对照组的最小 request handler。
|
||||
/// </summary>
|
||||
public sealed class MediatRBenchmarkRequestHandler :
|
||||
MediatR.IRequestHandler<MediatRBenchmarkRequest, MediatRBenchmarkResponse>
|
||||
{
|
||||
/// <summary>
|
||||
/// 处理 MediatR benchmark request。
|
||||
/// </summary>
|
||||
public Task<MediatRBenchmarkResponse> Handle(
|
||||
MediatRBenchmarkRequest request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
return Task.FromResult(new MediatRBenchmarkResponse(request.Id));
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,296 @@
|
||||
// Copyright (c) 2025-2026 GeWuYou
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
using BenchmarkDotNet.Attributes;
|
||||
using BenchmarkDotNet.Columns;
|
||||
using BenchmarkDotNet.Configs;
|
||||
using BenchmarkDotNet.Diagnosers;
|
||||
using BenchmarkDotNet.Jobs;
|
||||
using BenchmarkDotNet.Order;
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using GFramework.Core.Abstractions.Logging;
|
||||
using GFramework.Core.Ioc;
|
||||
using GFramework.Core.Logging;
|
||||
using GFramework.Cqrs.Abstractions.Cqrs;
|
||||
using MediatR;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace GFramework.Cqrs.Benchmarks.Messaging;
|
||||
|
||||
/// <summary>
|
||||
/// 对比不同 pipeline 行为数量下,单个 request 在直接调用、GFramework.CQRS runtime 与 MediatR 之间的 steady-state dispatch 开销。
|
||||
/// </summary>
|
||||
[Config(typeof(Config))]
|
||||
public class RequestPipelineBenchmarks
|
||||
{
|
||||
private MicrosoftDiContainer _container = null!;
|
||||
private ICqrsRuntime _runtime = null!;
|
||||
private ServiceProvider _serviceProvider = null!;
|
||||
private IMediator _mediatr = null!;
|
||||
private BenchmarkRequestHandler _baselineHandler = null!;
|
||||
private BenchmarkRequest _request = null!;
|
||||
|
||||
/// <summary>
|
||||
/// 控制当前场景注册的 pipeline 行为数量,保持与 `Mediator` benchmark 常见的“无行为 / 少量行为 / 多行为”矩阵一致。
|
||||
/// </summary>
|
||||
[Params(0, 1, 4)]
|
||||
public int PipelineCount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 配置 request pipeline benchmark 的公共输出格式。
|
||||
/// </summary>
|
||||
private sealed class Config : ManualConfig
|
||||
{
|
||||
public Config()
|
||||
{
|
||||
AddJob(Job.Default);
|
||||
AddColumnProvider(DefaultColumnProviders.Instance);
|
||||
AddColumn(new CustomColumn("Scenario", static (_, _) => "RequestPipeline"));
|
||||
AddDiagnoser(MemoryDiagnoser.Default);
|
||||
WithOrderer(new DefaultOrderer(SummaryOrderPolicy.FastestToSlowest, MethodOrderPolicy.Declared));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 构建 request pipeline dispatch 所需的最小 runtime 宿主和对照对象。
|
||||
/// </summary>
|
||||
[GlobalSetup]
|
||||
public void Setup()
|
||||
{
|
||||
LoggerFactoryResolver.Provider = new ConsoleLoggerFactoryProvider
|
||||
{
|
||||
MinLevel = LogLevel.Fatal
|
||||
};
|
||||
Fixture.Setup("RequestPipeline", handlerCount: 1, pipelineCount: PipelineCount);
|
||||
BenchmarkDispatcherCacheHelper.ClearDispatcherCaches();
|
||||
|
||||
_baselineHandler = new BenchmarkRequestHandler();
|
||||
_container = BenchmarkHostFactory.CreateFrozenGFrameworkContainer(container =>
|
||||
{
|
||||
container.RegisterSingleton<GFramework.Cqrs.Abstractions.Cqrs.IRequestHandler<BenchmarkRequest, BenchmarkResponse>>(
|
||||
_baselineHandler);
|
||||
RegisterGFrameworkPipelineBehaviors(container, PipelineCount);
|
||||
});
|
||||
_runtime = GFramework.Cqrs.CqrsRuntimeFactory.CreateRuntime(
|
||||
_container,
|
||||
LoggerFactoryResolver.Provider.CreateLogger(nameof(RequestPipelineBenchmarks)));
|
||||
|
||||
_serviceProvider = BenchmarkHostFactory.CreateMediatRServiceProvider(
|
||||
services =>
|
||||
{
|
||||
RegisterMediatRPipelineBehaviors(services, PipelineCount);
|
||||
},
|
||||
typeof(RequestPipelineBenchmarks),
|
||||
static candidateType =>
|
||||
candidateType == typeof(BenchmarkRequestHandler) ||
|
||||
candidateType == typeof(BenchmarkPipelineBehavior1) ||
|
||||
candidateType == typeof(BenchmarkPipelineBehavior2) ||
|
||||
candidateType == typeof(BenchmarkPipelineBehavior3) ||
|
||||
candidateType == typeof(BenchmarkPipelineBehavior4),
|
||||
ServiceLifetime.Singleton);
|
||||
_mediatr = _serviceProvider.GetRequiredService<IMediator>();
|
||||
|
||||
_request = new BenchmarkRequest(Guid.NewGuid());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 释放 MediatR 对照组使用的 DI 宿主。
|
||||
/// </summary>
|
||||
[GlobalCleanup]
|
||||
public void Cleanup()
|
||||
{
|
||||
try
|
||||
{
|
||||
BenchmarkCleanupHelper.DisposeAll(_container, _serviceProvider);
|
||||
}
|
||||
finally
|
||||
{
|
||||
BenchmarkDispatcherCacheHelper.ClearDispatcherCaches();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 直接调用 handler,作为 pipeline 编排之外的基线。
|
||||
/// </summary>
|
||||
[Benchmark(Baseline = true)]
|
||||
public ValueTask<BenchmarkResponse> SendRequest_Baseline()
|
||||
{
|
||||
return _baselineHandler.Handle(_request, CancellationToken.None);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 通过 GFramework.CQRS runtime 发送 request,并按当前矩阵配置执行 pipeline。
|
||||
/// </summary>
|
||||
[Benchmark]
|
||||
public ValueTask<BenchmarkResponse> SendRequest_GFrameworkCqrs()
|
||||
{
|
||||
return _runtime.SendAsync(BenchmarkContext.Instance, _request, CancellationToken.None);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 通过 MediatR 发送 request,并按当前矩阵配置执行 pipeline,作为外部设计对照。
|
||||
/// </summary>
|
||||
[Benchmark]
|
||||
public Task<BenchmarkResponse> SendRequest_MediatR()
|
||||
{
|
||||
return _mediatr.Send(_request, CancellationToken.None);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 按指定数量向 GFramework.CQRS 宿主注册最小 no-op pipeline 行为。
|
||||
/// </summary>
|
||||
/// <param name="container">当前 benchmark 使用的容器。</param>
|
||||
/// <param name="pipelineCount">要注册的行为数量。</param>
|
||||
/// <exception cref="ArgumentOutOfRangeException">行为数量不在支持的矩阵内时抛出。</exception>
|
||||
private static void RegisterGFrameworkPipelineBehaviors(MicrosoftDiContainer container, int pipelineCount)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(container);
|
||||
|
||||
switch (pipelineCount)
|
||||
{
|
||||
case 0:
|
||||
return;
|
||||
case 1:
|
||||
container.RegisterCqrsPipelineBehavior<BenchmarkPipelineBehavior1>();
|
||||
return;
|
||||
case 4:
|
||||
container.RegisterCqrsPipelineBehavior<BenchmarkPipelineBehavior1>();
|
||||
container.RegisterCqrsPipelineBehavior<BenchmarkPipelineBehavior2>();
|
||||
container.RegisterCqrsPipelineBehavior<BenchmarkPipelineBehavior3>();
|
||||
container.RegisterCqrsPipelineBehavior<BenchmarkPipelineBehavior4>();
|
||||
return;
|
||||
default:
|
||||
throw new ArgumentOutOfRangeException(nameof(pipelineCount), pipelineCount,
|
||||
"Only the 0/1/4 pipeline matrix is supported.");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 按指定数量向 MediatR 宿主注册最小 no-op pipeline 行为。
|
||||
/// </summary>
|
||||
/// <param name="services">当前 benchmark 使用的服务集合。</param>
|
||||
/// <param name="pipelineCount">要注册的行为数量。</param>
|
||||
/// <exception cref="ArgumentOutOfRangeException">行为数量不在支持的矩阵内时抛出。</exception>
|
||||
private static void RegisterMediatRPipelineBehaviors(IServiceCollection services, int pipelineCount)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(services);
|
||||
|
||||
switch (pipelineCount)
|
||||
{
|
||||
case 0:
|
||||
return;
|
||||
case 1:
|
||||
services.AddSingleton<MediatR.IPipelineBehavior<BenchmarkRequest, BenchmarkResponse>, BenchmarkPipelineBehavior1>();
|
||||
return;
|
||||
case 4:
|
||||
services.AddSingleton<MediatR.IPipelineBehavior<BenchmarkRequest, BenchmarkResponse>, BenchmarkPipelineBehavior1>();
|
||||
services.AddSingleton<MediatR.IPipelineBehavior<BenchmarkRequest, BenchmarkResponse>, BenchmarkPipelineBehavior2>();
|
||||
services.AddSingleton<MediatR.IPipelineBehavior<BenchmarkRequest, BenchmarkResponse>, BenchmarkPipelineBehavior3>();
|
||||
services.AddSingleton<MediatR.IPipelineBehavior<BenchmarkRequest, BenchmarkResponse>, BenchmarkPipelineBehavior4>();
|
||||
return;
|
||||
default:
|
||||
throw new ArgumentOutOfRangeException(nameof(pipelineCount), pipelineCount,
|
||||
"Only the 0/1/4 pipeline matrix is supported.");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Benchmark request。
|
||||
/// </summary>
|
||||
/// <param name="Id">请求标识。</param>
|
||||
public sealed record BenchmarkRequest(Guid Id) :
|
||||
GFramework.Cqrs.Abstractions.Cqrs.IRequest<BenchmarkResponse>,
|
||||
MediatR.IRequest<BenchmarkResponse>;
|
||||
|
||||
/// <summary>
|
||||
/// Benchmark response。
|
||||
/// </summary>
|
||||
/// <param name="Id">响应标识。</param>
|
||||
public sealed record BenchmarkResponse(Guid Id);
|
||||
|
||||
/// <summary>
|
||||
/// 同时实现 GFramework.CQRS 与 MediatR 契约的最小 request handler。
|
||||
/// </summary>
|
||||
public sealed class BenchmarkRequestHandler :
|
||||
GFramework.Cqrs.Abstractions.Cqrs.IRequestHandler<BenchmarkRequest, BenchmarkResponse>,
|
||||
MediatR.IRequestHandler<BenchmarkRequest, BenchmarkResponse>
|
||||
{
|
||||
/// <summary>
|
||||
/// 处理 GFramework.CQRS request。
|
||||
/// </summary>
|
||||
public ValueTask<BenchmarkResponse> Handle(BenchmarkRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
return ValueTask.FromResult(new BenchmarkResponse(request.Id));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 处理 MediatR request。
|
||||
/// </summary>
|
||||
Task<BenchmarkResponse> MediatR.IRequestHandler<BenchmarkRequest, BenchmarkResponse>.Handle(
|
||||
BenchmarkRequest request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
return Task.FromResult(new BenchmarkResponse(request.Id));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 为 benchmark 提供统一的 no-op pipeline 行为实现,尽量把测量焦点保持在调度器与行为编排本身。
|
||||
/// </summary>
|
||||
public abstract class BenchmarkPipelineBehaviorBase :
|
||||
GFramework.Cqrs.Abstractions.Cqrs.IPipelineBehavior<BenchmarkRequest, BenchmarkResponse>,
|
||||
MediatR.IPipelineBehavior<BenchmarkRequest, BenchmarkResponse>
|
||||
{
|
||||
/// <summary>
|
||||
/// 透传 GFramework.CQRS pipeline,避免引入额外业务逻辑噪音。
|
||||
/// </summary>
|
||||
public ValueTask<BenchmarkResponse> Handle(
|
||||
BenchmarkRequest message,
|
||||
GFramework.Cqrs.Abstractions.Cqrs.MessageHandlerDelegate<BenchmarkRequest, BenchmarkResponse> next,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
return next(message, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 透传 MediatR pipeline,保持与 GFramework.CQRS 相同的 no-op 语义。
|
||||
/// </summary>
|
||||
Task<BenchmarkResponse> MediatR.IPipelineBehavior<BenchmarkRequest, BenchmarkResponse>.Handle(
|
||||
BenchmarkRequest request,
|
||||
RequestHandlerDelegate<BenchmarkResponse> next,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
return next();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// pipeline 行为槽位 1。
|
||||
/// </summary>
|
||||
public sealed class BenchmarkPipelineBehavior1 : BenchmarkPipelineBehaviorBase
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// pipeline 行为槽位 2。
|
||||
/// </summary>
|
||||
public sealed class BenchmarkPipelineBehavior2 : BenchmarkPipelineBehaviorBase
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// pipeline 行为槽位 3。
|
||||
/// </summary>
|
||||
public sealed class BenchmarkPipelineBehavior3 : BenchmarkPipelineBehaviorBase
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// pipeline 行为槽位 4。
|
||||
/// </summary>
|
||||
public sealed class BenchmarkPipelineBehavior4 : BenchmarkPipelineBehaviorBase
|
||||
{
|
||||
}
|
||||
}
|
||||
224
GFramework.Cqrs.Benchmarks/Messaging/RequestStartupBenchmarks.cs
Normal file
224
GFramework.Cqrs.Benchmarks/Messaging/RequestStartupBenchmarks.cs
Normal file
@ -0,0 +1,224 @@
|
||||
// Copyright (c) 2025-2026 GeWuYou
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
using BenchmarkDotNet.Attributes;
|
||||
using BenchmarkDotNet.Columns;
|
||||
using BenchmarkDotNet.Configs;
|
||||
using BenchmarkDotNet.Diagnosers;
|
||||
using BenchmarkDotNet.Jobs;
|
||||
using BenchmarkDotNet.Order;
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using GFramework.Core.Abstractions.Logging;
|
||||
using GFramework.Core.Ioc;
|
||||
using GFramework.Core.Logging;
|
||||
using GFramework.Cqrs.Abstractions.Cqrs;
|
||||
using MediatR;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using ILogger = GFramework.Core.Abstractions.Logging.ILogger;
|
||||
|
||||
namespace GFramework.Cqrs.Benchmarks.Messaging;
|
||||
|
||||
/// <summary>
|
||||
/// 对比 request 宿主的初始化与首次分发成本,作为后续吸收 `Mediator` comparison benchmark 设计的 startup 基线。
|
||||
/// </summary>
|
||||
[Config(typeof(Config))]
|
||||
public class RequestStartupBenchmarks
|
||||
{
|
||||
private static readonly ILogger RuntimeLogger = CreateLogger(nameof(RequestStartupBenchmarks));
|
||||
private static readonly BenchmarkRequest Request = new(Guid.NewGuid());
|
||||
|
||||
private MicrosoftDiContainer _container = null!;
|
||||
private ServiceProvider _serviceProvider = null!;
|
||||
private IMediator _mediatr = null!;
|
||||
private ICqrsRuntime _runtime = null!;
|
||||
|
||||
/// <summary>
|
||||
/// 配置 request startup benchmark 的公共输出格式。
|
||||
/// </summary>
|
||||
private sealed class Config : ManualConfig
|
||||
{
|
||||
public Config()
|
||||
{
|
||||
AddJob(Job.Default
|
||||
.WithId("ColdStart")
|
||||
.WithInvocationCount(1)
|
||||
.WithUnrollFactor(1));
|
||||
AddColumnProvider(DefaultColumnProviders.Instance);
|
||||
AddColumn(new CustomColumn("Scenario", static (_, _) => "RequestStartup"), TargetMethodColumn.Method, CategoriesColumn.Default);
|
||||
AddDiagnoser(MemoryDiagnoser.Default);
|
||||
AddLogicalGroupRules(BenchmarkLogicalGroupRule.ByCategory);
|
||||
WithOrderer(new DefaultOrderer(SummaryOrderPolicy.FastestToSlowest, MethodOrderPolicy.Declared));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 构建 steady-state 初始化 benchmark 复用的宿主对象。
|
||||
/// </summary>
|
||||
[GlobalSetup]
|
||||
public void Setup()
|
||||
{
|
||||
Fixture.Setup("RequestStartup", handlerCount: 1, pipelineCount: 0);
|
||||
|
||||
_serviceProvider = CreateMediatRServiceProvider();
|
||||
_mediatr = _serviceProvider.GetRequiredService<IMediator>();
|
||||
_container = CreateGFrameworkContainer();
|
||||
_runtime = CreateGFrameworkRuntime(_container);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 在每次 cold-start 迭代前清空 dispatcher 静态缓存,确保两组 benchmark 都重新命中首次绑定路径。
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 使用 `IterationSetup` 而不是把缓存清理写在 benchmark 方法主体中,
|
||||
/// 可以把“清理静态缓存”留在测量边界之外,只保留宿主构建与首次发送本身。
|
||||
/// </remarks>
|
||||
[IterationSetup]
|
||||
public void ResetColdStartCaches()
|
||||
{
|
||||
BenchmarkDispatcherCacheHelper.ClearDispatcherCaches();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 释放 startup benchmark 复用的宿主对象。
|
||||
/// </summary>
|
||||
[GlobalCleanup]
|
||||
public void Cleanup()
|
||||
{
|
||||
BenchmarkCleanupHelper.DisposeAll(_container, _serviceProvider);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 返回已构建宿主中的 MediatR mediator,作为 initialization 组的句柄解析 baseline。
|
||||
/// </summary>
|
||||
[Benchmark(Baseline = true)]
|
||||
[BenchmarkCategory("Initialization")]
|
||||
public IMediator Initialization_MediatR()
|
||||
{
|
||||
return _mediatr;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 返回已构建宿主中的 GFramework.CQRS runtime,确保与 MediatR baseline 处于相同初始化阶段。
|
||||
/// </summary>
|
||||
[Benchmark]
|
||||
[BenchmarkCategory("Initialization")]
|
||||
public ICqrsRuntime Initialization_GFrameworkCqrs()
|
||||
{
|
||||
return _runtime;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 在新宿主上首次发送 request,作为 MediatR 的 cold-start baseline。
|
||||
/// </summary>
|
||||
[Benchmark(Baseline = true)]
|
||||
[BenchmarkCategory("ColdStart")]
|
||||
public async Task<BenchmarkResponse> ColdStart_MediatR()
|
||||
{
|
||||
using var serviceProvider = CreateMediatRServiceProvider();
|
||||
var mediator = serviceProvider.GetRequiredService<IMediator>();
|
||||
return await mediator.Send(Request, CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 在新 runtime 上首次发送 request,量化 GFramework.CQRS 的 first-hit 成本。
|
||||
/// </summary>
|
||||
[Benchmark]
|
||||
[BenchmarkCategory("ColdStart")]
|
||||
public async ValueTask<BenchmarkResponse> ColdStart_GFrameworkCqrs()
|
||||
{
|
||||
using var container = CreateGFrameworkContainer();
|
||||
var runtime = CreateGFrameworkRuntime(container);
|
||||
return await runtime.SendAsync(BenchmarkContext.Instance, Request, CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 构建只承载当前 benchmark request 的最小 GFramework.CQRS runtime。
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 该 benchmark 故意保持与 MediatR 对照组同样的“单 handler 最小宿主”模型,
|
||||
/// 因此这里继续使用单点手工注册,而不引入依赖完整 CQRS 注册协调器的程序集扫描路径。
|
||||
/// </remarks>
|
||||
private static MicrosoftDiContainer CreateGFrameworkContainer()
|
||||
{
|
||||
return BenchmarkHostFactory.CreateFrozenGFrameworkContainer(static currentContainer =>
|
||||
{
|
||||
currentContainer.RegisterTransient<GFramework.Cqrs.Abstractions.Cqrs.IRequestHandler<BenchmarkRequest, BenchmarkResponse>, BenchmarkRequestHandler>();
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 基于已冻结的 benchmark 容器构建最小 GFramework.CQRS runtime。
|
||||
/// </summary>
|
||||
/// <param name="container">当前 benchmark 拥有并负责释放的容器。</param>
|
||||
private static ICqrsRuntime CreateGFrameworkRuntime(MicrosoftDiContainer container)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(container);
|
||||
return GFramework.Cqrs.CqrsRuntimeFactory.CreateRuntime(container, RuntimeLogger);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 构建只承载当前 benchmark request 的最小 MediatR 对照宿主。
|
||||
/// </summary>
|
||||
private static ServiceProvider CreateMediatRServiceProvider()
|
||||
{
|
||||
return BenchmarkHostFactory.CreateMediatRServiceProvider(
|
||||
configure: null,
|
||||
typeof(RequestStartupBenchmarks),
|
||||
static candidateType => candidateType == typeof(BenchmarkRequestHandler),
|
||||
ServiceLifetime.Transient);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 为 benchmark 创建稳定的 fatal 级 logger,避免把日志成本混入 startup 测量。
|
||||
/// </summary>
|
||||
private static ILogger CreateLogger(string categoryName)
|
||||
{
|
||||
LoggerFactoryResolver.Provider = new ConsoleLoggerFactoryProvider
|
||||
{
|
||||
MinLevel = LogLevel.Fatal
|
||||
};
|
||||
return LoggerFactoryResolver.Provider.CreateLogger(categoryName);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Benchmark request。
|
||||
/// </summary>
|
||||
/// <param name="Id">请求标识。</param>
|
||||
public sealed record BenchmarkRequest(Guid Id) :
|
||||
GFramework.Cqrs.Abstractions.Cqrs.IRequest<BenchmarkResponse>,
|
||||
MediatR.IRequest<BenchmarkResponse>;
|
||||
|
||||
/// <summary>
|
||||
/// Benchmark response。
|
||||
/// </summary>
|
||||
/// <param name="Id">响应标识。</param>
|
||||
public sealed record BenchmarkResponse(Guid Id);
|
||||
|
||||
/// <summary>
|
||||
/// 同时实现 GFramework.CQRS 与 MediatR 契约的最小 request handler。
|
||||
/// </summary>
|
||||
public sealed class BenchmarkRequestHandler :
|
||||
GFramework.Cqrs.Abstractions.Cqrs.IRequestHandler<BenchmarkRequest, BenchmarkResponse>,
|
||||
MediatR.IRequestHandler<BenchmarkRequest, BenchmarkResponse>
|
||||
{
|
||||
/// <summary>
|
||||
/// 处理 GFramework.CQRS request。
|
||||
/// </summary>
|
||||
public ValueTask<BenchmarkResponse> Handle(BenchmarkRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
return ValueTask.FromResult(new BenchmarkResponse(request.Id));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 处理 MediatR request。
|
||||
/// </summary>
|
||||
Task<BenchmarkResponse> MediatR.IRequestHandler<BenchmarkRequest, BenchmarkResponse>.Handle(
|
||||
BenchmarkRequest request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
return Task.FromResult(new BenchmarkResponse(request.Id));
|
||||
}
|
||||
}
|
||||
}
|
||||
287
GFramework.Cqrs.Benchmarks/Messaging/StreamInvokerBenchmarks.cs
Normal file
287
GFramework.Cqrs.Benchmarks/Messaging/StreamInvokerBenchmarks.cs
Normal file
@ -0,0 +1,287 @@
|
||||
// Copyright (c) 2025-2026 GeWuYou
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
using BenchmarkDotNet.Attributes;
|
||||
using BenchmarkDotNet.Columns;
|
||||
using BenchmarkDotNet.Configs;
|
||||
using BenchmarkDotNet.Diagnosers;
|
||||
using BenchmarkDotNet.Jobs;
|
||||
using BenchmarkDotNet.Order;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using GFramework.Core.Abstractions.Logging;
|
||||
using GFramework.Core.Ioc;
|
||||
using GFramework.Core.Logging;
|
||||
using GFramework.Cqrs.Abstractions.Cqrs;
|
||||
using MediatR;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
[assembly: GFramework.Cqrs.CqrsHandlerRegistryAttribute(
|
||||
typeof(GFramework.Cqrs.Benchmarks.Messaging.GeneratedStreamInvokerBenchmarkRegistry))]
|
||||
|
||||
namespace GFramework.Cqrs.Benchmarks.Messaging;
|
||||
|
||||
/// <summary>
|
||||
/// 对比 stream 完整枚举在 direct handler、GFramework 反射路径、GFramework generated invoker 路径与 MediatR 之间的开销差异。
|
||||
/// </summary>
|
||||
[Config(typeof(Config))]
|
||||
public class StreamInvokerBenchmarks
|
||||
{
|
||||
private MicrosoftDiContainer _reflectionContainer = null!;
|
||||
private ICqrsRuntime _reflectionRuntime = null!;
|
||||
private MicrosoftDiContainer _generatedContainer = null!;
|
||||
private ICqrsRuntime _generatedRuntime = null!;
|
||||
private ServiceProvider _serviceProvider = null!;
|
||||
private IMediator _mediatr = null!;
|
||||
private ReflectionBenchmarkStreamHandler _baselineHandler = null!;
|
||||
private ReflectionBenchmarkStreamRequest _reflectionRequest = null!;
|
||||
private GeneratedBenchmarkStreamRequest _generatedRequest = null!;
|
||||
private MediatRBenchmarkStreamRequest _mediatrRequest = null!;
|
||||
|
||||
/// <summary>
|
||||
/// 配置 stream invoker benchmark 的公共输出格式。
|
||||
/// </summary>
|
||||
private sealed class Config : ManualConfig
|
||||
{
|
||||
public Config()
|
||||
{
|
||||
AddJob(Job.Default);
|
||||
AddColumnProvider(DefaultColumnProviders.Instance);
|
||||
AddColumn(new CustomColumn("Scenario", static (_, _) => "StreamInvoker"));
|
||||
AddDiagnoser(MemoryDiagnoser.Default);
|
||||
WithOrderer(new DefaultOrderer(SummaryOrderPolicy.FastestToSlowest, MethodOrderPolicy.Declared));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 构建 reflection / generated / MediatR 三组 stream dispatch 对照宿主。
|
||||
/// </summary>
|
||||
[GlobalSetup]
|
||||
public void Setup()
|
||||
{
|
||||
LoggerFactoryResolver.Provider = new ConsoleLoggerFactoryProvider
|
||||
{
|
||||
MinLevel = LogLevel.Fatal
|
||||
};
|
||||
Fixture.Setup("StreamInvoker", handlerCount: 1, pipelineCount: 0);
|
||||
BenchmarkDispatcherCacheHelper.ClearDispatcherCaches();
|
||||
|
||||
_baselineHandler = new ReflectionBenchmarkStreamHandler();
|
||||
_reflectionRequest = new ReflectionBenchmarkStreamRequest(Guid.NewGuid(), 3);
|
||||
_generatedRequest = new GeneratedBenchmarkStreamRequest(Guid.NewGuid(), 3);
|
||||
_mediatrRequest = new MediatRBenchmarkStreamRequest(Guid.NewGuid(), 3);
|
||||
|
||||
_reflectionContainer = BenchmarkHostFactory.CreateFrozenGFrameworkContainer(static container =>
|
||||
{
|
||||
container.RegisterTransient<GFramework.Cqrs.Abstractions.Cqrs.IStreamRequestHandler<ReflectionBenchmarkStreamRequest, ReflectionBenchmarkResponse>, ReflectionBenchmarkStreamHandler>();
|
||||
});
|
||||
_reflectionRuntime = GFramework.Cqrs.CqrsRuntimeFactory.CreateRuntime(
|
||||
_reflectionContainer,
|
||||
LoggerFactoryResolver.Provider.CreateLogger(nameof(StreamInvokerBenchmarks) + ".Reflection"));
|
||||
|
||||
_generatedContainer = BenchmarkHostFactory.CreateFrozenGFrameworkContainer(container =>
|
||||
{
|
||||
container.RegisterCqrsHandlersFromAssembly(typeof(StreamInvokerBenchmarks).Assembly);
|
||||
});
|
||||
_generatedRuntime = GFramework.Cqrs.CqrsRuntimeFactory.CreateRuntime(
|
||||
_generatedContainer,
|
||||
LoggerFactoryResolver.Provider.CreateLogger(nameof(StreamInvokerBenchmarks) + ".Generated"));
|
||||
|
||||
_serviceProvider = BenchmarkHostFactory.CreateMediatRServiceProvider(
|
||||
configure: null,
|
||||
typeof(StreamInvokerBenchmarks),
|
||||
static candidateType => candidateType == typeof(MediatRBenchmarkStreamHandler),
|
||||
ServiceLifetime.Transient);
|
||||
_mediatr = _serviceProvider.GetRequiredService<IMediator>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 释放 MediatR 对照组使用的 DI 宿主,并清理静态 dispatcher 缓存。
|
||||
/// </summary>
|
||||
[GlobalCleanup]
|
||||
public void Cleanup()
|
||||
{
|
||||
try
|
||||
{
|
||||
BenchmarkCleanupHelper.DisposeAll(_reflectionContainer, _generatedContainer, _serviceProvider);
|
||||
}
|
||||
finally
|
||||
{
|
||||
BenchmarkDispatcherCacheHelper.ClearDispatcherCaches();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 直接调用最小 stream handler 并完整枚举,作为 dispatch 额外开销 baseline。
|
||||
/// </summary>
|
||||
[Benchmark(Baseline = true)]
|
||||
public async ValueTask Stream_Baseline()
|
||||
{
|
||||
await foreach (var response in _baselineHandler.Handle(_reflectionRequest, CancellationToken.None).ConfigureAwait(false))
|
||||
{
|
||||
_ = response;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 通过 GFramework.CQRS 反射 stream binding 路径创建并完整枚举 stream。
|
||||
/// </summary>
|
||||
[Benchmark]
|
||||
public async ValueTask Stream_GFrameworkReflection()
|
||||
{
|
||||
await foreach (var response in _reflectionRuntime.CreateStream(BenchmarkContext.Instance, _reflectionRequest, CancellationToken.None)
|
||||
.ConfigureAwait(false))
|
||||
{
|
||||
_ = response;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 通过 generated stream invoker provider 预热后的 GFramework.CQRS runtime 创建并完整枚举 stream。
|
||||
/// </summary>
|
||||
[Benchmark]
|
||||
public async ValueTask Stream_GFrameworkGenerated()
|
||||
{
|
||||
await foreach (var response in _generatedRuntime.CreateStream(BenchmarkContext.Instance, _generatedRequest, CancellationToken.None)
|
||||
.ConfigureAwait(false))
|
||||
{
|
||||
_ = response;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 通过 MediatR 创建并完整枚举 stream,作为外部对照。
|
||||
/// </summary>
|
||||
[Benchmark]
|
||||
public async ValueTask Stream_MediatR()
|
||||
{
|
||||
await foreach (var response in _mediatr.CreateStream(_mediatrRequest, CancellationToken.None).ConfigureAwait(false))
|
||||
{
|
||||
_ = response;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reflection runtime stream request。
|
||||
/// </summary>
|
||||
/// <param name="Id">请求标识。</param>
|
||||
/// <param name="ItemCount">返回元素数量。</param>
|
||||
public sealed record ReflectionBenchmarkStreamRequest(Guid Id, int ItemCount) :
|
||||
GFramework.Cqrs.Abstractions.Cqrs.IStreamRequest<ReflectionBenchmarkResponse>;
|
||||
|
||||
/// <summary>
|
||||
/// Reflection runtime stream response。
|
||||
/// </summary>
|
||||
/// <param name="Id">响应标识。</param>
|
||||
public sealed record ReflectionBenchmarkResponse(Guid Id);
|
||||
|
||||
/// <summary>
|
||||
/// Generated runtime stream request。
|
||||
/// </summary>
|
||||
/// <param name="Id">请求标识。</param>
|
||||
/// <param name="ItemCount">返回元素数量。</param>
|
||||
public sealed record GeneratedBenchmarkStreamRequest(Guid Id, int ItemCount) :
|
||||
GFramework.Cqrs.Abstractions.Cqrs.IStreamRequest<GeneratedBenchmarkResponse>;
|
||||
|
||||
/// <summary>
|
||||
/// Generated runtime stream response。
|
||||
/// </summary>
|
||||
/// <param name="Id">响应标识。</param>
|
||||
public sealed record GeneratedBenchmarkResponse(Guid Id);
|
||||
|
||||
/// <summary>
|
||||
/// MediatR stream request。
|
||||
/// </summary>
|
||||
/// <param name="Id">请求标识。</param>
|
||||
/// <param name="ItemCount">返回元素数量。</param>
|
||||
public sealed record MediatRBenchmarkStreamRequest(Guid Id, int ItemCount) :
|
||||
MediatR.IStreamRequest<MediatRBenchmarkResponse>;
|
||||
|
||||
/// <summary>
|
||||
/// MediatR stream response。
|
||||
/// </summary>
|
||||
/// <param name="Id">响应标识。</param>
|
||||
public sealed record MediatRBenchmarkResponse(Guid Id);
|
||||
|
||||
/// <summary>
|
||||
/// Reflection runtime 的最小 stream request handler。
|
||||
/// </summary>
|
||||
public sealed class ReflectionBenchmarkStreamHandler :
|
||||
GFramework.Cqrs.Abstractions.Cqrs.IStreamRequestHandler<ReflectionBenchmarkStreamRequest, ReflectionBenchmarkResponse>
|
||||
{
|
||||
/// <summary>
|
||||
/// 处理 reflection benchmark stream request。
|
||||
/// </summary>
|
||||
public IAsyncEnumerable<ReflectionBenchmarkResponse> Handle(
|
||||
ReflectionBenchmarkStreamRequest request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
return EnumerateAsync(
|
||||
request.Id,
|
||||
request.ItemCount,
|
||||
static id => new ReflectionBenchmarkResponse(id),
|
||||
cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Generated runtime 的最小 stream request handler。
|
||||
/// </summary>
|
||||
public sealed class GeneratedBenchmarkStreamHandler :
|
||||
GFramework.Cqrs.Abstractions.Cqrs.IStreamRequestHandler<GeneratedBenchmarkStreamRequest, GeneratedBenchmarkResponse>
|
||||
{
|
||||
/// <summary>
|
||||
/// 处理 generated benchmark stream request。
|
||||
/// </summary>
|
||||
public IAsyncEnumerable<GeneratedBenchmarkResponse> Handle(
|
||||
GeneratedBenchmarkStreamRequest request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
return EnumerateAsync(
|
||||
request.Id,
|
||||
request.ItemCount,
|
||||
static id => new GeneratedBenchmarkResponse(id),
|
||||
cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// MediatR 对照组的最小 stream request handler。
|
||||
/// </summary>
|
||||
public sealed class MediatRBenchmarkStreamHandler :
|
||||
MediatR.IStreamRequestHandler<MediatRBenchmarkStreamRequest, MediatRBenchmarkResponse>
|
||||
{
|
||||
/// <summary>
|
||||
/// 处理 MediatR benchmark stream request。
|
||||
/// </summary>
|
||||
public IAsyncEnumerable<MediatRBenchmarkResponse> Handle(
|
||||
MediatRBenchmarkStreamRequest request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
return EnumerateAsync(
|
||||
request.Id,
|
||||
request.ItemCount,
|
||||
static id => new MediatRBenchmarkResponse(id),
|
||||
cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 为三组 stream benchmark 构造相同形状的低噪声异步枚举,避免枚举体差异干扰 invoker 对照。
|
||||
/// </summary>
|
||||
private static async IAsyncEnumerable<TResponse> EnumerateAsync<TResponse>(
|
||||
Guid id,
|
||||
int itemCount,
|
||||
Func<Guid, TResponse> responseFactory,
|
||||
[System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken)
|
||||
{
|
||||
for (var index = 0; index < itemCount; index++)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
yield return responseFactory(id);
|
||||
await Task.CompletedTask.ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
186
GFramework.Cqrs.Benchmarks/Messaging/StreamingBenchmarks.cs
Normal file
186
GFramework.Cqrs.Benchmarks/Messaging/StreamingBenchmarks.cs
Normal file
@ -0,0 +1,186 @@
|
||||
// Copyright (c) 2025-2026 GeWuYou
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
using BenchmarkDotNet.Attributes;
|
||||
using BenchmarkDotNet.Columns;
|
||||
using BenchmarkDotNet.Configs;
|
||||
using BenchmarkDotNet.Diagnosers;
|
||||
using BenchmarkDotNet.Jobs;
|
||||
using BenchmarkDotNet.Order;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using GFramework.Core.Abstractions.Logging;
|
||||
using GFramework.Core.Ioc;
|
||||
using GFramework.Core.Logging;
|
||||
using GFramework.Cqrs.Abstractions.Cqrs;
|
||||
using MediatR;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace GFramework.Cqrs.Benchmarks.Messaging;
|
||||
|
||||
/// <summary>
|
||||
/// 对比单个 stream request 在直接调用、GFramework.CQRS runtime 与 MediatR 之间的完整枚举开销。
|
||||
/// </summary>
|
||||
[Config(typeof(Config))]
|
||||
public class StreamingBenchmarks
|
||||
{
|
||||
private MicrosoftDiContainer _container = null!;
|
||||
private ICqrsRuntime _runtime = null!;
|
||||
private ServiceProvider _serviceProvider = null!;
|
||||
private IMediator _mediatr = null!;
|
||||
private BenchmarkStreamHandler _baselineHandler = null!;
|
||||
private BenchmarkStreamRequest _request = null!;
|
||||
|
||||
/// <summary>
|
||||
/// 配置 stream benchmark 的公共输出格式。
|
||||
/// </summary>
|
||||
private sealed class Config : ManualConfig
|
||||
{
|
||||
public Config()
|
||||
{
|
||||
AddJob(Job.Default);
|
||||
AddColumnProvider(DefaultColumnProviders.Instance);
|
||||
AddColumn(new CustomColumn("Scenario", static (_, _) => "StreamRequest"));
|
||||
AddDiagnoser(MemoryDiagnoser.Default);
|
||||
WithOrderer(new DefaultOrderer(SummaryOrderPolicy.FastestToSlowest, MethodOrderPolicy.Declared));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 构建 stream dispatch 所需的最小 runtime 宿主和对照对象。
|
||||
/// </summary>
|
||||
[GlobalSetup]
|
||||
public void Setup()
|
||||
{
|
||||
LoggerFactoryResolver.Provider = new ConsoleLoggerFactoryProvider
|
||||
{
|
||||
MinLevel = LogLevel.Fatal
|
||||
};
|
||||
Fixture.Setup("StreamRequest", handlerCount: 1, pipelineCount: 0);
|
||||
|
||||
_baselineHandler = new BenchmarkStreamHandler();
|
||||
_container = BenchmarkHostFactory.CreateFrozenGFrameworkContainer(container =>
|
||||
{
|
||||
container.RegisterSingleton<GFramework.Cqrs.Abstractions.Cqrs.IStreamRequestHandler<BenchmarkStreamRequest, BenchmarkResponse>>(
|
||||
_baselineHandler);
|
||||
});
|
||||
_runtime = GFramework.Cqrs.CqrsRuntimeFactory.CreateRuntime(
|
||||
_container,
|
||||
LoggerFactoryResolver.Provider.CreateLogger(nameof(StreamingBenchmarks)));
|
||||
|
||||
_serviceProvider = BenchmarkHostFactory.CreateMediatRServiceProvider(
|
||||
configure: null,
|
||||
typeof(StreamingBenchmarks),
|
||||
static candidateType => candidateType == typeof(BenchmarkStreamHandler),
|
||||
ServiceLifetime.Singleton);
|
||||
_mediatr = _serviceProvider.GetRequiredService<IMediator>();
|
||||
|
||||
_request = new BenchmarkStreamRequest(Guid.NewGuid(), 3);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 释放 MediatR 对照组使用的 DI 宿主。
|
||||
/// </summary>
|
||||
[GlobalCleanup]
|
||||
public void Cleanup()
|
||||
{
|
||||
BenchmarkCleanupHelper.DisposeAll(_container, _serviceProvider);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 直接调用 handler 并完整枚举响应序列,作为 stream dispatch 额外开销的 baseline。
|
||||
/// </summary>
|
||||
[Benchmark(Baseline = true)]
|
||||
public async ValueTask Stream_Baseline()
|
||||
{
|
||||
await foreach (var response in _baselineHandler.Handle(_request, CancellationToken.None).ConfigureAwait(false))
|
||||
{
|
||||
_ = response;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 通过 GFramework.CQRS runtime 创建并完整枚举 stream。
|
||||
/// </summary>
|
||||
[Benchmark]
|
||||
public async ValueTask Stream_GFrameworkCqrs()
|
||||
{
|
||||
await foreach (var response in _runtime.CreateStream(BenchmarkContext.Instance, _request, CancellationToken.None)
|
||||
.ConfigureAwait(false))
|
||||
{
|
||||
_ = response;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 通过 MediatR 创建并完整枚举 stream,作为外部设计对照。
|
||||
/// </summary>
|
||||
[Benchmark]
|
||||
public async ValueTask Stream_MediatR()
|
||||
{
|
||||
await foreach (var response in _mediatr.CreateStream(_request, CancellationToken.None).ConfigureAwait(false))
|
||||
{
|
||||
_ = response;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Benchmark stream request。
|
||||
/// </summary>
|
||||
/// <param name="Id">请求标识。</param>
|
||||
/// <param name="ItemCount">返回元素数量。</param>
|
||||
public sealed record BenchmarkStreamRequest(Guid Id, int ItemCount) :
|
||||
GFramework.Cqrs.Abstractions.Cqrs.IStreamRequest<BenchmarkResponse>,
|
||||
MediatR.IStreamRequest<BenchmarkResponse>;
|
||||
|
||||
/// <summary>
|
||||
/// 复用 request benchmark 的响应结构,保持跨场景可比性。
|
||||
/// </summary>
|
||||
/// <param name="Id">响应标识。</param>
|
||||
public sealed record BenchmarkResponse(Guid Id);
|
||||
|
||||
/// <summary>
|
||||
/// 同时实现 GFramework.CQRS 与 MediatR 契约的最小 stream handler。
|
||||
/// </summary>
|
||||
public sealed class BenchmarkStreamHandler :
|
||||
GFramework.Cqrs.Abstractions.Cqrs.IStreamRequestHandler<BenchmarkStreamRequest, BenchmarkResponse>,
|
||||
MediatR.IStreamRequestHandler<BenchmarkStreamRequest, BenchmarkResponse>
|
||||
{
|
||||
/// <summary>
|
||||
/// 处理 GFramework.CQRS stream request。
|
||||
/// </summary>
|
||||
public IAsyncEnumerable<BenchmarkResponse> Handle(
|
||||
BenchmarkStreamRequest request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
return EnumerateAsync(request, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 处理 MediatR stream request。
|
||||
/// </summary>
|
||||
IAsyncEnumerable<BenchmarkResponse> MediatR.IStreamRequestHandler<BenchmarkStreamRequest, BenchmarkResponse>.Handle(
|
||||
BenchmarkStreamRequest request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
return EnumerateAsync(request, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 为 benchmark 构造稳定、低噪声的异步响应序列。
|
||||
/// </summary>
|
||||
private static async IAsyncEnumerable<BenchmarkResponse> EnumerateAsync(
|
||||
BenchmarkStreamRequest request,
|
||||
[System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken)
|
||||
{
|
||||
for (int index = 0; index < request.ItemCount; index++)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
yield return new BenchmarkResponse(request.Id);
|
||||
await Task.CompletedTask.ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
23
GFramework.Cqrs.Benchmarks/Program.cs
Normal file
23
GFramework.Cqrs.Benchmarks/Program.cs
Normal file
@ -0,0 +1,23 @@
|
||||
// Copyright (c) 2025-2026 GeWuYou
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
using BenchmarkDotNet.Loggers;
|
||||
using BenchmarkDotNet.Running;
|
||||
|
||||
namespace GFramework.Cqrs.Benchmarks;
|
||||
|
||||
/// <summary>
|
||||
/// 提供 GFramework.CQRS benchmark 的统一命令行入口。
|
||||
/// </summary>
|
||||
internal static class Program
|
||||
{
|
||||
/// <summary>
|
||||
/// 运行当前程序集中的全部 benchmark。
|
||||
/// </summary>
|
||||
/// <param name="args">透传给 BenchmarkDotNet 的命令行参数。</param>
|
||||
private static void Main(string[] args)
|
||||
{
|
||||
ConsoleLogger.Default.WriteLine("Running GFramework.Cqrs benchmarks");
|
||||
BenchmarkSwitcher.FromAssembly(typeof(Program).Assembly).Run(args);
|
||||
}
|
||||
}
|
||||
45
GFramework.Cqrs.Benchmarks/README.md
Normal file
45
GFramework.Cqrs.Benchmarks/README.md
Normal file
@ -0,0 +1,45 @@
|
||||
# GFramework.Cqrs.Benchmarks
|
||||
|
||||
该模块承载 `GFramework.Cqrs` 的独立性能基准工程,用于持续比较运行时 dispatch、publish、cold-start 与后续 generator / pipeline 收口的成本变化。
|
||||
|
||||
## 目的
|
||||
|
||||
- 为 `GFramework.Cqrs` 建立独立于 NUnit 集成测试的 BenchmarkDotNet 基线
|
||||
- 参考 `ai-libs/Mediator/benchmarks` 的场景组织方式,逐步补齐 request、notification、stream 与初始化成本对比
|
||||
- 为后续吸收 `Mediator` 的 dispatch 设计、fixture 组织和对比矩阵提供可重复验证入口
|
||||
|
||||
## 当前内容
|
||||
|
||||
- `Program.cs`
|
||||
- benchmark 命令行入口
|
||||
- `Messaging/Fixture.cs`
|
||||
- 运行前输出并校验场景配置
|
||||
- `Messaging/RequestBenchmarks.cs`
|
||||
- direct handler、`GFramework.Cqrs` runtime 与 `MediatR` 的 request steady-state dispatch 对比
|
||||
- `Messaging/RequestPipelineBenchmarks.cs`
|
||||
- `0 / 1 / 4` 个 pipeline 行为下,direct handler、`GFramework.Cqrs` runtime 与 `MediatR` 的 request steady-state dispatch 对比
|
||||
- `Messaging/RequestStartupBenchmarks.cs`
|
||||
- `Initialization` 与 `ColdStart` 两组 request startup 成本对比,补齐与 `Mediator` comparison benchmark 更接近的 startup 维度
|
||||
- `Messaging/RequestInvokerBenchmarks.cs`
|
||||
- direct handler、`GFramework.Cqrs` reflection runtime、handwritten generated-invoker runtime 与 `MediatR` 的 request steady-state dispatch 对比
|
||||
- `Messaging/StreamInvokerBenchmarks.cs`
|
||||
- direct handler、`GFramework.Cqrs` reflection runtime、handwritten generated-invoker runtime 与 `MediatR` 的 stream 完整枚举对比
|
||||
- `Messaging/NotificationBenchmarks.cs`
|
||||
- `GFramework.Cqrs` runtime 与 `MediatR` 的单处理器 notification publish 对比
|
||||
- `Messaging/StreamingBenchmarks.cs`
|
||||
- direct handler、`GFramework.Cqrs` runtime 与 `MediatR` 的 stream request 完整枚举对比
|
||||
|
||||
## 最小使用方式
|
||||
|
||||
```bash
|
||||
dotnet run --project GFramework.Cqrs.Benchmarks/GFramework.Cqrs.Benchmarks.csproj -c Release
|
||||
```
|
||||
|
||||
也可以通过 `BenchmarkDotNet` 过滤器只运行某一类场景。
|
||||
|
||||
## 后续扩展方向
|
||||
|
||||
- generated invoker provider 与纯反射 dispatch 对比
|
||||
- generated stream invoker provider 与纯反射建流对比
|
||||
- registration / service lifetime 矩阵
|
||||
- request / stream 的真实 source-generator 产物与 handwritten generated provider 对照
|
||||
@ -884,7 +884,9 @@ public sealed class SchemaConfigGenerator : IIncrementalGenerator
|
||||
/// <summary>
|
||||
/// 递归拒绝当前共享子集尚未支持的开放对象关键字形状。
|
||||
/// 当前对象字段集默认是闭合的,因此这里只接受显式重复该语义的
|
||||
/// <c>additionalProperties: false</c>。
|
||||
/// <c>additionalProperties: false</c>,并继续拒绝
|
||||
/// <c>patternProperties</c>、<c>propertyNames</c> 与
|
||||
/// <c>unevaluatedProperties</c> 这类会重新打开对象形状的关键字。
|
||||
/// </summary>
|
||||
/// <param name="filePath">Schema 文件路径。</param>
|
||||
/// <param name="displayPath">逻辑字段路径。</param>
|
||||
@ -959,12 +961,7 @@ public sealed class SchemaConfigGenerator : IIncrementalGenerator
|
||||
out Diagnostic? diagnostic)
|
||||
{
|
||||
diagnostic = null;
|
||||
if (!element.TryGetProperty("additionalProperties", out var additionalPropertiesElement))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if (additionalPropertiesElement.ValueKind == JsonValueKind.False)
|
||||
if (TryGetUnsupportedOpenObjectKeywordName(element) is not { } keywordName)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
@ -974,8 +971,8 @@ public sealed class SchemaConfigGenerator : IIncrementalGenerator
|
||||
CreateFileLocation(filePath),
|
||||
Path.GetFileName(filePath),
|
||||
displayPath,
|
||||
"additionalProperties",
|
||||
"The current config schema subset only accepts 'additionalProperties: false' so object fields remain closed and strongly typed.");
|
||||
keywordName,
|
||||
"The current config schema subset only accepts 'additionalProperties: false' and rejects keywords that reopen object shapes so fields remain closed and strongly typed.");
|
||||
return false;
|
||||
}
|
||||
|
||||
@ -991,6 +988,25 @@ public sealed class SchemaConfigGenerator : IIncrementalGenerator
|
||||
null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 返回当前节点声明的首个未支持开放对象关键字。
|
||||
/// </summary>
|
||||
/// <param name="element">当前 schema 节点。</param>
|
||||
/// <returns>命中的关键字名称;未声明时返回空。</returns>
|
||||
private static string? TryGetUnsupportedOpenObjectKeywordName(JsonElement element)
|
||||
{
|
||||
if (element.TryGetProperty("additionalProperties", out var additionalPropertiesElement) &&
|
||||
additionalPropertiesElement.ValueKind != JsonValueKind.False)
|
||||
{
|
||||
return "additionalProperties";
|
||||
}
|
||||
|
||||
return element.TryGetProperty("patternProperties", out _) ? "patternProperties" :
|
||||
element.TryGetProperty("propertyNames", out _) ? "propertyNames" :
|
||||
element.TryGetProperty("unevaluatedProperties", out _) ? "unevaluatedProperties" :
|
||||
null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 以统一顺序递归遍历 schema 树,并把每个节点交给调用方提供的校验逻辑。
|
||||
/// 该遍历覆盖对象属性、<c>dependentSchemas</c> / <c>allOf</c> /
|
||||
|
||||
@ -81,6 +81,9 @@ GameProject/
|
||||
- `oneOf`
|
||||
- `anyOf`
|
||||
- 非 `false` 的 `additionalProperties`
|
||||
- `patternProperties`
|
||||
- `propertyNames`
|
||||
- `unevaluatedProperties`
|
||||
- 其他依赖开放对象形状、联合分支或属性合并的复杂组合约束
|
||||
|
||||
遇到这些情况时,建议先回到 [配置系统文档](../docs/zh-CN/game/config-system.md) 和原始 schema / YAML 设计本体,确认是否需要调整配置建模方式,而不是默认期待生成器直接支持完整 `JSON Schema` 语义。
|
||||
|
||||
@ -448,6 +448,55 @@ public sealed class YamlConfigLoaderAllOfTests
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 验证运行时会拒绝会重新打开对象形状的其他开放对象关键字。
|
||||
/// </summary>
|
||||
[TestCase("patternProperties", """
|
||||
{
|
||||
"^dynamic-": { "type": "integer" }
|
||||
}
|
||||
""")]
|
||||
[TestCase("propertyNames", """
|
||||
{
|
||||
"pattern": "^[a-z]+$"
|
||||
}
|
||||
""")]
|
||||
[TestCase("unevaluatedProperties", "false")]
|
||||
public void LoadAsync_Should_Throw_When_Object_Schema_Declares_Unsupported_OpenObject_Keyword(
|
||||
string keywordName,
|
||||
string keywordValueJson)
|
||||
{
|
||||
CreateConfigFile(
|
||||
"monster/slime.yaml",
|
||||
BuildMonsterConfigYaml(
|
||||
"""
|
||||
itemCount: 3
|
||||
"""));
|
||||
CreateSchemaFile(
|
||||
"schemas/monster.schema.json",
|
||||
BuildMonsterSchema(
|
||||
DefaultRewardPropertiesJson,
|
||||
DefaultAllOfJson,
|
||||
$$"""
|
||||
"{{keywordName}}": {{keywordValueJson}}
|
||||
"""));
|
||||
|
||||
var loader = CreateMonsterRewardLoader();
|
||||
var registry = CreateRegistry();
|
||||
|
||||
var exception = Assert.ThrowsAsync<ConfigLoadException>(() => loader.LoadAsync(registry));
|
||||
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(exception, Is.Not.Null);
|
||||
Assert.That(exception!.Diagnostic.FailureKind, Is.EqualTo(ConfigLoadFailureKind.SchemaUnsupported));
|
||||
Assert.That(exception.Diagnostic.DisplayPath, Is.EqualTo("reward"));
|
||||
Assert.That(exception.Message, Does.Contain($"unsupported '{keywordName}' metadata"));
|
||||
Assert.That(exception.Message, Does.Contain("rejects keywords that reopen object shapes"));
|
||||
Assert.That(registry.Count, Is.EqualTo(0));
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 验证 allOf 条目只接受 object-typed schema。
|
||||
/// </summary>
|
||||
|
||||
@ -373,7 +373,9 @@ internal static partial class YamlConfigSchemaValidator
|
||||
/// <summary>
|
||||
/// 显式拒绝当前共享子集中尚未支持的开放对象关键字形状。
|
||||
/// 当前配置系统默认采用闭合对象字段集;这里只接受显式重复该语义的
|
||||
/// <c>additionalProperties: false</c>,继续拒绝会引入动态字段形状的其它形式。
|
||||
/// <c>additionalProperties: false</c>,并继续拒绝
|
||||
/// <c>patternProperties</c>、<c>propertyNames</c> 与
|
||||
/// <c>unevaluatedProperties</c> 这类会重新打开对象形状的关键字。
|
||||
/// </summary>
|
||||
/// <param name="tableName">所属配置表名称。</param>
|
||||
/// <param name="schemaPath">Schema 文件路径。</param>
|
||||
@ -385,12 +387,7 @@ internal static partial class YamlConfigSchemaValidator
|
||||
string propertyPath,
|
||||
JsonElement element)
|
||||
{
|
||||
if (!element.TryGetProperty("additionalProperties", out var additionalPropertiesElement))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (additionalPropertiesElement.ValueKind == JsonValueKind.False)
|
||||
if (TryGetUnsupportedOpenObjectKeywordName(element) is not { } keywordName)
|
||||
{
|
||||
return;
|
||||
}
|
||||
@ -398,8 +395,8 @@ internal static partial class YamlConfigSchemaValidator
|
||||
throw ConfigLoadExceptionFactory.Create(
|
||||
ConfigLoadFailureKind.SchemaUnsupported,
|
||||
tableName,
|
||||
$"Property '{propertyPath}' in schema file '{schemaPath}' uses unsupported 'additionalProperties' metadata. " +
|
||||
"The current config schema subset only accepts 'additionalProperties: false' so object fields remain closed and strongly typed.",
|
||||
$"Property '{propertyPath}' in schema file '{schemaPath}' uses unsupported '{keywordName}' metadata. " +
|
||||
"The current config schema subset only accepts 'additionalProperties: false' and rejects keywords that reopen object shapes so fields remain closed and strongly typed.",
|
||||
schemaPath: schemaPath,
|
||||
displayPath: GetDiagnosticPath(propertyPath));
|
||||
}
|
||||
@ -416,6 +413,25 @@ internal static partial class YamlConfigSchemaValidator
|
||||
null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 返回当前节点声明的首个未支持开放对象关键字。
|
||||
/// </summary>
|
||||
/// <param name="element">当前 schema 节点。</param>
|
||||
/// <returns>命中的关键字名称;未声明时返回空。</returns>
|
||||
private static string? TryGetUnsupportedOpenObjectKeywordName(JsonElement element)
|
||||
{
|
||||
if (element.TryGetProperty("additionalProperties", out var additionalPropertiesElement) &&
|
||||
additionalPropertiesElement.ValueKind != JsonValueKind.False)
|
||||
{
|
||||
return "additionalProperties";
|
||||
}
|
||||
|
||||
return element.TryGetProperty("patternProperties", out _) ? "patternProperties" :
|
||||
element.TryGetProperty("propertyNames", out _) ? "propertyNames" :
|
||||
element.TryGetProperty("unevaluatedProperties", out _) ? "unevaluatedProperties" :
|
||||
null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 解析 schema 节点声明的类型名称,并在缺失或类型错误时立刻给出定位清晰的诊断。
|
||||
/// </summary>
|
||||
|
||||
@ -1965,6 +1965,58 @@ public class SchemaConfigGeneratorTests
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 验证生成器会拒绝会重新打开对象形状的其他开放对象关键字。
|
||||
/// </summary>
|
||||
[TestCase("patternProperties", """
|
||||
{
|
||||
"^dynamic-": { "type": "integer" }
|
||||
}
|
||||
""")]
|
||||
[TestCase("propertyNames", """
|
||||
{
|
||||
"pattern": "^[a-z]+$"
|
||||
}
|
||||
""")]
|
||||
[TestCase("unevaluatedProperties", "false")]
|
||||
public void Run_Should_Report_Diagnostic_When_Object_Schema_Declares_Unsupported_OpenObject_Keyword(
|
||||
string keywordName,
|
||||
string keywordValueJson)
|
||||
{
|
||||
const string source = DummySource;
|
||||
var schema = $$"""
|
||||
{
|
||||
"type": "object",
|
||||
"required": ["id", "reward"],
|
||||
"properties": {
|
||||
"id": { "type": "integer" },
|
||||
"reward": {
|
||||
"type": "object",
|
||||
"{{keywordName}}": {{keywordValueJson}},
|
||||
"properties": {
|
||||
"itemCount": { "type": "integer" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
var result = SchemaGeneratorTestDriver.Run(
|
||||
source,
|
||||
("monster.schema.json", schema));
|
||||
|
||||
var diagnostic = result.Results.Single().Diagnostics.Single();
|
||||
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(diagnostic.Id, Is.EqualTo("GF_ConfigSchema_016"));
|
||||
Assert.That(diagnostic.Severity, Is.EqualTo(DiagnosticSeverity.Error));
|
||||
Assert.That(diagnostic.GetMessage(), Does.Contain("reward"));
|
||||
Assert.That(diagnostic.GetMessage(), Does.Contain(keywordName));
|
||||
Assert.That(diagnostic.GetMessage(), Does.Contain("rejects keywords that reopen object shapes"));
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 验证 <c>then</c> 子 schema 内的非法 <c>format</c> 也会在生成阶段直接给出诊断。
|
||||
/// </summary>
|
||||
|
||||
@ -2003,6 +2003,120 @@ public class CqrsHandlerRegistryGeneratorTests
|
||||
}
|
||||
""";
|
||||
|
||||
private const string MixedRequestInvokerProviderSource = """
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Reflection;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Microsoft.Extensions.DependencyInjection
|
||||
{
|
||||
public interface IServiceCollection { }
|
||||
|
||||
public static class ServiceCollectionServiceExtensions
|
||||
{
|
||||
public static void AddTransient(IServiceCollection services, Type serviceType, Type implementationType) { }
|
||||
}
|
||||
}
|
||||
|
||||
namespace GFramework.Core.Abstractions.Logging
|
||||
{
|
||||
public interface ILogger
|
||||
{
|
||||
void Debug(string msg);
|
||||
}
|
||||
}
|
||||
|
||||
namespace GFramework.Cqrs.Abstractions.Cqrs
|
||||
{
|
||||
public interface IRequest<TResponse> { }
|
||||
public interface INotification { }
|
||||
public interface IStreamRequest<TResponse> { }
|
||||
|
||||
public interface IRequestHandler<in TRequest, TResponse> where TRequest : IRequest<TResponse>
|
||||
{
|
||||
ValueTask<TResponse> Handle(TRequest request, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
public interface INotificationHandler<in TNotification> where TNotification : INotification { }
|
||||
public interface IStreamRequestHandler<in TRequest, out TResponse> where TRequest : IStreamRequest<TResponse> { }
|
||||
}
|
||||
|
||||
namespace GFramework.Cqrs
|
||||
{
|
||||
public interface ICqrsHandlerRegistry
|
||||
{
|
||||
void Register(Microsoft.Extensions.DependencyInjection.IServiceCollection services, GFramework.Core.Abstractions.Logging.ILogger logger);
|
||||
}
|
||||
|
||||
public interface ICqrsRequestInvokerProvider
|
||||
{
|
||||
bool TryGetDescriptor(Type requestType, Type responseType, out CqrsRequestInvokerDescriptor? descriptor);
|
||||
}
|
||||
|
||||
public interface IEnumeratesCqrsRequestInvokerDescriptors
|
||||
{
|
||||
IReadOnlyList<CqrsRequestInvokerDescriptorEntry> GetDescriptors();
|
||||
}
|
||||
|
||||
public sealed class CqrsRequestInvokerDescriptor
|
||||
{
|
||||
public CqrsRequestInvokerDescriptor(Type handlerType, MethodInfo invokerMethod) { }
|
||||
}
|
||||
|
||||
public sealed class CqrsRequestInvokerDescriptorEntry
|
||||
{
|
||||
public CqrsRequestInvokerDescriptorEntry(Type requestType, Type responseType, CqrsRequestInvokerDescriptor descriptor)
|
||||
{
|
||||
RequestType = requestType;
|
||||
ResponseType = responseType;
|
||||
Descriptor = descriptor;
|
||||
}
|
||||
|
||||
public Type RequestType { get; }
|
||||
|
||||
public Type ResponseType { get; }
|
||||
|
||||
public CqrsRequestInvokerDescriptor Descriptor { get; }
|
||||
}
|
||||
|
||||
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
|
||||
public sealed class CqrsHandlerRegistryAttribute : Attribute
|
||||
{
|
||||
public CqrsHandlerRegistryAttribute(Type registryType) { }
|
||||
}
|
||||
}
|
||||
|
||||
namespace TestApp
|
||||
{
|
||||
using GFramework.Cqrs.Abstractions.Cqrs;
|
||||
|
||||
public sealed record AlphaRequest() : IRequest<string>;
|
||||
|
||||
public sealed record BetaRequest() : IRequest<int>;
|
||||
|
||||
public sealed class AlphaHandler : IRequestHandler<AlphaRequest, string>
|
||||
{
|
||||
public ValueTask<string> Handle(AlphaRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
return ValueTask.FromResult("alpha");
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class Container
|
||||
{
|
||||
private sealed class HiddenBetaHandler : IRequestHandler<BetaRequest, int>
|
||||
{
|
||||
public ValueTask<int> Handle(BetaRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
return ValueTask.FromResult(42);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
private const string HiddenImplementationStreamInvokerProviderSource = """
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
@ -2108,6 +2222,122 @@ public class CqrsHandlerRegistryGeneratorTests
|
||||
}
|
||||
""";
|
||||
|
||||
private const string MixedStreamInvokerProviderSource = """
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Reflection;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Microsoft.Extensions.DependencyInjection
|
||||
{
|
||||
public interface IServiceCollection { }
|
||||
|
||||
public static class ServiceCollectionServiceExtensions
|
||||
{
|
||||
public static void AddTransient(IServiceCollection services, Type serviceType, Type implementationType) { }
|
||||
}
|
||||
}
|
||||
|
||||
namespace GFramework.Core.Abstractions.Logging
|
||||
{
|
||||
public interface ILogger
|
||||
{
|
||||
void Debug(string msg);
|
||||
}
|
||||
}
|
||||
|
||||
namespace GFramework.Cqrs.Abstractions.Cqrs
|
||||
{
|
||||
public interface IRequest<TResponse> { }
|
||||
public interface INotification { }
|
||||
public interface IStreamRequest<TResponse> { }
|
||||
|
||||
public interface IRequestHandler<in TRequest, TResponse> where TRequest : IRequest<TResponse> { }
|
||||
public interface INotificationHandler<in TNotification> where TNotification : INotification { }
|
||||
|
||||
public interface IStreamRequestHandler<in TRequest, out TResponse> where TRequest : IStreamRequest<TResponse>
|
||||
{
|
||||
IAsyncEnumerable<TResponse> Handle(TRequest request, CancellationToken cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
namespace GFramework.Cqrs
|
||||
{
|
||||
public interface ICqrsHandlerRegistry
|
||||
{
|
||||
void Register(Microsoft.Extensions.DependencyInjection.IServiceCollection services, GFramework.Core.Abstractions.Logging.ILogger logger);
|
||||
}
|
||||
|
||||
public interface ICqrsStreamInvokerProvider
|
||||
{
|
||||
bool TryGetDescriptor(Type requestType, Type responseType, out CqrsStreamInvokerDescriptor? descriptor);
|
||||
}
|
||||
|
||||
public interface IEnumeratesCqrsStreamInvokerDescriptors
|
||||
{
|
||||
IReadOnlyList<CqrsStreamInvokerDescriptorEntry> GetDescriptors();
|
||||
}
|
||||
|
||||
public sealed class CqrsStreamInvokerDescriptor
|
||||
{
|
||||
public CqrsStreamInvokerDescriptor(Type handlerType, MethodInfo invokerMethod) { }
|
||||
}
|
||||
|
||||
public sealed class CqrsStreamInvokerDescriptorEntry
|
||||
{
|
||||
public CqrsStreamInvokerDescriptorEntry(Type requestType, Type responseType, CqrsStreamInvokerDescriptor descriptor)
|
||||
{
|
||||
RequestType = requestType;
|
||||
ResponseType = responseType;
|
||||
Descriptor = descriptor;
|
||||
}
|
||||
|
||||
public Type RequestType { get; }
|
||||
|
||||
public Type ResponseType { get; }
|
||||
|
||||
public CqrsStreamInvokerDescriptor Descriptor { get; }
|
||||
}
|
||||
|
||||
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
|
||||
public sealed class CqrsHandlerRegistryAttribute : Attribute
|
||||
{
|
||||
public CqrsHandlerRegistryAttribute(Type registryType) { }
|
||||
}
|
||||
}
|
||||
|
||||
namespace TestApp
|
||||
{
|
||||
using GFramework.Cqrs.Abstractions.Cqrs;
|
||||
|
||||
public sealed record AlphaStream() : IStreamRequest<int>;
|
||||
|
||||
public sealed record BetaStream() : IStreamRequest<string>;
|
||||
|
||||
public sealed class AlphaStreamHandler : IStreamRequestHandler<AlphaStream, int>
|
||||
{
|
||||
public async IAsyncEnumerable<int> Handle(AlphaStream request, CancellationToken cancellationToken)
|
||||
{
|
||||
yield return 1;
|
||||
await Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class Container
|
||||
{
|
||||
private sealed class HiddenBetaStreamHandler : IStreamRequestHandler<BetaStream, string>
|
||||
{
|
||||
public async IAsyncEnumerable<string> Handle(BetaStream request, CancellationToken cancellationToken)
|
||||
{
|
||||
yield return "beta";
|
||||
await Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
private const string PreciseReflectedRequestInvokerProviderBoundarySource = """
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
@ -3052,6 +3282,40 @@ public class CqrsHandlerRegistryGeneratorTests
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 验证当同一轮生成同时包含 direct registration 与“隐藏实现类型 + 可见 handler interface”注册时,
|
||||
/// request invoker provider 会按稳定实现排序生成连续描述符和方法编号。
|
||||
/// </summary>
|
||||
[Test]
|
||||
public void Emits_Request_Invoker_Provider_Metadata_In_Stable_Order_For_Mixed_Direct_And_Reflected_Implementations()
|
||||
{
|
||||
var generatedSource = RunGenerator(MixedRequestInvokerProviderSource);
|
||||
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(
|
||||
generatedSource,
|
||||
Does.Contain(
|
||||
"new global::GFramework.Cqrs.CqrsRequestInvokerDescriptorEntry(typeof(global::TestApp.AlphaRequest), typeof(string), new global::GFramework.Cqrs.CqrsRequestInvokerDescriptor(typeof(global::GFramework.Cqrs.Abstractions.Cqrs.IRequestHandler<global::TestApp.AlphaRequest, string>), typeof(__GFrameworkGeneratedCqrsHandlerRegistry).GetMethod(nameof(InvokeRequestHandler0), global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Static)!))"));
|
||||
Assert.That(
|
||||
generatedSource,
|
||||
Does.Contain(
|
||||
"new global::GFramework.Cqrs.CqrsRequestInvokerDescriptorEntry(typeof(global::TestApp.BetaRequest), typeof(int), new global::GFramework.Cqrs.CqrsRequestInvokerDescriptor(typeof(global::GFramework.Cqrs.Abstractions.Cqrs.IRequestHandler<global::TestApp.BetaRequest, int>), typeof(__GFrameworkGeneratedCqrsHandlerRegistry).GetMethod(nameof(InvokeRequestHandler1), global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Static)!))"));
|
||||
Assert.That(
|
||||
generatedSource,
|
||||
Does.Contain(
|
||||
"private static global::System.Threading.Tasks.ValueTask<string> InvokeRequestHandler0(object handler, object request, global::System.Threading.CancellationToken cancellationToken)"));
|
||||
Assert.That(
|
||||
generatedSource,
|
||||
Does.Contain(
|
||||
"private static global::System.Threading.Tasks.ValueTask<int> InvokeRequestHandler1(object handler, object request, global::System.Threading.CancellationToken cancellationToken)"));
|
||||
Assert.That(
|
||||
generatedSource,
|
||||
Does.Contain(
|
||||
"var typedHandler = (global::GFramework.Cqrs.Abstractions.Cqrs.IRequestHandler<global::TestApp.BetaRequest, int>)handler;"));
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 验证当 runtime 缺少 <c>ICqrsRequestInvokerProvider</c> 时,
|
||||
/// 生成器会整体跳过 request invoker provider 元数据发射,而不是输出半套 descriptor 成员。
|
||||
@ -3265,6 +3529,40 @@ public class CqrsHandlerRegistryGeneratorTests
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 验证当同一轮生成同时包含 direct registration 与“隐藏实现类型 + 可见 handler interface”注册时,
|
||||
/// stream invoker provider 会按稳定实现排序生成连续描述符和方法编号。
|
||||
/// </summary>
|
||||
[Test]
|
||||
public void Emits_Stream_Invoker_Provider_Metadata_In_Stable_Order_For_Mixed_Direct_And_Reflected_Implementations()
|
||||
{
|
||||
var generatedSource = RunGenerator(MixedStreamInvokerProviderSource);
|
||||
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(
|
||||
generatedSource,
|
||||
Does.Contain(
|
||||
"new global::GFramework.Cqrs.CqrsStreamInvokerDescriptorEntry(typeof(global::TestApp.AlphaStream), typeof(int), new global::GFramework.Cqrs.CqrsStreamInvokerDescriptor(typeof(global::GFramework.Cqrs.Abstractions.Cqrs.IStreamRequestHandler<global::TestApp.AlphaStream, int>), typeof(__GFrameworkGeneratedCqrsHandlerRegistry).GetMethod(nameof(InvokeStreamHandler0), global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Static)!))"));
|
||||
Assert.That(
|
||||
generatedSource,
|
||||
Does.Contain(
|
||||
"new global::GFramework.Cqrs.CqrsStreamInvokerDescriptorEntry(typeof(global::TestApp.BetaStream), typeof(string), new global::GFramework.Cqrs.CqrsStreamInvokerDescriptor(typeof(global::GFramework.Cqrs.Abstractions.Cqrs.IStreamRequestHandler<global::TestApp.BetaStream, string>), typeof(__GFrameworkGeneratedCqrsHandlerRegistry).GetMethod(nameof(InvokeStreamHandler1), global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Static)!))"));
|
||||
Assert.That(
|
||||
generatedSource,
|
||||
Does.Contain(
|
||||
"private static object InvokeStreamHandler0(object handler, object request, global::System.Threading.CancellationToken cancellationToken)"));
|
||||
Assert.That(
|
||||
generatedSource,
|
||||
Does.Contain(
|
||||
"private static object InvokeStreamHandler1(object handler, object request, global::System.Threading.CancellationToken cancellationToken)"));
|
||||
Assert.That(
|
||||
generatedSource,
|
||||
Does.Contain(
|
||||
"var typedHandler = (global::GFramework.Cqrs.Abstractions.Cqrs.IStreamRequestHandler<global::TestApp.BetaStream, string>)handler;"));
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 验证当 runtime 缺少 <c>ICqrsStreamInvokerProvider</c> 时,
|
||||
/// 生成器会整体跳过 stream invoker provider 元数据发射,而不是保留孤立的 descriptor 成员。
|
||||
|
||||
@ -74,6 +74,7 @@
|
||||
<None Remove="GFramework.Godot.Tests\**"/>
|
||||
<None Remove="GFramework.Cqrs\**"/>
|
||||
<None Remove="GFramework.Cqrs.Abstractions\**"/>
|
||||
<None Remove="GFramework.Cqrs.Benchmarks\**"/>
|
||||
<None Remove="GFramework.Cqrs.Tests\**"/>
|
||||
<None Remove="GFramework.Tests.Common\**"/>
|
||||
<None Remove="ai-libs\**" />
|
||||
@ -123,6 +124,7 @@
|
||||
<Compile Remove="GFramework.Godot.Tests\**" />
|
||||
<Compile Remove="GFramework.Cqrs\**" />
|
||||
<Compile Remove="GFramework.Cqrs.Abstractions\**" />
|
||||
<Compile Remove="GFramework.Cqrs.Benchmarks\**" />
|
||||
<Compile Remove="GFramework.Cqrs.Tests\**" />
|
||||
<Compile Remove="GFramework.Tests.Common\**" />
|
||||
<Compile Remove="ai-libs\**" />
|
||||
@ -158,6 +160,7 @@
|
||||
<EmbeddedResource Remove="GFramework.Godot.Tests\**" />
|
||||
<EmbeddedResource Remove="GFramework.Cqrs\**" />
|
||||
<EmbeddedResource Remove="GFramework.Cqrs.Abstractions\**" />
|
||||
<EmbeddedResource Remove="GFramework.Cqrs.Benchmarks\**" />
|
||||
<EmbeddedResource Remove="GFramework.Cqrs.Tests\**" />
|
||||
<EmbeddedResource Remove="GFramework.Tests.Common\**" />
|
||||
<EmbeddedResource Remove="ai-libs\**" />
|
||||
|
||||
@ -50,6 +50,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GFramework.Cqrs.SourceGener
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GFramework.Game.SourceGenerators", "GFramework.Game.SourceGenerators\GFramework.Game.SourceGenerators.csproj", "{9D3AADF0-55E6-4F80-B9C5-875F63E170D8}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GFramework.Cqrs.Benchmarks", "GFramework.Cqrs.Benchmarks\GFramework.Cqrs.Benchmarks.csproj", "{5609D017-E481-431B-874A-7D06BFF698F9}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
@ -360,6 +362,18 @@ Global
|
||||
{9D3AADF0-55E6-4F80-B9C5-875F63E170D8}.Release|x64.Build.0 = Release|Any CPU
|
||||
{9D3AADF0-55E6-4F80-B9C5-875F63E170D8}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{9D3AADF0-55E6-4F80-B9C5-875F63E170D8}.Release|x86.Build.0 = Release|Any CPU
|
||||
{5609D017-E481-431B-874A-7D06BFF698F9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{5609D017-E481-431B-874A-7D06BFF698F9}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{5609D017-E481-431B-874A-7D06BFF698F9}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{5609D017-E481-431B-874A-7D06BFF698F9}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{5609D017-E481-431B-874A-7D06BFF698F9}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{5609D017-E481-431B-874A-7D06BFF698F9}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{5609D017-E481-431B-874A-7D06BFF698F9}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{5609D017-E481-431B-874A-7D06BFF698F9}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{5609D017-E481-431B-874A-7D06BFF698F9}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{5609D017-E481-431B-874A-7D06BFF698F9}.Release|x64.Build.0 = Release|Any CPU
|
||||
{5609D017-E481-431B-874A-7D06BFF698F9}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{5609D017-E481-431B-874A-7D06BFF698F9}.Release|x86.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
|
||||
@ -38,14 +38,10 @@ help the current worktree land on the right recovery documents without scanning
|
||||
- Purpose: continue the data repository persistence hardening plus the settings / serialization follow-up backlog.
|
||||
- Tracking: `ai-plan/public/data-repository-persistence/todos/data-repository-persistence-tracking.md`
|
||||
- Trace: `ai-plan/public/data-repository-persistence/traces/data-repository-persistence-trace.md`
|
||||
- `semantic-release-versioning`
|
||||
- Purpose: migrate release version calculation from fixed patch bumps to semantic-release while keeping the existing tag-driven NuGet publish flow.
|
||||
- Tracking: `ai-plan/public/semantic-release-versioning/todos/semantic-release-versioning-tracking.md`
|
||||
- Trace: `ai-plan/public/semantic-release-versioning/traces/semantic-release-versioning-trace.md`
|
||||
- `runtime-generator-boundary`
|
||||
- Purpose: keep runtime and abstractions packages isolated from source-generator dependencies, packaging leaks, and attribute usage.
|
||||
- Tracking: `ai-plan/public/runtime-generator-boundary/todos/runtime-generator-boundary-tracking.md`
|
||||
- Trace: `ai-plan/public/runtime-generator-boundary/traces/runtime-generator-boundary-trace.md`
|
||||
- `microsoft-di-container-disposal`
|
||||
- Purpose: track `PR #330` disposal-contract fixes for `MicrosoftDiContainer`, related benchmark cleanup hardening, and review follow-up.
|
||||
- Tracking: `ai-plan/public/microsoft-di-container-disposal/todos/microsoft-di-container-disposal-tracking.md`
|
||||
- Trace: `ai-plan/public/microsoft-di-container-disposal/traces/microsoft-di-container-disposal-trace.md`
|
||||
|
||||
## Worktree To Active Topic Map
|
||||
|
||||
@ -63,18 +59,8 @@ help the current worktree land on the right recovery documents without scanning
|
||||
- Branch: `feat/data-repository-persistence`
|
||||
- Worktree hint: `GFramework-data-repository-persistence`
|
||||
- Priority 1: `data-repository-persistence`
|
||||
- Branch: `feat/semantic-release-versioning`
|
||||
- Worktree hint: `GFramework`
|
||||
- Priority 1: `semantic-release-versioning`
|
||||
- Branch: `build/semantic-release-rules`
|
||||
- Worktree hint: `GFramework`
|
||||
- Priority 1: `semantic-release-versioning`
|
||||
- Branch: `fix/release-notes-pr-links`
|
||||
- Worktree hint: `GFramework`
|
||||
- Priority 1: `semantic-release-versioning`
|
||||
- Branch: `fix/runtime-generator-boundary`
|
||||
- Worktree hint: `GFramework`
|
||||
- Priority 1: `runtime-generator-boundary`
|
||||
- Branch: `docs/sdk-update-documentation`
|
||||
- Worktree hint: `GFramework-update-documentation`
|
||||
- Priority 1: `documentation-full-coverage-governance`
|
||||
- Branch: `fix/microsoft-di-container-disposal`
|
||||
- Priority 1: `microsoft-di-container-disposal`
|
||||
|
||||
@ -12,6 +12,7 @@
|
||||
- 当前焦点:
|
||||
- 已完成 object-focused `if` / `then` / `else`,继续评估下一批仍不改变生成类型形状的共享关键字
|
||||
- 已明确将 `oneOf` / `anyOf` 归类为当前不支持的组合关键字,并在 Runtime / Generator / Tooling 三端显式拒绝,避免静默接受导致形状漂移
|
||||
- 已把开放对象关键字边界收紧为只接受 `additionalProperties: false`,并在 Runtime / Generator / Tooling 三端显式拒绝 `patternProperties`、`propertyNames`、`unevaluatedProperties`
|
||||
- 已完成 PR #262 的 CodeRabbit follow-up,补齐 latest review body 中 folded `Nitpick comments` 的 skill 解析并按建议收口 Tooling / Tests
|
||||
- 先以 Runtime / Generator / Tooling 三端一致语义为前提筛选下一项,而不是盲目扩全量 JSON Schema
|
||||
- Tooling / Docs 后续改为非阻塞并行 lane;active 入口只保留主线恢复点,把批处理细节下沉到 backlog 文件
|
||||
@ -20,6 +21,8 @@
|
||||
|
||||
- 组合关键字扩展风险:下一批候选关键字可能像标准 `oneOf` / `anyOf` 一样更容易引入生成类型形状漂移
|
||||
- 缓解措施:`oneOf` / `anyOf` 已改为三端显式拒绝;后续仅继续评估不会引入联合形状、属性合并或分支生成漂移的关键字子集
|
||||
- 开放对象形状风险:如果某一端静默接受 `patternProperties`、`propertyNames`、`unevaluatedProperties` 等关键字,会重新打开对象形状并造成契约漂移
|
||||
- 缓解措施:当前三端已统一把开放对象边界收紧为只接受 `additionalProperties: false`,其余开放对象关键字直接报错
|
||||
- 工具链验证风险:VS Code 与 CI / 发布管道验证覆盖不足
|
||||
- 缓解措施:继续为新增共享关键字补齐三端测试覆盖,优先保证 C# Runtime 与 Generator 回归通过,并记录 JS 测试与构建验证
|
||||
- PR review 信号漂移风险:CodeRabbit 可能把建议折叠在 latest review body,而不是 issue comments
|
||||
@ -40,6 +43,9 @@
|
||||
- `minProperties`、`maxProperties`、`dependentRequired`、`dependentSchemas`、`allOf`、object-focused `if` / `then` / `else`
|
||||
- 已明确拒绝会改变生成类型形状的组合关键字:
|
||||
- `oneOf`、`anyOf` 当前会在 Runtime / Generator / Tooling 三端直接报错,而不是静默忽略
|
||||
- 已明确拒绝会重新打开对象形状的开放对象关键字:
|
||||
- 当前只接受 `additionalProperties: false`
|
||||
- `patternProperties`、`propertyNames`、`unevaluatedProperties` 当前会在 Runtime / Generator / Tooling 三端直接报错,而不是静默忽略
|
||||
- `if` / `then` / `else` 已按“不改变生成类型形状”的边界落地:
|
||||
- 只允许 object 节点上的 object-typed inline schema
|
||||
- `if` 必填,且必须至少伴随 `then` 或 `else` 之一
|
||||
@ -86,11 +92,13 @@
|
||||
- `2026-04-17` 之前的详细实现记录与定向验证命令已归档到历史 tracking / trace
|
||||
- active 跟踪文件只保留当前恢复点、当前状态和下一步,不再重复堆积已完成阶段的完整历史
|
||||
- 最近验证摘要:`2026-04-30` 已完成 Tooling / Docs reader-facing 收口与工具 parser 边界收紧,详细命令、批次背景与验证结果保留在 trace 的 `2026-04-30` 分阶段记录中
|
||||
- 最近验证摘要:`2026-05-06` 已完成开放对象关键字边界收口;Runtime / Generator / Tooling 现统一拒绝 `patternProperties`、`propertyNames`、`unevaluatedProperties`,并保留 `additionalProperties: false` 作为唯一共享闭合对象入口;详细命令与批次背景保留在 trace 的 `2026-05-06` 记录中
|
||||
- 最近验证摘要:`2026-05-06` 已按 PR `#325` latest review follow-up 移除三端开放对象校验中的不可达 `additionalProperties: false` 放行分支,补齐 Tooling 正向回归,并同步拆分 reader-facing docs 对开放对象边界的表述;细节与验证命令保留在 trace 的 `2026-05-06` 追加记录中
|
||||
- PR `#306` follow-up 摘要:已按 latest open review threads 补齐 Generator `anyOf` 对称回归、Tooling schema type 白名单、object-array 直系收集边界,以及 reader-facing docs 的显式 `additionalProperties: false` / adoption guidance 说明;细节和验证命令保留在 trace 的 `2026-04-30` 新增阶段记录中
|
||||
- PR review 跟进指针:当前分支的 latest review follow-up 与后续本地核验结论以 `ai-first-config-system-trace.md` 为准,active tracking 不再重复展开逐条命令历史
|
||||
|
||||
## 下一步
|
||||
|
||||
1. 主线继续回到 `YamlConfigSchemaValidator.cs`、`SchemaConfigGenerator.cs` 与 `configValidation.js` 的共享关键字盘点,默认跳过 `oneOf` / `anyOf`
|
||||
1. 主线继续回到 `YamlConfigSchemaValidator.cs`、`SchemaConfigGenerator.cs` 与 `configValidation.js` 的共享关键字盘点,默认跳过 `oneOf` / `anyOf` 以及开放对象关键字扩展
|
||||
2. Tooling / Docs 若要并发推进,优先补 reader-facing 示例或采用路径,不再重复扩写能力边界说明
|
||||
3. 保持 active tracking / trace 精简,只记录当前恢复点、最近验证和下一步恢复指针
|
||||
|
||||
@ -231,3 +231,96 @@
|
||||
|
||||
1. 推送本轮修复后,重新抓取 PR `#306` review 状态,确认哪些 open threads 会被 GitHub 自动折叠或仍需人工回复
|
||||
2. 若还有残留 open threads,优先区分“远端未刷新 / 已过时评论 / 仍成立问题”,不要再把 review body 摘要和 latest open threads 混在一起处理
|
||||
|
||||
## 2026-05-06
|
||||
|
||||
### 阶段:开放对象关键字边界收口(AI-FIRST-CONFIG-RP-003)
|
||||
|
||||
- 已在 Runtime、Source Generator 与 VS Code Tooling 三端统一收紧开放对象关键字边界
|
||||
- 本轮不是扩 JSON Schema 能力,而是避免某一端静默接受会重新打开对象形状的 schema:
|
||||
- 当前继续接受 `additionalProperties: false` 作为显式闭合对象提醒
|
||||
- `patternProperties`、`propertyNames`、`unevaluatedProperties` 当前改为三端直接失败
|
||||
- reader-facing docs 也已同步更新,避免采用文档继续把这类关键字描述成“也许工具没做但运行时可能支持”的灰区
|
||||
|
||||
### 关键决定
|
||||
|
||||
- `additionalProperties: false` 仍是唯一共享支持的开放对象相关关键字形状
|
||||
- 任何会重新引入动态字段集的开放对象关键字,都视为当前主线之外的设计,而不是后续工具增强项
|
||||
- 本轮继续保持主线为 `C# Runtime + Source Generator + Consumer DX`,没有把工作重心切回复杂表单或宿主验证
|
||||
|
||||
### Stop Condition
|
||||
|
||||
- Batch baseline:`origin/main` (`a8c6c11e`, `2026-05-05 13:14:24 +0800`)
|
||||
- Primary metric:branch diff vs `origin/main` changed files,阈值 `50`
|
||||
- 本轮执行时的 branch diff 指标仍为 `0`,说明当前批次尚未把 `HEAD` 推进到接近阈值;reviewability headroom 充足
|
||||
|
||||
### 验证
|
||||
|
||||
- 2026-05-06:`bun run test`(`tools/gframework-config-tool`)
|
||||
- 结果:通过(133 tests)
|
||||
- 备注:新增 JS 回归覆盖 `patternProperties`、`propertyNames` 与 `unevaluatedProperties` 的显式拒绝
|
||||
- 2026-05-06:`dotnet test GFramework.Game.Tests/GFramework.Game.Tests.csproj -c Release --filter "FullyQualifiedName~YamlConfigLoaderAllOfTests"`
|
||||
- 结果:通过(18 tests)
|
||||
- 备注:运行时新增开放对象关键字拒绝回归,继续沿用 `SchemaUnsupported` + `reward` 诊断路径
|
||||
- 2026-05-06:`dotnet test GFramework.SourceGenerators.Tests/GFramework.SourceGenerators.Tests.csproj -c Release --filter "FullyQualifiedName~SchemaConfigGeneratorTests"`
|
||||
- 结果:通过(57 tests)
|
||||
- 备注:生成器新增 `GF_ConfigSchema_016` 对称回归,覆盖 3 类开放对象关键字
|
||||
- 2026-05-06:`dotnet build GFramework.Game/GFramework.Game.csproj -c Release`
|
||||
- 结果:通过(0 warnings, 0 errors)
|
||||
- 2026-05-06:`dotnet build GFramework.Game.SourceGenerators/GFramework.Game.SourceGenerators.csproj -c Release`
|
||||
- 结果:通过(0 warnings, 0 errors)
|
||||
- 2026-05-06:`python3 scripts/license-header.py --check --paths ...`
|
||||
- 结果:通过
|
||||
- 备注:仓库脚本默认 `git ls-files` 在当前 WSL worktree 绑定下无法直接解析仓库上下文,因此本轮改为对受影响文件执行 targeted check
|
||||
- 2026-05-06:`git diff --check`
|
||||
- 结果:通过
|
||||
|
||||
### 下一步
|
||||
|
||||
1. 继续盘点下一批不会改变生成类型形状、也不会重新打开对象形状的共享关键字
|
||||
2. Tooling / Docs 如继续并发推进,优先补真实采用示例,不再重复扩写开放对象边界清单
|
||||
3. 若后续 batch 再触碰 schema contract,继续保持 Runtime / Generator / Tooling 三端同步失败语义与 reader-facing docs 一致
|
||||
|
||||
### 阶段:PR #325 latest review follow-up 收口(AI-FIRST-CONFIG-RP-003)
|
||||
|
||||
- 已使用 `gframework-pr-review` 抓取并复核 PR `#325` 的 latest review body、未解决 latest-head 线程、MegaLinter 摘要与测试报告
|
||||
- 本轮按“仅修复本地仍成立项”收口 5 条 review 信号:
|
||||
- Runtime / Generator / Tooling 三端均移除开放对象关键字校验中的不可达 `additionalProperties: false` 放行分支
|
||||
- Tooling 测试补齐 `additionalProperties: false` 的正向回归,避免共享允许边界后续回退
|
||||
- `docs/zh-CN/game/index.md` 将开放对象边界说明拆成并列语句,避免把 `patternProperties` / `propertyNames` / `unevaluatedProperties` 误读成 `additionalProperties` 的变体
|
||||
- 本轮没有跟进 stale 信号:
|
||||
- PR 当前 failed checks 为 `0`
|
||||
- latest test report 为 `2280 passed / 0 failed`
|
||||
- MegaLinter 仅保留 `dotnet-format` 摘要噪音,未提供需要额外修复的新代码格式差异
|
||||
|
||||
### 验证
|
||||
|
||||
- 2026-05-06:`python3 .agents/skills/gframework-pr-review/scripts/fetch_current_pr_review.py --json-output /tmp/gframework-current-pr-review.json`
|
||||
- 结果:通过
|
||||
- 备注:确认 PR `#325` 仍有 3 条 CodeRabbit nitpick 与 2 条 Greptile open threads,需要本地核验
|
||||
- 2026-05-06:`node --test ./test/*.test.js`(`tools/gframework-config-tool`)
|
||||
- 结果:通过(134 tests)
|
||||
- 备注:新增 `additionalProperties: false` 正向回归后,工具端继续显式接受唯一共享闭合对象入口
|
||||
- 2026-05-06:`dotnet test GFramework.Game.Tests/GFramework.Game.Tests.csproj -c Release --filter "FullyQualifiedName~YamlConfigLoaderAllOfTests"`
|
||||
- 结果:通过(18 tests)
|
||||
- 备注:运行时开放对象关键字回归保持通过,未引入额外诊断路径漂移
|
||||
- 2026-05-06:`dotnet test GFramework.SourceGenerators.Tests/GFramework.SourceGenerators.Tests.csproj -c Release --filter "FullyQualifiedName~SchemaConfigGeneratorTests"`
|
||||
- 结果:通过(57 tests)
|
||||
- 备注:生成器开放对象关键字诊断回归保持通过,移除不可达分支未影响既有诊断契约
|
||||
- 2026-05-06:`dotnet build GFramework.Game/GFramework.Game.csproj -c Release`
|
||||
- 结果:通过(0 warnings, 0 errors)
|
||||
- 2026-05-06:`dotnet build GFramework.Game.SourceGenerators/GFramework.Game.SourceGenerators.csproj -c Release`
|
||||
- 结果:通过(0 warnings, 0 errors)
|
||||
- 2026-05-06:`python3 scripts/license-header.py --check`
|
||||
- 结果:环境受限
|
||||
- 备注:仓库脚本默认通过 `git ls-files` 枚举文件,在当前 WSL worktree 绑定下返回 `128`;已改为对受影响文件执行 targeted check 并通过
|
||||
- 2026-05-06:`python3 scripts/license-header.py --check --paths GFramework.Game/Config/YamlConfigSchemaValidator.cs GFramework.Game.SourceGenerators/Config/SchemaConfigGenerator.cs tools/gframework-config-tool/src/configValidation.js tools/gframework-config-tool/test/configValidation.test.js`
|
||||
- 结果:通过
|
||||
- 2026-05-06:`git diff --check`
|
||||
- 结果:通过
|
||||
|
||||
### 下一步
|
||||
|
||||
1. 执行本轮受影响 Tooling / Runtime / Generator 定向验证,并确认没有新增 warning 或格式漂移
|
||||
2. 若验证通过,重新抓取 PR `#325` review 状态,区分哪些 open threads 会随推送自动折叠
|
||||
3. 继续把 PR review follow-up 约束在“latest unresolved thread + 本地仍成立问题”,不回头追旧 summary 噪音
|
||||
|
||||
@ -0,0 +1,82 @@
|
||||
# GitHub Issue Review Skill 跟踪
|
||||
|
||||
## 目标
|
||||
|
||||
为仓库新增一个与 `$gframework-pr-review` 并列的 `$gframework-issue-review` skill,让 AI 能够从 GitHub issue
|
||||
快速提取正文、讨论和关键事件,形成结构化分诊结果,并把后续代码处理明确衔接到 `$gframework-boot`。
|
||||
|
||||
- 保持与现有 PR review skill 相同的目录与 CLI 体验
|
||||
- 支持“当前恰好一个 open issue 时自动选中,否则要求显式传号”的解析策略
|
||||
- 输出适合 AI 后续验证的结构化 JSON 与高信号文本摘要
|
||||
- 给出最小回归测试,覆盖自动选中与解析边界
|
||||
- 用真实仓库 issue 做一次抓取验证,确保默认路径可用
|
||||
|
||||
## 当前恢复点
|
||||
|
||||
- 恢复点编号:`ISSUE-SKILL-RP-002`
|
||||
- 当前阶段:`Phase 3`
|
||||
- 当前焦点:
|
||||
- 收敛 PR #328 上仍然有效的 AI review 评论,避免新 skill 在仓库中留下已知漂移
|
||||
- 保持 `$gframework-issue-review` 的 GitHub API 抓取在代理、认证与 JSON CLI 契约上更稳健
|
||||
- 确保非 bug issue 的 triage 结果不会被错误导向 `clarify-issue-before-code`
|
||||
|
||||
### 已知风险
|
||||
|
||||
- GitHub timeline API 可能因响应缺失或字段差异导致部分事件无法结构化
|
||||
- 缓解措施:把 timeline 解析作为尽力而为能力,缺失时记录到 `parse_warnings`
|
||||
- 当前仓库 open issue 数量若在验证时变化为 `0` 或 `>1`,默认自动解析路径将无法通过
|
||||
- 缓解措施:脚本明确报错并要求 `--issue <number>`,验证时同时保留显式 issue 号路径
|
||||
- issue 文本中的模块归因和处理建议只能是启发式结果,不能替代本地代码验证
|
||||
- 缓解措施:skill 文档明确要求后续仍通过 `$gframework-boot` 与本地源码核实
|
||||
- GitHub API 仍可能在无 token 环境下命中匿名 rate limit
|
||||
- 缓解措施:脚本现已支持从 `GFRAMEWORK_GITHUB_TOKEN`、`GITHUB_TOKEN`、`GH_TOKEN` 读取认证;无 token 时保持匿名降级
|
||||
|
||||
## 已完成
|
||||
|
||||
- 已建立活跃 topic:
|
||||
- `ai-plan/public/github-issue-review-skill/todos/`
|
||||
- `ai-plan/public/github-issue-review-skill/traces/`
|
||||
- 已将分支 `feat/github-issue-review-skill` 映射到该 topic,供后续 `boot` 优先恢复
|
||||
- 已新增 `.agents/skills/gframework-issue-review/`:
|
||||
- `SKILL.md`
|
||||
- `agents/openai.yaml`
|
||||
- `scripts/fetch_current_issue_review.py`
|
||||
- `scripts/test_fetch_current_issue_review.py`
|
||||
- 已实现与 `gframework-pr-review` 同构的 GitHub API 抓取骨架:
|
||||
- 支持 issue 元数据、评论、timeline、引用与 triage hints 输出
|
||||
- 支持 `--issue`、`--format`、`--json-output`、`--section`、`--max-description-length`
|
||||
- 支持“仅当当前仓库恰好一个 open issue 时自动解析,否则要求显式传号”
|
||||
- 已修正新脚本在当前 WSL 会话下误回退到 `git.exe` 的兼容问题:
|
||||
- 在主仓库根目录且存在 Linux `git` 时,也优先绑定 `--git-dir` / `--work-tree`
|
||||
- 已根据 PR #328 review 收敛仍然有效的问题:
|
||||
- 为 `fetch_current_issue_review.py` 与回归测试补齐 shebang 后 license header
|
||||
- 去掉开发机特定的 Windows Git 绝对路径回退,改为环境变量覆盖 + `git.exe` / `git`
|
||||
- GitHub 请求先走环境代理,并在代理请求失败且检测到代理环境变量时再无代理重试
|
||||
- 支持通过标准 token 环境变量附带 `Authorization` 头,避免高频运行时过早命中匿名限流
|
||||
- 将 `needs_clarification` 改为按 issue 主类型分支,避免 feature / docs issue 被 bug 规则误判
|
||||
- 修正 `--format json --json-output` 时 stdout 仍输出 JSON,文件写入只作为附加副作用
|
||||
- 补充 docs / feature 场景回归测试,并将 skill 示例 issue 号改为占位符
|
||||
|
||||
## 验证
|
||||
|
||||
- `python3 scripts/license-header.py --check`
|
||||
- 结果:通过
|
||||
- 备注:本轮修改涉及的受支持文件均包含 Apache-2.0 license header
|
||||
- `python3 .agents/skills/gframework-issue-review/scripts/test_fetch_current_issue_review.py`
|
||||
- 结果:通过
|
||||
- 备注:`5` 个脚本级测试全部通过,新增 docs / feature 分诊回归覆盖
|
||||
- `python3 .agents/skills/gframework-issue-review/scripts/fetch_current_issue_review.py --section summary --section warnings`
|
||||
- 结果:通过
|
||||
- 备注:真实 GitHub API 抓取成功,自动解析到当前唯一 open issue `#327`
|
||||
- `python3 .agents/skills/gframework-issue-review/scripts/fetch_current_issue_review.py --format json --json-output /tmp/gframework-open-issue-review.json`
|
||||
- 结果:通过
|
||||
- 备注:stdout 输出 JSON,文件也成功写出;显式抓取 `#327` 时 `next_action=clarify-issue-before-code`
|
||||
- `dotnet build GFramework.sln -c Release`
|
||||
- 结果:通过
|
||||
- 备注:`0 Warning(s)`,`0 Error(s)`
|
||||
|
||||
## 下一步
|
||||
|
||||
1. 将本轮 PR review 修复提交到当前分支,并回到 PR 线程确认相关评论是否可关闭
|
||||
2. 需要继续处理 issue `#327` 时,重新用 `$gframework-issue-review` 抓取目标 issue,并把结果带入 `$gframework-boot`
|
||||
3. 若后续需要更细的 issue 事件语义,再补强 timeline 解析与脚本级回归测试
|
||||
@ -0,0 +1,84 @@
|
||||
# GitHub Issue Review Skill Trace
|
||||
|
||||
## 2026-05-06
|
||||
|
||||
### 阶段:能力落地准备(ISSUE-SKILL-RP-001)
|
||||
|
||||
- 读取 `AGENTS.md`、`.ai/environment/tools.ai.yaml`、`ai-plan/public/README.md` 与现有
|
||||
`.agents/skills/gframework-pr-review/` 实现,确认新 skill 最稳妥的方案是复用现有 PR review 的
|
||||
GitHub API、WSL worktree Git 解析、文本 section 输出与脚本级测试骨架
|
||||
- 确认当前任务属于 `new` + `complex`:
|
||||
- `new`:当前没有与 issue review skill 对应的公开恢复主题
|
||||
- `complex`:同时涉及 skill 设计、GitHub API 脚本、CLI 契约、测试和 `ai-plan` 恢复入口
|
||||
- 根据实现前确认的产品决策固定默认行为:
|
||||
- 未显式传 issue 号时,只在“仓库当前恰好一个 open issue”时自动选中
|
||||
- skill 默认只做“抓取 + 分诊 + boot 衔接”,不在脚本层直接改代码
|
||||
- 已创建新 topic 目录并将当前分支 `feat/github-issue-review-skill` 映射到该 topic
|
||||
|
||||
### 当前执行目标
|
||||
|
||||
1. 新增 `gframework-issue-review` skill 文档与默认 prompt
|
||||
2. 新增 `fetch_current_issue_review.py` 及其最小回归测试
|
||||
3. 用真实 open issue 抓取验证默认流程,并记录最小验证命令
|
||||
|
||||
### 下一步
|
||||
|
||||
1. 直接用 `$gframework-issue-review` + `$gframework-boot` 开始 issue `#327` 的后续处理
|
||||
2. 若后续仓库同时出现多个 open issue,统一改用显式 `--issue <number>` 入口
|
||||
|
||||
### 阶段:实现与验证完成(ISSUE-SKILL-RP-001)
|
||||
|
||||
- 已落盘新 skill 文件:
|
||||
- `.agents/skills/gframework-issue-review/SKILL.md`
|
||||
- `.agents/skills/gframework-issue-review/agents/openai.yaml`
|
||||
- `.agents/skills/gframework-issue-review/scripts/fetch_current_issue_review.py`
|
||||
- `.agents/skills/gframework-issue-review/scripts/test_fetch_current_issue_review.py`
|
||||
- 真实抓取验证时首次发现:当前 WSL 会话会解析到 `git.exe`,但无法执行
|
||||
- 已在新脚本中修正为:只要仓库根目录存在 Linux `git`,就优先绑定显式 `--git-dir` / `--work-tree`
|
||||
- 完成验证:
|
||||
- `python3 .agents/skills/gframework-issue-review/scripts/test_fetch_current_issue_review.py`
|
||||
- `python3 .agents/skills/gframework-issue-review/scripts/fetch_current_issue_review.py --section summary --section warnings`
|
||||
- `python3 .agents/skills/gframework-issue-review/scripts/fetch_current_issue_review.py --format json --json-output /tmp/gframework-open-issue-review.json`
|
||||
- `dotnet build GFramework.sln -c Release`
|
||||
- 真实 issue 验证结论:
|
||||
- 当前 open issue 自动解析为 `#327`
|
||||
- `resolution_mode=auto-single-open-issue`
|
||||
- `comment_count=0`
|
||||
- `next_action=clarify-issue-before-code`
|
||||
- `affected_active_topics=cqrs-rewrite`
|
||||
|
||||
### 阶段:PR review 跟进修复(ISSUE-SKILL-RP-002)
|
||||
|
||||
- 使用 `$gframework-pr-review` 抓取当前分支 PR #328 后,确认以下评论在本地代码中仍然有效:
|
||||
- `fetch_current_issue_review.py` 和回归测试缺少 shebang 后 license header
|
||||
- issue-review 脚本仍保留开发机特定的 Windows Git 绝对路径回退
|
||||
- `open_url()` 无条件禁用代理,且未支持 GitHub token 认证
|
||||
- `build_information_flags()` 仍把 bug 场景的澄清门槛套用到 feature / docs issue
|
||||
- `--format json --json-output` 组合时 stdout 只输出路径而不是 JSON
|
||||
- skill 文档命令和示例中把 issue 号 `312` 写死
|
||||
- 已在活跃 topic 下同步恢复点:
|
||||
- 跟踪文件更新为 `ISSUE-SKILL-RP-002`
|
||||
- 记录本轮修复范围、验证待办与后续恢复入口
|
||||
- 已落盘修复:
|
||||
- 为 issue-review 脚本和测试补齐 license header
|
||||
- 将 GitHub 请求改为“先按环境代理请求,代理失败再无代理重试”
|
||||
- 支持 `GFRAMEWORK_GITHUB_TOKEN` / `GITHUB_TOKEN` / `GH_TOKEN`
|
||||
- 将 triage 澄清逻辑改为按主 issue 类型分支
|
||||
- 为 docs / feature issue 增加 next-action 回归测试
|
||||
- 将 skill 示例 issue 号改为占位符
|
||||
- 让 `--format json --json-output` 同时保留 stdout JSON 与落盘副作用
|
||||
- 已完成验证:
|
||||
- `python3 scripts/license-header.py --check`
|
||||
- `python3 .agents/skills/gframework-issue-review/scripts/test_fetch_current_issue_review.py`
|
||||
- `python3 .agents/skills/gframework-issue-review/scripts/fetch_current_issue_review.py --issue 327 --format json --json-output /tmp/gframework-open-issue-review.json`
|
||||
- `dotnet build GFramework.sln -c Release`
|
||||
- 本轮验证结论:
|
||||
- license header 检查通过
|
||||
- 脚本级测试 `5/5` 通过
|
||||
- `--format json --json-output` 现在会同时输出 stdout JSON 并写出 JSON 文件
|
||||
- 仓库 Release build 通过,`0 Warning(s)` / `0 Error(s)`
|
||||
|
||||
### 下一步
|
||||
|
||||
1. 按仓库规范提交本轮 PR review 修复
|
||||
2. 需要继续跟进 issue `#327` 时,再切回 `$gframework-issue-review` + `$gframework-boot` 路径
|
||||
@ -0,0 +1,48 @@
|
||||
# MicrosoftDiContainer Disposal Tracking
|
||||
|
||||
## Goal
|
||||
|
||||
Fix issue `#327` by making `MicrosoftDiContainer` explicitly disposable, ensuring frozen service providers and lock
|
||||
state are released deterministically, and updating CQRS benchmarks so every owned container is disposed in cleanup or
|
||||
cold-start paths.
|
||||
|
||||
## Current Recovery Point
|
||||
|
||||
- Recovery point: `MDC-DISPOSE-RP-001`
|
||||
- Phase: completed and ready to archive
|
||||
- Focus:
|
||||
- keep the final validated implementation and archive handoff concise
|
||||
|
||||
## Active Risks
|
||||
|
||||
- No active implementation blockers remain after validation.
|
||||
|
||||
## Completed In This Stage
|
||||
|
||||
- Extended `IIocContainer` to inherit `IDisposable` so callers holding the abstraction can release container-owned
|
||||
resources explicitly.
|
||||
- Implemented `MicrosoftDiContainer.Dispose()` with idempotent root-provider release, lock cleanup, state clearing, and
|
||||
`ObjectDisposedException` guards for post-disposal access.
|
||||
- Updated `Clear()` to dispose the currently built root provider before resetting container state.
|
||||
- Added Core regression tests that verify resolved DI-owned singletons are disposed and that disposed containers reject
|
||||
further registration, lookup, and scope creation.
|
||||
- Fixed CQRS benchmark cleanup so every benchmark-owned `MicrosoftDiContainer` is disposed, including the temporary
|
||||
cold-start container path in `RequestStartupBenchmarks`.
|
||||
|
||||
## Validation Target
|
||||
|
||||
- `python3 scripts/license-header.py --check`
|
||||
- `dotnet test GFramework.Core.Tests -c Release --filter "FullyQualifiedName~MicrosoftDiContainer|FullyQualifiedName~IocContainerLifetimeTests"`
|
||||
- `dotnet build GFramework.Cqrs.Benchmarks/GFramework.Cqrs.Benchmarks.csproj -c Release`
|
||||
- `dotnet build GFramework.sln -c Release`
|
||||
|
||||
## Latest Validation Result
|
||||
|
||||
- `python3 scripts/license-header.py --check` passed on 2026-05-06.
|
||||
- `dotnet test GFramework.Core.Tests/GFramework.Core.Tests.csproj -c Release --filter "FullyQualifiedName~MicrosoftDiContainer|FullyQualifiedName~IocContainerLifetimeTests"` passed on 2026-05-06 with `55` tests passed.
|
||||
- `dotnet build GFramework.Cqrs.Benchmarks/GFramework.Cqrs.Benchmarks.csproj -c Release` passed on 2026-05-06 with `0 warnings` and `0 errors`.
|
||||
- `dotnet build GFramework.sln -c Release` passed on 2026-05-06 with `0 warnings` and `0 errors`.
|
||||
|
||||
## Next Recommended Resume Step
|
||||
|
||||
Archive this topic under `ai-plan/public/archive/` and push the fix branch for review.
|
||||
@ -0,0 +1,31 @@
|
||||
# MicrosoftDiContainer Disposal Trace
|
||||
|
||||
## 2026-05-06
|
||||
|
||||
### MDC-DISPOSE-RP-001 Issue #327 disposal repair
|
||||
|
||||
- Trigger:
|
||||
- issue `#327` reports that `MicrosoftDiContainer` holds a `ReaderWriterLockSlim` and a frozen `IServiceProvider`
|
||||
but never releases either resource explicitly
|
||||
- CQRS benchmark types keep `MicrosoftDiContainer` fields alive across runs and currently only dispose the MediatR
|
||||
`ServiceProvider` side
|
||||
- `RequestStartupBenchmarks` also creates temporary GFramework runtimes whose backing containers are never surfaced
|
||||
for cleanup
|
||||
- Decisions:
|
||||
- treat the fix as a container lifetime contract update, not only a benchmark workaround
|
||||
- add the disposal contract at the `IIocContainer` abstraction so callers holding interface references can release the
|
||||
container explicitly
|
||||
- keep runtime ownership unchanged; benchmarks that create containers remain responsible for disposing them
|
||||
- Implementation notes:
|
||||
- `MicrosoftDiContainer` now releases its frozen root `IServiceProvider`, clears registration state, disposes the
|
||||
internal `ReaderWriterLockSlim`, and rejects all later operations with `ObjectDisposedException`
|
||||
- `RequestStartupBenchmarks` was rewritten so the steady-state runtime keeps an explicit container field and the
|
||||
cold-start benchmark disposes its temporary container in the same measured invocation
|
||||
- other benchmark classes that own `MicrosoftDiContainer` fields now dispose them during `GlobalCleanup`
|
||||
- Validation milestone:
|
||||
- `python3 scripts/license-header.py --check` passed
|
||||
- `dotnet test GFramework.Core.Tests/GFramework.Core.Tests.csproj -c Release --filter "FullyQualifiedName~MicrosoftDiContainer|FullyQualifiedName~IocContainerLifetimeTests"` passed (`55/55`)
|
||||
- `dotnet build GFramework.Cqrs.Benchmarks/GFramework.Cqrs.Benchmarks.csproj -c Release` passed with `0 warnings / 0 errors`
|
||||
- `dotnet build GFramework.sln -c Release` passed with `0 warnings / 0 errors`
|
||||
- Immediate next step:
|
||||
- archive the topic and push the branch
|
||||
@ -7,9 +7,9 @@ CQRS 迁移与收敛。
|
||||
|
||||
## 当前恢复点
|
||||
|
||||
- 恢复点编号:`CQRS-REWRITE-RP-082`
|
||||
- 恢复点编号:`CQRS-REWRITE-RP-091`
|
||||
- 当前阶段:`Phase 8`
|
||||
- 当前 PR 锚点:`PR #323`
|
||||
- 当前 PR 锚点:`PR #331`
|
||||
- 当前结论:
|
||||
- `GFramework.Cqrs` 已完成对外部 `Mediator` 的生产级替代,当前主线已从“是否可替代”转向“仓库内部收口与能力深化顺序”
|
||||
- `dispatch/invoker` 生成前移已扩展到 request / stream 路径,`RP-077` 已补齐 request invoker provider gate 与 stream gate 对称的 descriptor / descriptor entry runtime 合同回归
|
||||
@ -18,72 +18,59 @@ CQRS 迁移与收敛。
|
||||
- `RP-080` 已将基础 generation gate 回归扩展到 notification handler interface、stream handler interface 与 registry attribute 缺失分支
|
||||
- `RP-081` 已继续补齐基础 generation gate 的 logging 与 DI runtime contract 缺失分支
|
||||
- 当前 `RP-082` 已补齐基础 generation gate 的 request handler runtime contract 缺失分支
|
||||
- `ai-plan` active 入口现以 `PR #323` 和 `RP-082` 为唯一权威恢复锚点;`PR #307`、其他更早 PR 与阶段细节均以下方归档或说明为准
|
||||
- `RP-083` 已补齐 mixed direct / reflected-implementation request 与 stream invoker provider 发射顺序回归
|
||||
- `RP-084` 已引入独立 `GFramework.Cqrs.Benchmarks` 项目,作为持续吸收 `Mediator` benchmark 组织方式的第一落点
|
||||
- `RP-085` 已补齐 stream request benchmark,对齐 `Mediator` messaging benchmark 的第二个核心场景
|
||||
- `RP-086` 已补齐 request pipeline `0 / 1 / 4` 数量矩阵,开始把 benchmark 关注点从单纯 messaging steady-state 扩展到行为编排开销
|
||||
- `RP-087` 已补齐 request startup benchmark,把 initialization 与 cold-start 维度正式纳入 `GFramework.Cqrs.Benchmarks`
|
||||
- 当前 `RP-088` 已补齐 request invoker reflection / generated-provider 对照,开始直接量化 dispatcher 预热 generated descriptor 的收益
|
||||
- 当前 `RP-089` 已补齐 stream invoker reflection / generated-provider 对照,使 generated descriptor 预热收益从 request 扩展到 stream 路径
|
||||
- 当前 `RP-090` 已收敛 `PR #326` benchmark review:统一 benchmark 最小宿主构建、冻结 GFramework 容器、限制 MediatR 扫描范围,并恢复 request startup cold-start 对照
|
||||
- 当前 `RP-091` 已把 benchmark 项目发布面隔离与包清单校验前移到 PR:`GFramework.Cqrs.Benchmarks` 明确保持不可打包,`publish.yml` 与 `ci.yml` 复用同一份 packed-modules 校验脚本
|
||||
- `ai-plan` active 入口现以 `RP-091` 为最新恢复锚点;`PR #331`、`PR #326`、`PR #323`、`PR #307` 与其他更早阶段细节均以下方归档或说明为准
|
||||
|
||||
## 当前活跃事实
|
||||
|
||||
- 当前分支对应 `PR #323`,状态为 `OPEN`
|
||||
- latest-head review 仍以 `ai-plan` 恢复文档收敛为主要待闭环项;代码与测试侧的本地有效问题已收敛
|
||||
- 当前分支为 `fix/package-validation-guard`
|
||||
- `GFramework.Cqrs.Benchmarks` 作为 benchmark 基础设施项目,必须持续排除在 NuGet / GitHub Packages 发布集合之外
|
||||
- 发布工作流已有 packed modules 校验,但 PR 工作流此前没有等价的 solution pack 产物名单校验
|
||||
- 本地 `dotnet pack GFramework.sln -c Release --no-restore -o <temp-dir>` 当前只产出 14 个预期包,未复现 benchmark `.nupkg`
|
||||
- latest-head review 现仍有少量 open thread,但本地复核后,仍成立的问题已收敛到 benchmark 对照公平性、workflow 输入安全性与 active 文档压缩
|
||||
- benchmark 场景现统一通过 `BenchmarkHostFactory` 构建最小宿主:GFramework 侧在 runtime 分发前显式 `Freeze()` 容器,MediatR 侧只扫描当前场景需要的 handler / behavior 类型
|
||||
- `RequestStartupBenchmarks` 已恢复 `ColdStart_GFrameworkCqrs` 结果产出,不再命中 `No CQRS request handler registered`
|
||||
- 已新增手动触发的 benchmark workflow;默认只验证 benchmark 项目 Release build,只有显式提供过滤器时才执行 BenchmarkDotNet 运行;过滤器输入现通过环境变量传入 shell,避免 workflow_dispatch 输入直接插值到命令行
|
||||
- 远端 `CTRF` 最新汇总为 `2274/2274` passed
|
||||
- `MegaLinter` 当前只暴露 `dotnet-format` 的 `Restore operation failed` 环境噪音,尚未提供本地仍成立的文件级格式诊断
|
||||
|
||||
## 当前风险
|
||||
|
||||
- 顶层 `GFramework.sln` / `GFramework.csproj` 在 WSL 下仍可能受 Windows NuGet fallback 配置影响,完整 solution 级验证成本高于模块级验证
|
||||
- 若后续新增 benchmark / example / tooling 项目但未同步校验发布面,solution 级 `dotnet pack` 仍可能在 tag 发布前才暴露异常包
|
||||
- `RequestStartupBenchmarks` 为了量化真正的单次 cold-start,引入了 `InvocationCount=1` / `UnrollFactor=1` 的专用 job;该配置会触发 BenchmarkDotNet 的 `MinIterationTime` 提示,后续若要做稳定基线比较,还需要决定是否引入批量外层循环或自定义 cold-start harness
|
||||
- 仓库内部仍保留旧 `Command` / `Query` API、`LegacyICqrsRuntime` alias 与部分历史命名语义,后续若不继续分批收口,容易混淆“对外替代已完成”与“内部收口未完成”
|
||||
- 若继续扩大 generated invoker 覆盖面,需要持续区分“可静态表达的合同”与 `PreciseReflectedRegistrationSpec` 等仍需保守回退的场景
|
||||
|
||||
## 最近权威验证
|
||||
|
||||
- `dotnet pack GFramework.sln -c Release --no-restore -o /tmp/gframework-pack-validation -p:IncludeSymbols=false`
|
||||
- 结果:通过
|
||||
- 备注:当前本地产物仅包含 14 个预期发布包,未生成 `GFramework.Cqrs.Benchmarks.*.nupkg`
|
||||
- `bash scripts/validate-packed-modules.sh /tmp/gframework-pack-validation`
|
||||
- 结果:通过
|
||||
- 备注:共享脚本确认 actual package set 与预期 14 个发布包完全一致
|
||||
- `dotnet build GFramework.Cqrs.Benchmarks/GFramework.Cqrs.Benchmarks.csproj -c Release`
|
||||
- 结果:通过,`0 warning / 0 error`
|
||||
- `python3 scripts/license-header.py --check`
|
||||
- 结果:通过
|
||||
- `dotnet run --project GFramework.Cqrs.Benchmarks/GFramework.Cqrs.Benchmarks.csproj -c Release -- --filter "*RequestStartupBenchmarks*" --job short --warmupCount 1 --iterationCount 1 --launchCount 1`
|
||||
- 结果:通过
|
||||
- 备注:`ColdStart_GFrameworkCqrs` 已恢复出数,最新本地输出约 `220-292 us`,MediatR 对照约 `575-616 us`;当前仅剩 BenchmarkDotNet 对单次 cold-start 场景的 `MinIterationTime` 提示
|
||||
- `dotnet build GFramework.Cqrs.Benchmarks/GFramework.Cqrs.Benchmarks.csproj -c Release`
|
||||
- 结果:通过,`0 warning / 0 error`
|
||||
- 备注:用于验证本轮 request invoker / pipeline / stream invoker 调整与 benchmark workflow 改动后的 Release 编译结果
|
||||
- `python3 .agents/skills/gframework-pr-review/scripts/fetch_current_pr_review.py --format json --json-output <temporary-json-output>`
|
||||
- 结果:通过
|
||||
- 备注:确认当前分支对应 `PR #323`,本轮剩余 open AI feedback 主要集中在 `ai-plan` PR 锚点收敛
|
||||
- `git diff --check`
|
||||
- 结果:通过
|
||||
- `python3 scripts/license-header.py --check`
|
||||
- 结果:通过
|
||||
- 备注:当前 WSL worktree 需要显式绑定 `GIT_DIR` / `GIT_WORK_TREE` 后运行
|
||||
- `dotnet build GFramework.SourceGenerators.Tests/GFramework.SourceGenerators.Tests.csproj -c Release`
|
||||
- 结果:通过,`0 warning / 0 error`
|
||||
- `dotnet test GFramework.SourceGenerators.Tests/GFramework.SourceGenerators.Tests.csproj -c Release --filter "FullyQualifiedName~CqrsHandlerRegistryGeneratorTests.Does_Not_Emit_Stream_Invoker_Provider_Metadata_When_Runtime_Lacks_Stream_Provider_Interface|FullyQualifiedName~CqrsHandlerRegistryGeneratorTests.Does_Not_Emit_Stream_Invoker_Provider_Metadata_When_Runtime_Lacks_Stream_Descriptor_Enumerator|FullyQualifiedName~CqrsHandlerRegistryGeneratorTests.Does_Not_Emit_Stream_Invoker_Provider_Metadata_When_Runtime_Lacks_Stream_Descriptor_Type|FullyQualifiedName~CqrsHandlerRegistryGeneratorTests.Does_Not_Emit_Stream_Invoker_Provider_Metadata_When_Runtime_Lacks_Stream_Descriptor_Entry_Type|FullyQualifiedName~CqrsHandlerRegistryGeneratorTests.Emits_Stream_Invoker_Provider_Metadata_When_Runtime_Contract_Is_Available"`
|
||||
- 结果:通过,`5/5` passed
|
||||
- `dotnet test GFramework.SourceGenerators.Tests/GFramework.SourceGenerators.Tests.csproj -c Release --filter "FullyQualifiedName~CqrsHandlerRegistryGeneratorTests.Does_Not_Emit_Request_Invoker_Provider_Metadata_When_Runtime_Lacks_Request_Descriptor_Type|FullyQualifiedName~CqrsHandlerRegistryGeneratorTests.Does_Not_Emit_Request_Invoker_Provider_Metadata_When_Runtime_Lacks_Request_Descriptor_Entry_Type|FullyQualifiedName~CqrsHandlerRegistryGeneratorTests.Does_Not_Emit_Request_Invoker_Provider_Metadata_When_Runtime_Lacks_Request_Provider_Interface|FullyQualifiedName~CqrsHandlerRegistryGeneratorTests.Does_Not_Emit_Request_Invoker_Provider_Metadata_When_Runtime_Lacks_Request_Descriptor_Enumerator"`
|
||||
- 结果:通过,`4/4` passed
|
||||
- `dotnet build GFramework.Cqrs.SourceGenerators/GFramework.Cqrs.SourceGenerators.csproj -c Release`
|
||||
- 结果:通过,`0 warning / 0 error`
|
||||
- `python3 scripts/license-header.py --check`
|
||||
- 结果:通过
|
||||
- 备注:当前 WSL worktree 需要显式绑定 `GIT_DIR` / `GIT_WORK_TREE` 后运行,避免脚本内部 plain `git ls-files` 误判仓库上下文
|
||||
- `dotnet test GFramework.SourceGenerators.Tests/GFramework.SourceGenerators.Tests.csproj -c Release --filter "FullyQualifiedName~CqrsHandlerRegistryGeneratorTests.Emits_String_Fallback_Metadata_For_Mixed_Fallback_When_Runtime_Disallows_Multiple_Fallback_Attributes"`
|
||||
- 结果:通过,`1/1` passed
|
||||
- `python3 scripts/license-header.py --check`
|
||||
- 结果:通过
|
||||
- 备注:当前 WSL worktree 需要显式绑定 `GIT_DIR` / `GIT_WORK_TREE` 后运行
|
||||
- `git diff --check`
|
||||
- 结果:通过
|
||||
- `dotnet test GFramework.SourceGenerators.Tests/GFramework.SourceGenerators.Tests.csproj -c Release --filter "FullyQualifiedName~CqrsHandlerRegistryGeneratorTests.Does_Not_Generate_Registry_When_Runtime_Lacks_Handler_Registry_Interface"`
|
||||
- 结果:通过,`1/1` passed
|
||||
- `python3 scripts/license-header.py --check`
|
||||
- 结果:通过
|
||||
- 备注:当前 WSL worktree 需要显式绑定 `GIT_DIR` / `GIT_WORK_TREE` 后运行
|
||||
- `git diff --check`
|
||||
- 结果:通过
|
||||
- `dotnet test GFramework.SourceGenerators.Tests/GFramework.SourceGenerators.Tests.csproj -c Release --filter "FullyQualifiedName~CqrsHandlerRegistryGeneratorTests.Does_Not_Generate_Registry_When_Runtime_Lacks_Required_Generation_Contract"`
|
||||
- 结果:通过,`4/4` passed
|
||||
- `python3 scripts/license-header.py --check`
|
||||
- 结果:通过
|
||||
- 备注:当前 WSL worktree 需要显式绑定 `GIT_DIR` / `GIT_WORK_TREE` 后运行
|
||||
- `git diff --check`
|
||||
- 结果:通过
|
||||
- `dotnet test GFramework.SourceGenerators.Tests/GFramework.SourceGenerators.Tests.csproj -c Release --filter "FullyQualifiedName~CqrsHandlerRegistryGeneratorTests.Does_Not_Generate_Registry_When_Runtime_Lacks_Required_Generation_Contract"`
|
||||
- 结果:通过,`6/6` passed
|
||||
- `python3 scripts/license-header.py --check`
|
||||
- 结果:通过
|
||||
- 备注:当前 WSL worktree 需要显式绑定 `GIT_DIR` / `GIT_WORK_TREE` 后运行
|
||||
- `git diff --check`
|
||||
- 结果:通过
|
||||
- `dotnet test GFramework.SourceGenerators.Tests/GFramework.SourceGenerators.Tests.csproj -c Release --filter "FullyQualifiedName~CqrsHandlerRegistryGeneratorTests.Does_Not_Generate_Registry_When_Runtime_Lacks_Required_Generation_Contract"`
|
||||
- 结果:通过,`7/7` passed
|
||||
- 备注:确认当前分支对应 `PR #331`,本轮 latest-head open AI feedback 已收敛到 `dotnet pack --no-build`、共享包校验脚本跨平台兼容性与 active 文档 PR 锚点同步
|
||||
- `python3 scripts/license-header.py --check`
|
||||
- 结果:通过
|
||||
- 备注:当前 WSL worktree 需要显式绑定 `GIT_DIR` / `GIT_WORK_TREE` 后运行
|
||||
@ -92,9 +79,9 @@ CQRS 迁移与收敛。
|
||||
|
||||
## 下一推荐步骤
|
||||
|
||||
1. 继续处理 `PR #323` 的剩余 review 收尾,优先保持 `ai-plan` active 入口与 trace 的单一锚点一致
|
||||
2. 若继续推进代码切片,优先复核基础 generation gate 之外的 runtime contract 或 fallback selection 分支;基础 gate 的可安全构造缺失分支已覆盖
|
||||
3. 在进入下一批 runtime / generator 收敛前,保持最小 Release build 或 targeted test 作为权威验证
|
||||
1. 运行 `dotnet pack` 与新的 `scripts/validate-packed-modules.sh`,确认本轮共享校验脚本与 PR workflow 步骤在本地一致通过
|
||||
2. 运行受影响的 Release build / 头部校验,确认 workflow 与脚本改动未引入新的命名、文件头或 shell 语法问题
|
||||
3. 创建修复 PR 时,将重点放在“发布面保护前移到 PR”而不是“扩充 expected package 列表”
|
||||
|
||||
## 活跃文档
|
||||
|
||||
|
||||
@ -1,5 +1,103 @@
|
||||
# CQRS 重写迁移追踪
|
||||
|
||||
## 2026-05-06
|
||||
|
||||
### 阶段:PR #331 review 收尾补丁(CQRS-REWRITE-RP-091)
|
||||
|
||||
- 使用 `$gframework-pr-review` 拉取当前分支 `fix/package-validation-guard` 对应的 `PR #331` latest-head review 后,主线程只保留本地复核仍成立的问题:
|
||||
- `.github/workflows/ci.yml` 的 `dotnet pack` 步骤缺少 `--no-build`,会在已完成 solution `Build` 后重复编译整仓库
|
||||
- `scripts/validate-packed-modules.sh` 使用 GNU `find -printf`,在 macOS / BSD `find` 下无法运行
|
||||
- `ai-plan/public/cqrs-rewrite/todos/cqrs-rewrite-migration-tracking.md` 的 active PR 锚点仍写成 `待创建`,与当前公开 PR 状态不一致
|
||||
- 本轮决策:
|
||||
- `ci.yml` 的 pack 步骤显式补上 `--no-build`,使其与前置 `Build` 步骤形成单次编译链路
|
||||
- 共享包校验脚本改为使用 `find ... -exec basename {} \;`,避免依赖 GNU-only 选项
|
||||
- active tracking 同步到 `PR #331`,并把这轮 PR review 的剩余问题描述更新为当前已核验的真实范围
|
||||
- 预期结果:
|
||||
- PR workflow 的 pack 阶段不再对同一 solution 重复编译
|
||||
- `validate-packed-modules.sh` 可在 GNU / BSD `find` 环境下保持相同行为
|
||||
- `cqrs-rewrite` active 恢复入口继续与当前公开 PR 保持一致
|
||||
|
||||
### 阶段:benchmark 发布面隔离与包清单校验前移(CQRS-REWRITE-RP-091)
|
||||
|
||||
- 针对 tag 发布中出现的 `GFramework.Cqrs.Benchmarks` 异常包名单,本轮先复核 benchmark 项目与 solution pack 的本地事实:
|
||||
- `GFramework.Cqrs.Benchmarks.csproj` 已包含 `IsPackable=false` 与 `GeneratePackageOnBuild=false`
|
||||
- 本地执行 `dotnet pack GFramework.sln -c Release --no-restore -o /tmp/gframework-sln-pack-probe -p:IncludeSymbols=false` 时,产物仅包含 14 个预期发布包
|
||||
- 因此本轮不把 benchmark 包加入发布白名单,而是把“benchmark 永不发布”与“PR 前置完整包名单校验”同时固化
|
||||
- 本轮决策:
|
||||
- 为 `GFramework.Cqrs.Benchmarks` 补充注释,明确其 benchmark-only 的发布边界
|
||||
- 新增 `scripts/validate-packed-modules.sh`,集中维护预期包集合与实际 `.nupkg` diff 逻辑
|
||||
- `publish.yml` 改为调用共享脚本,避免发布工作流与 PR 工作流各自维护一份包名单
|
||||
- `ci.yml` 新增 solution `dotnet pack` 与 packed modules 校验,把异常发布包从 tag 发布前移到普通 PR 阶段
|
||||
- 预期结果:
|
||||
- benchmark / example / tooling 一类新项目若意外进入发布面,会先在 PR 失败,而不是等到 tag 发布
|
||||
- 发布与 PR 使用同一份包名单规则,减少后续名单漂移
|
||||
- `GFramework.Cqrs.Benchmarks` 继续只服务于 benchmark workflow,不进入 NuGet / GitHub Packages
|
||||
|
||||
### 阶段:benchmark 对照宿主收敛与 startup cold-start 恢复(CQRS-REWRITE-RP-090)
|
||||
|
||||
- 使用 `$gframework-pr-review` 拉取 `PR #326` latest-head review 后,主线程确认仍有效的 benchmark 反馈集中在三类问题:
|
||||
- `RequestBenchmarks` 的 GFramework / MediatR handler 生命周期不对齐
|
||||
- `RequestStartupBenchmarks` 把容器构建、程序集扫描范围和缓存清理阶段混在一起,导致 cold-start 对照不公平
|
||||
- benchmark 工程里的 `MicrosoftDiContainer` 多处以 `ImplementationType` 方式注册 handler,但未在 runtime 分发前 `Freeze()`,首次真实解析路径存在隐藏失败风险
|
||||
- 本轮本地复核的关键根因:
|
||||
- `MicrosoftDiContainer.Get(Type)` 在未冻结时只读取 `ImplementationInstance`,不会实例化 `ImplementationType`
|
||||
- `ColdStart_GFrameworkCqrs` 清空 dispatcher 静态缓存后,首次发送必须走真实 handler 解析,因此会稳定触发 `No CQRS request handler registered`
|
||||
- 多个 benchmark 同时采用“手工 MediatR 注册 + `RegisterServicesFromAssembly(...)` 全程序集扫描”,容易把无关 handler / behavior 一并纳入对照,且存在重复注册漂移
|
||||
- 本轮决策:
|
||||
- 新增 `Messaging/BenchmarkHostFactory.cs`,统一 benchmark 最小宿主构建规则
|
||||
- GFramework benchmark 宿主统一先注册再 `Freeze()`,保证 steady-state 与 cold-start 都走真实可解析容器
|
||||
- MediatR benchmark 宿主统一通过 `TypeEvaluator` 限制到当前场景所需 handler / behavior 类型,保留正常 `AddMediatR` 组装路径,同时移除全程序集扫描噪音
|
||||
- `RequestStartupBenchmarks` 采用专用 `ColdStart` job,设置 `InvocationCount=1` 与 `WithUnrollFactor(1)`,并把 dispatcher cache reset 放到 `IterationSetup`
|
||||
- 已修改的 benchmark 范围:
|
||||
- `RequestBenchmarks`
|
||||
- `RequestPipelineBenchmarks`
|
||||
- `RequestStartupBenchmarks`
|
||||
- `StreamingBenchmarks`
|
||||
- `NotificationBenchmarks`
|
||||
- `RequestInvokerBenchmarks`
|
||||
- `StreamInvokerBenchmarks`
|
||||
- 结果:
|
||||
- `ColdStart_GFrameworkCqrs` 已恢复出有效结果,不再出现 `No CQRS request handler registered`
|
||||
- `RequestBenchmarks`、`RequestStartupBenchmarks` 在本地均可实际运行
|
||||
- `RequestStartupBenchmarks` 目前仍会收到 BenchmarkDotNet 对单次 cold-start 场景的 `MinIterationTime` 提示;这是测量形状带来的工具提示,不再是运行级失败
|
||||
|
||||
### 验证(RP-090)
|
||||
|
||||
- `python3 .agents/skills/gframework-pr-review/scripts/fetch_current_pr_review.py --json-output /tmp/gframework-current-pr-review.json`
|
||||
- 结果:通过
|
||||
- 备注:确认当前分支对应 `PR #326`,仍有效的 open AI feedback 集中在 benchmark 对照语义与 active 文档收敛
|
||||
- `dotnet build GFramework.Cqrs.Benchmarks/GFramework.Cqrs.Benchmarks.csproj -c Release`
|
||||
- 结果:通过,`0 warning / 0 error`
|
||||
- `dotnet run --project GFramework.Cqrs.Benchmarks/GFramework.Cqrs.Benchmarks.csproj -c Release -- --filter "*RequestStartupBenchmarks*" --job short --warmupCount 1 --iterationCount 1 --launchCount 1`
|
||||
- 结果:通过
|
||||
- 备注:`ColdStart_GFrameworkCqrs` 已恢复,最新本地输出约 `220-292 us`,`ColdStart_MediatR` 约 `575-616 us`
|
||||
- `dotnet run --project GFramework.Cqrs.Benchmarks/GFramework.Cqrs.Benchmarks.csproj -c Release -- --filter "*RequestBenchmarks*" --job short --warmupCount 1 --iterationCount 1 --launchCount 1`
|
||||
- 结果:通过
|
||||
- 备注:steady-state request 对照可正常运行,未再触发 MediatR 重复注册或 GFramework 首次解析失败
|
||||
|
||||
### 阶段:PR #326 review 收尾补丁(CQRS-REWRITE-RP-090)
|
||||
|
||||
- 再次使用 `$gframework-pr-review` 复核 `PR #326` latest-head open threads 后,主线程确认本轮仍成立且适合在当前 PR 内收敛的问题集中在四类:
|
||||
- `.github/workflows/benchmark.yml` 的 `benchmark_filter` 直接插值到 shell,存在 workflow_dispatch 输入注入风险
|
||||
- `RequestInvokerBenchmarks` 与 `StreamInvokerBenchmarks` 的 MediatR handler 生命周期仍为 `Singleton`,与 GFramework 反射 / generated 路径的 transient 语义不一致
|
||||
- `RequestPipelineBenchmarks` 未在场景切换前后清理 dispatcher 缓存,且四个空 pipeline behavior 类型仍使用非法的分号类声明
|
||||
- `ai-plan/public/cqrs-rewrite` active 文档仍保留旧失败结论与重复日期标题,和“active 入口只保留最新权威恢复点”的约束不一致
|
||||
- 本轮刻意未扩展处理的 review:
|
||||
- `MicrosoftDiContainer` 的释放契约建议会扩大到核心 Ioc 接口与全仓库生命周期语义,不适合作为 benchmark review 顺手改动
|
||||
- `RequestStartupBenchmarks` 的“手工单点注册 vs 受限程序集扫描”差异目前属于有意保留的最小宿主模型,代码注释已明确该设计边界
|
||||
- 已修改:
|
||||
- `.github/workflows/benchmark.yml`
|
||||
- `GFramework.Cqrs.Benchmarks/Messaging/RequestInvokerBenchmarks.cs`
|
||||
- `GFramework.Cqrs.Benchmarks/Messaging/RequestPipelineBenchmarks.cs`
|
||||
- `GFramework.Cqrs.Benchmarks/Messaging/StreamInvokerBenchmarks.cs`
|
||||
- `ai-plan/public/cqrs-rewrite/todos/cqrs-rewrite-migration-tracking.md`
|
||||
- `ai-plan/public/cqrs-rewrite/traces/cqrs-rewrite-migration-trace.md`
|
||||
- 预期结果:
|
||||
- 手动 benchmark workflow 的过滤器输入不再直接参与 shell 解析
|
||||
- request / stream invoker 三路对照的 handler 生命周期重新回到同一基线
|
||||
- request pipeline benchmark 在 `0 / 1 / 4` 场景切换时不再复用旧 dispatcher cache
|
||||
- active tracking / trace 更符合 boot 恢复入口所要求的“只保留最新权威结论”形状
|
||||
|
||||
## 2026-04-30
|
||||
|
||||
### 阶段:历史 PR #307 active 入口收敛(CQRS-REWRITE-RP-076)
|
||||
@ -212,3 +310,263 @@
|
||||
|
||||
1. 若 review 重新触发后仍有 latest-head open thread,继续以 `PR #323` 为当前唯一 PR 恢复锚点复核
|
||||
2. 后续若继续推进代码切片,优先复核基础 generation gate 之外的 runtime contract 或 fallback selection 分支
|
||||
|
||||
## 2026-05-06(RP-083 ~ RP-089)
|
||||
|
||||
### 阶段:mixed invoker provider 排序回归(CQRS-REWRITE-RP-083)
|
||||
|
||||
- 使用 `$gframework-batch-boot 50` 继续 `feat/cqrs-optimization` 的 CQRS 收口批次
|
||||
- 批次目标:在 branch diff 相对 `origin/main` 接近 `50` 个文件前,继续补齐低风险的 generator runtime contract / emission 回归
|
||||
- 本轮基线选择:
|
||||
- `origin/main a8c6c11e`,committer date `2026-05-05 13:14:24 +0800`
|
||||
- `main a8c6c11e`,committer date `2026-05-05 13:14:24 +0800`
|
||||
- 当前分支 `feat/cqrs-optimization a8c6c11e`,committer date `2026-05-05 13:14:24 +0800`
|
||||
- 启动时 branch diff vs `origin/main` 为 `0` files / `0` lines,因此继续选择低风险测试回归切片
|
||||
- 本轮复核 `CreateGeneratedRegistrySourceShape` 与 invoker emission 路径后确认:
|
||||
- 现有测试已覆盖 request / stream provider 的单一 direct 场景、单一 reflected-implementation 场景、precise reflected 跳过边界,以及各项 runtime contract 缺失分支
|
||||
- 尚未锁定“同一 registry 同时包含 direct registration 与 reflected-implementation registration”时的 descriptor 顺序与 `Invoke*HandlerN` 编号稳定性
|
||||
- 已补齐:
|
||||
- `Emits_Request_Invoker_Provider_Metadata_In_Stable_Order_For_Mixed_Direct_And_Reflected_Implementations`
|
||||
- `Emits_Stream_Invoker_Provider_Metadata_In_Stable_Order_For_Mixed_Direct_And_Reflected_Implementations`
|
||||
- 两组 source fixture:`MixedRequestInvokerProviderSource`、`MixedStreamInvokerProviderSource`
|
||||
- 通过新增回归,显式锁定以下约束:
|
||||
- provider descriptor 条目按稳定实现排序输出
|
||||
- `InvokeRequestHandler0/1` 与 `InvokeStreamHandler0/1` 的方法编号随 emission 顺序连续增长
|
||||
- 隐藏实现类型不会破坏 direct registration 与 reflected-implementation registration 的混合发射
|
||||
|
||||
### 验证(RP-083)
|
||||
|
||||
- `dotnet test GFramework.SourceGenerators.Tests/GFramework.SourceGenerators.Tests.csproj -c Release --filter "FullyQualifiedName~CqrsHandlerRegistryGeneratorTests.Emits_Request_Invoker_Provider_Metadata_In_Stable_Order_For_Mixed_Direct_And_Reflected_Implementations|FullyQualifiedName~CqrsHandlerRegistryGeneratorTests.Emits_Stream_Invoker_Provider_Metadata_In_Stable_Order_For_Mixed_Direct_And_Reflected_Implementations"`
|
||||
- 结果:通过,`2/2` passed
|
||||
|
||||
### 当前 stop-condition 度量(RP-083)
|
||||
|
||||
- primary metric:branch diff files vs `origin/main`
|
||||
- 当前说明:active batch 尚未提交时,基于 `HEAD` 的 branch diff 仍显示 `0` files / `0` lines;提交本批后再以新 `HEAD` 复算累计 branch diff
|
||||
|
||||
### 当前下一步(RP-083)
|
||||
|
||||
1. 提交本轮 mixed invoker provider 排序回归后,复算 branch diff vs `origin/main`,确认 `50` 文件阈值仍有充足余量
|
||||
2. 若继续推进代码切片,优先复核 invoker provider 之外的 runtime contract 或 fallback selection 分支
|
||||
|
||||
### 阶段:benchmark 基础设施引入(CQRS-REWRITE-RP-084)
|
||||
|
||||
- 用户明确将当前长期分支目标上提为:系统性吸收 `ai-libs/Mediator` 的实现思路与设计哲学,并将可取部分纳入 `GFramework.Cqrs`
|
||||
- 本轮据此调整批次目标,不再把关注点收缩到单个 generator 回归,而是建立能持续比较和吸收设计差异的 benchmark 基础设施
|
||||
- 参考 `ai-libs/Mediator` 的 benchmark 设计后,本轮采纳的核心结构包括:
|
||||
- 独立 benchmark 项目壳,而非扩展现有 NUnit 测试项目
|
||||
- 共享 `Fixture` 输出并校验场景配置
|
||||
- `Request` / `Notification` 两个 messaging 场景作为首批最小落点
|
||||
- 自定义列 `CustomColumn`,为后续矩阵扩展保留可读结果标签
|
||||
- 本轮新增:
|
||||
- `GFramework.Cqrs.Benchmarks/GFramework.Cqrs.Benchmarks.csproj`
|
||||
- `GFramework.Cqrs.Benchmarks/Program.cs`
|
||||
- `GFramework.Cqrs.Benchmarks/CustomColumn.cs`
|
||||
- `GFramework.Cqrs.Benchmarks/Messaging/Fixture.cs`
|
||||
- `GFramework.Cqrs.Benchmarks/Messaging/BenchmarkContext.cs`
|
||||
- `GFramework.Cqrs.Benchmarks/Messaging/RequestBenchmarks.cs`
|
||||
- `GFramework.Cqrs.Benchmarks/Messaging/NotificationBenchmarks.cs`
|
||||
- `GFramework.Cqrs.Benchmarks/README.md`
|
||||
- 设计取舍:
|
||||
- 使用最小 `ICqrsContext` marker,避免把完整 `ArchitectureContext` 初始化成本混入 steady-state dispatch
|
||||
- 直接复用 `GFramework.Cqrs.CqrsRuntimeFactory` 与 `MicrosoftDiContainer`,让基准聚焦于 runtime dispatch / publish
|
||||
- 外部对照组先接入 `MediatR`,保持与 `Mediator` benchmark 的对照哲学一致;但本轮仍只做最小 request / notification 场景
|
||||
- 暂不把 source generator benchmark、cold-start 独立工程或完整 pipeline / stream 矩阵一起引入,避免首批 scope 失控
|
||||
- 兼容性修正:
|
||||
- 在根 `GFramework.csproj` 中显式排除 `GFramework.Cqrs.Benchmarks/**`,避免 meta-package 意外编译 benchmark 源码
|
||||
- 将 benchmark 项目加入 `GFramework.sln`,保持仓库级工作流完整
|
||||
|
||||
### 验证(RP-084)
|
||||
|
||||
- `dotnet build GFramework.Cqrs.Benchmarks/GFramework.Cqrs.Benchmarks.csproj -c Release`
|
||||
- 结果:通过,`0 warning / 0 error`
|
||||
- `GIT_DIR=<worktree-git-dir> GIT_WORK_TREE=<worktree-root> python3 scripts/license-header.py --check`
|
||||
- 结果:通过
|
||||
- `git diff --check`
|
||||
- 结果:通过
|
||||
|
||||
### 当前 stop-condition 度量(RP-084)
|
||||
|
||||
- primary metric:branch diff files vs `origin/main`
|
||||
- 当前说明:本轮仍在 `50` 文件阈值以内,可继续按 benchmark 场景或 CQRS runtime 对照能力分批推进
|
||||
|
||||
### 当前下一步(RP-084)
|
||||
|
||||
1. 继续扩展 `GFramework.Cqrs.Benchmarks`,优先补齐 pipeline、stream、cold-start 与 generated invoker provider 对照场景
|
||||
2. 当后续有具体 runtime 优化切片时,用该 benchmark 项目验证是否真正吸收到了 `Mediator` 的低开销 dispatch 设计收益
|
||||
|
||||
### 阶段:stream request benchmark 对照(CQRS-REWRITE-RP-085)
|
||||
|
||||
- 继续沿用 `$gframework-batch-boot 50`,当前 branch diff 相对 `origin/main` 仍明显低于阈值
|
||||
- 在 `RP-084` 已建立独立 benchmark 项目后,本轮优先补齐 `ai-libs/Mediator/benchmarks/Mediator.Benchmarks/Messaging/StreamingBenchmarks.cs` 对应的最小 stream 场景
|
||||
- 选择 stream 作为第二批 benchmark 的原因:
|
||||
- 已有独立的 `CreateStream` runtime 路径和单独的 stream invoker provider 元数据契约
|
||||
- 与 `Mediator` 的 messaging benchmark 分层直接对应
|
||||
- 不需要像 pipeline / cold-start 那样先进一步澄清运行时或宿主边界
|
||||
- 本轮新增:
|
||||
- `GFramework.Cqrs.Benchmarks/Messaging/StreamingBenchmarks.cs`
|
||||
- `GFramework.Cqrs.Benchmarks/README.md` 中的 stream 场景说明
|
||||
- 设计约束:
|
||||
- 保持与前一批一致的三路对照:`Baseline`、`GFramework.Cqrs`、`MediatR`
|
||||
- 基准测量“完整枚举 3 个元素”的全量消费成本,而不是只测创建异步枚举器
|
||||
- 使用最小 `ICqrsContext` marker,继续避免把完整 `ArchitectureContext` 初始化成本混入 steady-state stream dispatch
|
||||
- 结论:
|
||||
- 当前 benchmark 项目已经覆盖 `Request`、`Notification`、`StreamRequest` 三个核心 messaging steady-state 场景
|
||||
- 下一批更适合转向 request pipeline 数量矩阵或 cold-start / initialization,而不是继续扩同层次的 messaging 基线
|
||||
|
||||
### 验证(RP-085)
|
||||
|
||||
- `dotnet build GFramework.Cqrs.Benchmarks/GFramework.Cqrs.Benchmarks.csproj -c Release`
|
||||
- 结果:通过,`0 warning / 0 error`
|
||||
- `GIT_DIR=<worktree-git-dir> GIT_WORK_TREE=<worktree-root> python3 scripts/license-header.py --check`
|
||||
- 结果:通过
|
||||
- `git diff --check`
|
||||
- 结果:通过
|
||||
|
||||
### 当前 stop-condition 度量(RP-085)
|
||||
|
||||
- primary metric:branch diff files vs `origin/main`
|
||||
- 当前说明:新增 stream benchmark 后仍处于 `50` 文件阈值以内,适合继续下一批 request pipeline 或 cold-start 场景
|
||||
|
||||
### 当前下一步(RP-085)
|
||||
|
||||
1. 继续扩展 `GFramework.Cqrs.Benchmarks`,优先补齐 request pipeline 数量矩阵,随后再评估 cold-start / initialization
|
||||
2. 当需要验证 generated invoker provider 的实际收益时,把 request benchmark 扩展为 reflection / generated provider 对照,而不是只停留在框架间对比
|
||||
|
||||
### 阶段:request pipeline 数量矩阵(CQRS-REWRITE-RP-086)
|
||||
|
||||
- 继续沿用 `$gframework-batch-boot 50`,当前 branch diff 相对 `origin/main` 仍明显低于阈值
|
||||
- 本轮把 benchmark 关注点从单纯 messaging steady-state 扩展到 request pipeline 编排行为,原因是:
|
||||
- `ai-libs/Mediator` 的对照价值已经不只在 request / notification / stream 三个入口本身,还在 pipeline 包装策略与生命周期取舍
|
||||
- `GFramework.Cqrs.Internal.CqrsDispatcher` 已按 `behaviorCount` 缓存 `RequestPipelineExecutor<TResponse>` 形状,因此单独量化 `0 / 1 / 4` 个行为的 steady-state 开销有直接信息密度
|
||||
- 本轮新增:
|
||||
- `GFramework.Cqrs.Benchmarks/Messaging/RequestPipelineBenchmarks.cs`
|
||||
- `GFramework.Cqrs.Benchmarks/README.md` 中的 request pipeline 场景说明
|
||||
- 设计取舍:
|
||||
- 采用 `0 / 1 / 4` 个 pipeline 行为,而不是立即扩到更大的参数空间,先锁定最有代表性的无行为 / 少量行为 / 常见多行为矩阵
|
||||
- 使用最小 no-op 行为族,不引入日志、计时或上下文刷新逻辑,避免把测量结果污染成业务行为成本
|
||||
- `GFramework.Cqrs` 与 `MediatR` 侧都只注册当前 benchmark 请求对应的闭合行为类型,确保矩阵反映编排成本而非程序集扫描差异
|
||||
- 接受的只读 subagent 结论:
|
||||
- 下一批 benchmark 继续优先考虑 `cold-start / initialization` 与 `generated provider` 对照,而不是立即照搬 `Mediator` 的 large-project 维度
|
||||
- 当前 `GFramework.Cqrs.Benchmarks` 仍未接入 `Mediator` 包和 `GFramework.Cqrs.SourceGenerators`,因此本轮不扩成 `Mediator_IMediator` / generated-provider 对照,避免 scope 失控
|
||||
- 结论:
|
||||
- 当前 benchmark 项目已经覆盖 `Request`、`Notification`、`StreamRequest` 与 `RequestPipeline`
|
||||
- 后续若要继续贴近 `Mediator` 的 comparison benchmark,最值得优先补的是 initialization / first-hit 与 generated invoker provider,而不是继续横向堆更多 steady-state messaging 入口
|
||||
|
||||
### 验证(RP-086)
|
||||
|
||||
- `dotnet build GFramework.Cqrs.Benchmarks/GFramework.Cqrs.Benchmarks.csproj -c Release`
|
||||
- 结果:通过,`0 warning / 0 error`
|
||||
|
||||
### 当前 stop-condition 度量(RP-086)
|
||||
|
||||
- primary metric:branch diff files vs `origin/main`
|
||||
- 当前说明:提交前基于 `HEAD` 的 branch diff 仍为 `14` files,距离 `50` 文件阈值仍有明显余量
|
||||
|
||||
### 当前下一步(RP-086)
|
||||
|
||||
1. 提交本轮 request pipeline benchmark 后,继续扩展 `GFramework.Cqrs.Benchmarks`,优先补齐 initialization / cold-start 场景
|
||||
2. 当需要验证 dispatcher 预热与 source generator 收益时,引入 generated invoker provider 对照,并评估是否同时接入 `Mediator` concrete runtime 作为更贴近设计哲学的外部参照
|
||||
|
||||
### 阶段:request startup 基线(CQRS-REWRITE-RP-087)
|
||||
|
||||
- 继续沿用 `$gframework-batch-boot 50`,当前 branch diff 相对 `origin/main` 仍明显低于阈值
|
||||
- 本轮目标:把 benchmark 从 steady-state dispatch 再向前推进一层,补齐与 `ai-libs/Mediator/benchmarks/Mediator.Benchmarks/Messaging/Comparison/*` 更接近的 startup 维度
|
||||
- 本轮新增:
|
||||
- `GFramework.Cqrs.Benchmarks/Messaging/RequestStartupBenchmarks.cs`
|
||||
- `GFramework.Cqrs.Benchmarks/README.md` 中的 startup 场景说明
|
||||
- 设计取舍:
|
||||
- `Initialization` 只测“从已配置宿主解析/创建 runtime 句柄”的成本,不把完整架构初始化混入 benchmark
|
||||
- `ColdStart` 只测新宿主上的首次 request send;`GFramework.Cqrs` 侧在每次 benchmark 前通过反射清空 dispatcher 静态缓存,避免把热缓存误当 first-hit
|
||||
- `ColdStart_MediatR` 改为真正 `await` 完任务后再释放 `ServiceProvider`,以满足 `Meziantou.Analyzer` 对资源生命周期的要求,并避免 benchmark 本身含有错误宿主释放语义
|
||||
- 结论:
|
||||
- 当前 benchmark 项目已经覆盖 `Request`、`Notification`、`StreamRequest`、`RequestPipeline`、`RequestStartup`
|
||||
- 后续若继续贴近 `Mediator` comparison benchmark,下一批最有价值的是 generated invoker provider、registration / service lifetime 与 concrete runtime 外部对照,而不是继续只加同层 steady-state case
|
||||
|
||||
### 验证(RP-087)
|
||||
|
||||
- `dotnet build GFramework.Cqrs.Benchmarks/GFramework.Cqrs.Benchmarks.csproj -c Release`
|
||||
- 结果:通过,`0 warning / 0 error`
|
||||
|
||||
### 当前 stop-condition 度量(RP-087)
|
||||
|
||||
- primary metric:branch diff files vs `origin/main`
|
||||
- 当前说明:提交前 branch diff 仍远低于 `50` 文件阈值,可继续下一批 benchmark 或低风险 runtime 对照切片
|
||||
|
||||
### 当前下一步(RP-087)
|
||||
|
||||
1. 提交本轮 request startup benchmark 后,继续扩展 `GFramework.Cqrs.Benchmarks`,优先评估 generated invoker provider 与 registration / service lifetime 矩阵
|
||||
2. 若要更贴近 `Mediator` 的 comparison benchmark 设计哲学,评估是否在 benchmark 项目中同时接入 `Mediator` concrete runtime 对照,而不只保留 `MediatR`
|
||||
|
||||
### 阶段:request invoker reflection / generated 对照(CQRS-REWRITE-RP-088)
|
||||
|
||||
- 继续沿用 `$gframework-batch-boot 50`,当前 branch diff 相对 `origin/main` 仍明显低于阈值
|
||||
- 本轮目标:不再只比较 `GFramework.Cqrs` 与 `MediatR` 的外层框架差异,而是开始直接量化 `GFramework.Cqrs` 内部 reflection request binding 与 generated invoker provider 路径的 steady-state 差异
|
||||
- 本轮新增:
|
||||
- `GFramework.Cqrs.Benchmarks/Messaging/RequestInvokerBenchmarks.cs`
|
||||
- `GFramework.Cqrs.Benchmarks/Messaging/GeneratedRequestInvokerBenchmarkRegistry.cs`
|
||||
- `GFramework.Cqrs.Benchmarks/README.md` 中的 generated invoker 场景说明
|
||||
- 设计取舍:
|
||||
- 采用 benchmark 内手写的 generated registry/provider“等价物”,而不是当轮就把真实 `GFramework.Cqrs.SourceGenerators` 接到 benchmark 项目中,目的是先走通真实的 registrar -> descriptor 预热 -> dispatcher generated path,同时把写入面控制在低风险范围
|
||||
- generated 对照使用程序集级 `CqrsHandlerRegistryAttribute` + `ICqrsRequestInvokerProvider` + `IEnumeratesCqrsRequestInvokerDescriptors`,确保运行时语义与生产路径一致
|
||||
- 在 benchmark 生命周期前后清理 dispatcher 静态缓存,避免 generated descriptor 预热状态跨场景泄漏,污染 reflection 对照
|
||||
- 结论:
|
||||
- 当前 benchmark 项目已经能区分 `GFramework.Cqrs` 的 reflection request 路径、generated request 路径与 `MediatR` 外部对照
|
||||
- 后续若继续贴近 `Mediator` comparison benchmark,下一批更适合扩到 registration / service lifetime、stream generated provider,或再决定是否接入 `Mediator` concrete runtime
|
||||
|
||||
### 验证(RP-088)
|
||||
|
||||
- `dotnet build GFramework.Cqrs.Benchmarks/GFramework.Cqrs.Benchmarks.csproj -c Release`
|
||||
- 结果:通过,`0 warning / 0 error`
|
||||
|
||||
### 当前 stop-condition 度量(RP-088)
|
||||
|
||||
- primary metric:branch diff files vs `origin/main`
|
||||
- 当前说明:提交前 branch diff 仍远低于 `50` 文件阈值,可继续推进下一批 benchmark 对照切片
|
||||
|
||||
### 当前下一步(RP-088)
|
||||
|
||||
1. 提交本轮 request invoker benchmark 后,继续扩展 `GFramework.Cqrs.Benchmarks`,优先评估 registration / service lifetime 或 stream generated provider
|
||||
|
||||
### 阶段:stream invoker reflection / generated 对照(CQRS-REWRITE-RP-089)
|
||||
|
||||
- 使用 `$gframework-batch-boot 30` 继续 `feat/cqrs-optimization` 的 CQRS 收口批次
|
||||
- 本轮基线选择:
|
||||
- `origin/main c01abac0`,committer date `2026-05-06 09:40:08 +0800`
|
||||
- `main a8c6c11e`,committer date `2026-05-05 13:14:24 +0800`
|
||||
- 启动时 branch diff vs `origin/main` 为 `18` files / `2100` lines,低于 `30` 文件阈值,因此继续选择单模块、低风险 benchmark 切片
|
||||
- 复核 `GFramework.Cqrs.Benchmarks` 与 `ai-libs/Mediator/benchmarks` 后确认:
|
||||
- `RP-088` 已把 generated descriptor 预热收益量化到 request dispatch 路径
|
||||
- stream benchmark 仍停留在 direct handler / reflection runtime / `MediatR` 三路对照,尚未量化 generated stream invoker provider 的收益
|
||||
- 虽然 `Mediator` 参考基准大量使用 service lifetime 矩阵,但当前 `GFramework.Cqrs.Benchmarks` 尚未建立对称的 scoped host 模式;直接扩 lifetime 会引入超出本批风险预算的宿主语义变化
|
||||
- 本轮因此优先选择 request 对称切片,而不是 service lifetime 扩展:
|
||||
- 新增 `Messaging/StreamInvokerBenchmarks.cs`
|
||||
- 新增 `Messaging/GeneratedStreamInvokerBenchmarkRegistry.cs`
|
||||
- 更新 `GFramework.Cqrs.Benchmarks/README.md`
|
||||
- 设计约束:
|
||||
- 继续沿用 handwritten generated registry/provider 模式,避免把 benchmark 基础设施与真实 source-generator 输出耦合
|
||||
- 复用与 `RP-088` 相同的 dispatcher 缓存清理策略,确保 reflection / generated 路径对照不受静态缓存残留污染
|
||||
- 使用统一的异步枚举体工厂,让三组 stream handler 共享同一枚举成本基线,把变量收敛到 invoker/provider 接线路径
|
||||
|
||||
### 当前下一步(RP-089)
|
||||
|
||||
1. 完成本轮 benchmark 项目 Release build、license header 检查与 diff 校验后,更新 active tracking 的权威验证列表
|
||||
2. 若 branch diff 仍明显低于 `30` 文件阈值,可继续评估 notification publish strategy 或更贴近 `Mediator` concrete runtime 的单批对照
|
||||
3. 若要继续贴近 `Mediator` 的 comparison benchmark 设计哲学,评估是否把 `Mediator` concrete runtime 本身接入 benchmark 项目,而不是长期只保留 `MediatR`
|
||||
|
||||
### 验证(RP-089)
|
||||
|
||||
- `dotnet build GFramework.Cqrs.Benchmarks/GFramework.Cqrs.Benchmarks.csproj -c Release`
|
||||
- 结果:通过,`0 warning / 0 error`
|
||||
- `GIT_DIR=<worktree-git-dir> GIT_WORK_TREE=<worktree-root> python3 scripts/license-header.py --check`
|
||||
- 结果:通过
|
||||
- `git diff --check`
|
||||
- 结果:通过
|
||||
- `dotnet run --project GFramework.Cqrs.Benchmarks/GFramework.Cqrs.Benchmarks.csproj -c Release -- --filter "*RequestStartupBenchmarks*" --job short --warmupCount 1 --iterationCount 1 --launchCount 1`
|
||||
- 结果:部分通过;`MediatR` startup benchmark 已恢复真实测量,`ColdStart_GFrameworkCqrs` 仍因 `No CQRS request handler registered` 失败
|
||||
|
||||
### 阶段:手动 benchmark workflow(CQRS-REWRITE-RP-089)
|
||||
|
||||
- 新增 `.github/workflows/benchmark.yml`,提供仅 `workflow_dispatch` 触发的 benchmark 入口
|
||||
- workflow 默认只执行 `GFramework.Cqrs.Benchmarks` 的 Release build,避免在当前已知 `RequestStartupBenchmarks` 残留未清时默认运行失败
|
||||
- 只有在手动输入 `benchmark_filter` 时才执行 BenchmarkDotNet,并上传 `BenchmarkDotNet.Artifacts` 供后续比较
|
||||
|
||||
@ -0,0 +1,54 @@
|
||||
# Microsoft DI Container Disposal 跟踪
|
||||
|
||||
## 目标
|
||||
|
||||
围绕 `PR #330` 收敛 `MicrosoftDiContainer` 的释放契约、并发释放竞态,以及 `GFramework.Cqrs.Benchmarks` 的宿主清理鲁棒性。
|
||||
|
||||
## 当前恢复点
|
||||
|
||||
- 恢复点编号:`MICROSOFT-DI-DISPOSAL-RP-001`
|
||||
- 当前阶段:`Phase 1`
|
||||
- 当前 PR 锚点:`PR #330`
|
||||
- 当前结论:
|
||||
- `$gframework-pr-review` 已确认 latest-head review 仍存在 5 条 open AI thread,其中 `IIocContainer` 文档契约、`MicrosoftDiContainer.Clear()` 的不可达释放逻辑、`Dispose()` 并发竞态,以及 benchmark `Cleanup()` 缺乏异常隔离均已在本地补齐
|
||||
- `CodeRabbit` 关于 `GFramework.Cqrs.Benchmarks` 的 cleanup 问题虽然标在单个文件上,但同类模式实际覆盖 `RequestBenchmarks`、`NotificationBenchmarks`、`RequestPipelineBenchmarks`、`RequestStartupBenchmarks`、`StreamingBenchmarks`、`RequestInvokerBenchmarks`、`StreamInvokerBenchmarks`,当前已通过共享 helper 一次性收敛
|
||||
- `MicrosoftDiContainer.Dispose()` 现会先对外发布 `_disposed` 状态并释放写锁,让等待线程统一抛出容器级 `ObjectDisposedException`;随后仅在锁静默后才销毁底层 `ReaderWriterLockSlim`
|
||||
- 针对剩余的 `greptile` P1,本轮进一步将底层锁销毁收敛为单次执行,避免两个并发 `Dispose()` 调用都进入 `DisposeLockWhenQuiescent()` 时触发双重 `ReaderWriterLockSlim.Dispose()`
|
||||
|
||||
## 当前活跃事实
|
||||
|
||||
- 当前分支:`fix/microsoft-di-container-disposal`
|
||||
- 当前分支对应 `PR #330`,状态为 `OPEN`
|
||||
- 已决定的最小修复面:
|
||||
- `GFramework.Core.Abstractions/Ioc/IIocContainer.cs`
|
||||
- `GFramework.Core/Ioc/MicrosoftDiContainer.cs`
|
||||
- `GFramework.Core.Tests/Ioc/IocContainerLifetimeTests.cs`
|
||||
- `GFramework.Core.Tests/Ioc/MicrosoftDiContainerTests.cs`
|
||||
- `GFramework.Cqrs.Benchmarks/Messaging/*.cs` 的 7 个 benchmark cleanup
|
||||
|
||||
## 当前风险
|
||||
|
||||
- 若极端情况下存在长时间不退出的遗留 waiter,`DisposeLockWhenQuiescent()` 会在有限自旋后跳过底层锁销毁并记录警告,以优先保证 `Dispose()` 不被无限阻塞
|
||||
- 并发释放回归测试依赖对内部 `_lock` 的反射访问,需要保持断言目标明确,避免把实现细节暴露成对外契约
|
||||
|
||||
## 最近权威验证
|
||||
|
||||
- `python3 .agents/skills/gframework-pr-review/scripts/fetch_current_pr_review.py --json-output /tmp/gframework-current-pr-review.json`
|
||||
- 结果:通过
|
||||
- 备注:确认当前分支对应 `PR #330`,open AI review 重点已收敛到释放契约、并发竞态和 benchmark cleanup
|
||||
- `python3 scripts/license-header.py --check`
|
||||
- 结果:通过
|
||||
- `dotnet test GFramework.Core.Tests/GFramework.Core.Tests.csproj -c Release --filter "FullyQualifiedName~IocContainerLifetimeTests|FullyQualifiedName~MicrosoftDiContainerTests"`
|
||||
- 结果:通过,`57/57` passed
|
||||
- `dotnet build GFramework.Cqrs.Benchmarks/GFramework.Cqrs.Benchmarks.csproj -c Release`
|
||||
- 结果:通过,`0 warning / 0 error`
|
||||
|
||||
## 待补最新验证
|
||||
|
||||
- `dotnet test GFramework.Core.Tests/GFramework.Core.Tests.csproj -c Release --filter "FullyQualifiedName~IocContainerLifetimeTests"`
|
||||
- `dotnet build GFramework.Core/GFramework.Core.csproj -c Release`
|
||||
|
||||
## 下一推荐步骤
|
||||
|
||||
1. 运行 `IocContainerLifetimeTests` 与 `GFramework.Core` Release build,确认单次锁销毁修复没有引入新的 warning 或回归
|
||||
2. 再次运行 `$gframework-pr-review` 或检查生成的 JSON,确认当前 latest-head open threads 是否只剩待推送的 GitHub 状态差异
|
||||
@ -0,0 +1,40 @@
|
||||
# Microsoft DI Container Disposal 追踪
|
||||
|
||||
## 2026-05-06
|
||||
|
||||
### 阶段:PR #330 review triage 与修复面收敛(MICROSOFT-DI-DISPOSAL-RP-001)
|
||||
|
||||
- 使用 `$gframework-pr-review` 抓取当前分支对应的 `PR #330` latest-head review 后,主线程确认仍有效的 open AI 反馈集中在四类:
|
||||
- `IIocContainer` 缺少显式的释放生命周期文档
|
||||
- `MicrosoftDiContainer.Clear()` 在 `_frozen == false` 路径下仍保留不可达的 `_provider.Dispose()` 调用
|
||||
- `MicrosoftDiContainer.Dispose()` 会让等待中的读写线程泄露 `ReaderWriterLockSlim` 的 `ObjectDisposedException`
|
||||
- 多个 `GFramework.Cqrs.Benchmarks` cleanup 顺序释放资源但缺乏异常隔离,前一个 `Dispose()` 失败会阻断后续资源回收
|
||||
- 本轮决策:
|
||||
- 先补 `ai-plan/public/microsoft-di-container-disposal` 的 tracking / trace,保证该跨模块 PR follow-up 有明确恢复入口
|
||||
- 通过 `EnterReadLockOrThrowDisposed` / `EnterWriteLockOrThrowDisposed` 收口 `MicrosoftDiContainer` 的等待中竞态,而不是零散修补个别 API
|
||||
- 通过共享 `BenchmarkCleanupHelper` 一次性收敛 benchmark 宿主 cleanup 的同类风险
|
||||
- 实现补充:
|
||||
- `IIocContainer` 现已补充释放契约文档,明确 `Dispose()` 幂等性、根 `IServiceProvider` 与同步资源归属,以及释放后的统一异常语义
|
||||
- `MicrosoftDiContainer.Clear()` 已移除未冻结路径下不可达的 `_provider.Dispose()` 调用
|
||||
- `MicrosoftDiContainer.Dispose()` 现先发布 `_disposed`,再等待遗留 waiter 退场后释放底层锁;若锁在有限自旋内未静默,则记录 warning 并跳过锁销毁,避免 `Dispose()` 无限阻塞
|
||||
- `GFramework.Cqrs.Benchmarks` 新增 `BenchmarkCleanupHelper`,并统一接入 7 个 `GlobalCleanup` 入口
|
||||
- 回归验证:
|
||||
- `Dispose_Should_Translate_Waiting_Readers_To_Container_ObjectDisposedException`
|
||||
- `Dispose_Should_Be_Idempotent_When_Called_Concurrently`
|
||||
- `dotnet test GFramework.Core.Tests/GFramework.Core.Tests.csproj -c Release --filter "FullyQualifiedName~IocContainerLifetimeTests|FullyQualifiedName~MicrosoftDiContainerTests"` 通过,`57/57` passed
|
||||
- `dotnet build GFramework.Cqrs.Benchmarks/GFramework.Cqrs.Benchmarks.csproj -c Release` 通过,`0 warning / 0 error`
|
||||
|
||||
### 当前下一步
|
||||
|
||||
1. 推送当前分支后重新运行 `$gframework-pr-review`,确认 latest-head open threads 是否已与本地修复对齐
|
||||
|
||||
### 阶段:收敛剩余并发 Dispose 双重锁销毁竞态(MICROSOFT-DI-DISPOSAL-RP-001)
|
||||
|
||||
- 根据用户补充的 `greptile` P1,重新核对 `MicrosoftDiContainer.Dispose()` 的尾部流程后确认还存在一个更窄的窗口:
|
||||
- 线程 A 与线程 B 都可能通过最外层 `_disposed` 快速路径
|
||||
- 线程 A 完成主释放并退出写锁后,线程 B 仍可能拿到写锁、因为 `_disposed == true` 直接返回,但 `finally` 仍会调用 `DisposeLockWhenQuiescent()`
|
||||
- 这样两个线程都可能执行 `_lock.Dispose()`;第二次调用会抛出 `ObjectDisposedException`
|
||||
- 本轮修复决策:
|
||||
- 在 `DisposeLockWhenQuiescent()` 入口增加 `Interlocked.CompareExchange` 守卫,把底层锁销毁流程收敛为单次执行
|
||||
- 保持现有“先发布 `_disposed`、再等待 waiter 退场”的语义不变,只修复重复销毁底层锁的尾部竞态
|
||||
- 在 `IocContainerLifetimeTests` 增加更直接的回归断言,验证并发 `Dispose()` 后锁销毁启动标记只会变为 `1`
|
||||
@ -812,14 +812,14 @@ if (MonsterConfigBindings.References.TryGetByDisplayPath("dropItems", out var re
|
||||
- `dependentSchemas`:供运行时校验、VS Code 校验、对象 section 表单 hint 和生成代码 XML 文档复用;当前只接受“已声明 sibling 字段触发 object 子 schema”的形状,不改变生成类型形状,并按 focused constraint block 语义允许条件子 schema 未声明的额外同级字段继续存在
|
||||
- `allOf`:供运行时校验、VS Code 校验、对象 section 表单 hint 和生成代码 XML 文档复用;当前只接受 object 节点上的 object-typed inline schema 数组,并按 focused constraint block 语义把每个条目叠加到当前对象上,不做属性合并,也不改变生成类型形状
|
||||
- `if` / `then` / `else`:供运行时校验、VS Code 校验、对象 section 表单 hint 和生成代码 XML 文档复用;当前只接受 object 节点上的 object-typed inline schema,`if` 必填且必须至少配合 `then` 或 `else` 之一使用,分支只能约束父对象已声明的字段,不做属性合并,也不改变生成类型形状;条件匹配本身沿用 `dependentSchemas` / `allOf` 的 focused matcher 语义,允许对象保留未在条件块中声明的额外同级字段
|
||||
- `additionalProperties`:当前共享支持边界只接受 `additionalProperties: false`;它用于声明对象是闭合的,运行时、生成器和工具都会据此拒绝未声明字段。其他 `additionalProperties` 形态当前不属于共享支持子集,会在解析或生成阶段直接被拒绝
|
||||
- `additionalProperties`:当前共享支持边界只接受 `additionalProperties: false`;它用于声明对象是闭合的,运行时、生成器和工具都会据此拒绝未声明字段。其他 `additionalProperties` 形态,以及 `patternProperties`、`propertyNames`、`unevaluatedProperties` 这类会重新打开对象形状的关键字,当前都不属于共享支持子集,会在解析或生成阶段直接被拒绝
|
||||
- `oneOf` / `anyOf`:当前不属于共享支持子集;Runtime / Generator / Tooling 会在解析或生成阶段直接拒绝,避免静默接受会改变生成类型形状的组合关键字
|
||||
|
||||
如果你的 schema 需要超出这些边界的复杂 shape,推荐采用下面的回退顺序:
|
||||
|
||||
1. 先在 raw YAML 与 schema 文件中直接编辑,而不是强行依赖表单入口
|
||||
2. 再核对该 shape 是否仍符合这里列出的共享支持子集
|
||||
3. 如果它依赖 `oneOf` / `anyOf`、非 `false` 的 `additionalProperties`、会向父对象注入新字段的 `allOf` / `dependentSchemas` / `if` 分支,或者更异构的深层数组结构,就应当把它视为当前版本之外的设计,而不是工具层遗漏的“隐藏能力”
|
||||
3. 如果它依赖 `oneOf` / `anyOf`、非 `false` 的 `additionalProperties`、`patternProperties` / `propertyNames` / `unevaluatedProperties` 这类开放对象关键字、会向父对象注入新字段的 `allOf` / `dependentSchemas` / `if` 分支,或者更异构的深层数组结构,就应当把它视为当前版本之外的设计,而不是工具层遗漏的“隐藏能力”
|
||||
|
||||
`allOf` 的最小可工作示例如下。关键点是:字段形状先在父对象 `properties` 中声明,再用 `allOf` 叠加 `required` 或更细的字段约束;`allOf` 条目不会把新字段并回父对象。
|
||||
|
||||
|
||||
@ -86,8 +86,7 @@ IStorage storage = new FileStorage("GameData", serializer);
|
||||
这条工作流的正式契约,以 `GFramework.Game` Runtime 和 `GFramework.Game.SourceGenerators` 当前共享支持的 schema
|
||||
子集为准。`VS Code` 配置工具主要负责编辑期提示和表单辅助,不单独扩展运行时可接受的 schema 形状。
|
||||
|
||||
开始接入时,建议先把 schema 约束控制在共享子集内,并尽早确认像 `additionalProperties: false`(需显式设置为 `false`;省略或 `true` 视为非 `false`)这类已收口的对象边界,以及
|
||||
`oneOf` / `anyOf` 当前会被直接拒绝,而不是在工具里看起来“可以先写”。如果你的配置模型需要更深层的嵌套数组、联合分支或其他超出共享子集的复杂
|
||||
开始接入时,建议先把 schema 约束控制在共享子集内,并尽早确认像 `additionalProperties: false` 这类已收口的对象边界:它必须显式设置为 `false`,省略或 `true` 都视为非 `false`。`patternProperties` / `propertyNames` / `unevaluatedProperties` 当前也不属于共享子集。`oneOf` / `anyOf` 当前会被直接拒绝,而不是在工具里看起来“可以先写”。如果你的配置模型需要更深层的嵌套数组、联合分支或其他超出共享子集的复杂
|
||||
shape,优先回到 raw YAML 和 schema 设计本体处理,再决定是否拆分结构或调整约束方式。
|
||||
|
||||
完整约定见:
|
||||
|
||||
51
scripts/validate-packed-modules.sh
Normal file
51
scripts/validate-packed-modules.sh
Normal file
@ -0,0 +1,51 @@
|
||||
#!/usr/bin/env bash
|
||||
# Copyright (c) 2025-2026 GeWuYou
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
package_dir="${1:-./packages}"
|
||||
|
||||
if [ ! -d "$package_dir" ]; then
|
||||
echo "Package directory not found: $package_dir" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
expected_packages=(
|
||||
"GeWuYou.GFramework"
|
||||
"GeWuYou.GFramework.Core"
|
||||
"GeWuYou.GFramework.Core.Abstractions"
|
||||
"GeWuYou.GFramework.Core.SourceGenerators"
|
||||
"GeWuYou.GFramework.Cqrs"
|
||||
"GeWuYou.GFramework.Cqrs.Abstractions"
|
||||
"GeWuYou.GFramework.Cqrs.SourceGenerators"
|
||||
"GeWuYou.GFramework.Ecs.Arch"
|
||||
"GeWuYou.GFramework.Ecs.Arch.Abstractions"
|
||||
"GeWuYou.GFramework.Game"
|
||||
"GeWuYou.GFramework.Game.Abstractions"
|
||||
"GeWuYou.GFramework.Game.SourceGenerators"
|
||||
"GeWuYou.GFramework.Godot"
|
||||
"GeWuYou.GFramework.Godot.SourceGenerators"
|
||||
)
|
||||
|
||||
work_dir="$(mktemp -d)"
|
||||
trap 'rm -rf "$work_dir"' EXIT
|
||||
|
||||
expected_file="$work_dir/expected-packages.txt"
|
||||
actual_file="$work_dir/actual-packages.txt"
|
||||
|
||||
mapfile -t actual_packages < <(
|
||||
find "$package_dir" -maxdepth 1 -type f -name '*.nupkg' -exec basename {} \; \
|
||||
| sed -E 's/\.[0-9][0-9A-Za-z.-]*\.nupkg$//' \
|
||||
| sort -u
|
||||
)
|
||||
|
||||
printf '%s\n' "${expected_packages[@]}" | sort > "$expected_file"
|
||||
printf '%s\n' "${actual_packages[@]}" > "$actual_file"
|
||||
|
||||
echo "Expected packages:"
|
||||
cat "$expected_file"
|
||||
echo "Actual packages:"
|
||||
cat "$actual_file"
|
||||
|
||||
diff -u "$expected_file" "$actual_file"
|
||||
@ -115,8 +115,8 @@ Minimal adoption checklist:
|
||||
- Place each config domain under `config/<domain>/*.yaml`
|
||||
- Place the matching schema at `schemas/<domain>.schema.json`
|
||||
- Use `x-gframework-ref-table` only on fields that should link to another config domain or reference file
|
||||
- Keep `additionalProperties` explicitly set to `false` when you need closed-object validation; omitting it or setting
|
||||
it to `true` is outside the supported subset
|
||||
- Keep `additionalProperties` explicitly set to `false` when you need closed-object validation; omitting it, setting
|
||||
it to `true`, or mixing in `patternProperties`, `propertyNames`, or `unevaluatedProperties` is outside the supported subset
|
||||
|
||||
Use raw YAML directly when you need:
|
||||
|
||||
@ -124,7 +124,8 @@ Use raw YAML directly when you need:
|
||||
- supported object rules such as `allOf`, `dependentSchemas`, or object-focused `if` / `then` / `else` only when they
|
||||
push the edit path beyond the lightweight form boundary
|
||||
- `contains` / `minContains` / `maxContains` when the structure is easier to reason about directly in YAML
|
||||
- schema designs outside the current shared subset, including `oneOf`, `anyOf`, or non-`false` `additionalProperties`
|
||||
- schema designs outside the current shared subset, including `oneOf`, `anyOf`, non-`false` `additionalProperties`, or
|
||||
other open-object keywords such as `patternProperties`, `propertyNames`, and `unevaluatedProperties`
|
||||
|
||||
## Documentation
|
||||
|
||||
@ -138,8 +139,9 @@ Use raw YAML directly when you need:
|
||||
- Form preview supports nested objects and object-array editing, but deeper nested object arrays inside array items still
|
||||
fall back to raw YAML
|
||||
- Batch editing remains limited to top-level scalar fields and top-level scalar arrays
|
||||
- Closed-object support is limited to `additionalProperties: false`, and unsupported combinators such as `oneOf` /
|
||||
`anyOf` are rejected on purpose
|
||||
- Closed-object support is limited to `additionalProperties: false`; open-object keywords such as
|
||||
`patternProperties`, `propertyNames`, and `unevaluatedProperties` are rejected on purpose, as are unsupported
|
||||
combinators such as `oneOf` / `anyOf`
|
||||
|
||||
## Local Testing
|
||||
|
||||
|
||||
@ -1273,23 +1273,21 @@ function parseSchemaNode(rawNode, displayPath) {
|
||||
/**
|
||||
* Reject open-object keyword forms that would drift away from the Runtime and
|
||||
* Source Generator contracts. The current shared subset keeps object fields
|
||||
* closed and only accepts an explicit `additionalProperties: false` reminder.
|
||||
* closed, only accepts an explicit `additionalProperties: false` reminder, and
|
||||
* rejects other keywords that would reopen object shapes.
|
||||
*
|
||||
* @param {Record<string, unknown>} schemaNode Raw schema object.
|
||||
* @param {string} displayPath Logical property path.
|
||||
*/
|
||||
function validateUnsupportedOpenObjectKeyword(schemaNode, displayPath) {
|
||||
if (!Object.prototype.hasOwnProperty.call(schemaNode, "additionalProperties")) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (schemaNode.additionalProperties === false) {
|
||||
const unsupportedKeyword = getUnsupportedOpenObjectKeywordName(schemaNode);
|
||||
if (!unsupportedKeyword) {
|
||||
return;
|
||||
}
|
||||
|
||||
throw new Error(
|
||||
`Schema property '${displayPath}' uses unsupported 'additionalProperties' metadata. ` +
|
||||
"The current config schema subset only accepts 'additionalProperties: false' so object fields remain closed and strongly typed.");
|
||||
`Schema property '${displayPath}' uses unsupported '${unsupportedKeyword}' metadata. ` +
|
||||
"The current config schema subset only accepts 'additionalProperties: false' and rejects keywords that reopen object shapes so fields remain closed and strongly typed.");
|
||||
}
|
||||
|
||||
/**
|
||||
@ -1380,6 +1378,34 @@ function getUnsupportedCombinatorKeywordName(schemaNode) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the first open-object keyword that the current shared schema subset
|
||||
* intentionally rejects to keep object shapes closed and strongly typed.
|
||||
*
|
||||
* @param {Record<string, unknown>} schemaNode Raw schema object.
|
||||
* @returns {string | undefined} Unsupported keyword name when present.
|
||||
*/
|
||||
function getUnsupportedOpenObjectKeywordName(schemaNode) {
|
||||
if (Object.prototype.hasOwnProperty.call(schemaNode, "additionalProperties") &&
|
||||
schemaNode.additionalProperties !== false) {
|
||||
return "additionalProperties";
|
||||
}
|
||||
|
||||
if (Object.prototype.hasOwnProperty.call(schemaNode, "patternProperties")) {
|
||||
return "patternProperties";
|
||||
}
|
||||
|
||||
if (Object.prototype.hasOwnProperty.call(schemaNode, "propertyNames")) {
|
||||
return "propertyNames";
|
||||
}
|
||||
|
||||
if (Object.prototype.hasOwnProperty.call(schemaNode, "unevaluatedProperties")) {
|
||||
return "unevaluatedProperties";
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse one optional `not` sub-schema and keep path formatting aligned with
|
||||
* the runtime/generator diagnostics.
|
||||
|
||||
@ -228,6 +228,80 @@ test("parseSchemaContent should reject unsupported additionalProperties forms",
|
||||
/unsupported 'additionalProperties' metadata/u);
|
||||
});
|
||||
|
||||
test("parseSchemaContent should allow explicit additionalProperties false", () => {
|
||||
assert.doesNotThrow(() => parseSchemaContent(`
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"reward": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"itemCount": { "type": "integer" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`));
|
||||
});
|
||||
|
||||
test("parseSchemaContent should reject unsupported open-object keywords", () => {
|
||||
assert.throws(
|
||||
() => parseSchemaContent(`
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"reward": {
|
||||
"type": "object",
|
||||
"patternProperties": {
|
||||
"^dynamic-": { "type": "integer" }
|
||||
},
|
||||
"properties": {
|
||||
"itemCount": { "type": "integer" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`),
|
||||
/unsupported 'patternProperties' metadata/u);
|
||||
|
||||
assert.throws(
|
||||
() => parseSchemaContent(`
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"reward": {
|
||||
"type": "object",
|
||||
"propertyNames": {
|
||||
"pattern": "^[a-z]+$"
|
||||
},
|
||||
"properties": {
|
||||
"itemCount": { "type": "integer" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`),
|
||||
/unsupported 'propertyNames' metadata/u);
|
||||
|
||||
assert.throws(
|
||||
() => parseSchemaContent(`
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"reward": {
|
||||
"type": "object",
|
||||
"unevaluatedProperties": false,
|
||||
"properties": {
|
||||
"itemCount": { "type": "integer" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`),
|
||||
/unsupported 'unevaluatedProperties' metadata/u);
|
||||
});
|
||||
|
||||
test("parseSchemaContent should reject unsupported explicit schema types", () => {
|
||||
assert.throws(
|
||||
() => parseSchemaContent(`
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user