@vesviet/agent-skills 5.7.3 → 5.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/INDEX.md +21 -18
- package/README.md +11 -10
- package/VERSION +1 -1
- package/adapters/antigravity/ANTIGRAVITY.md +89 -4
- package/adapters/antigravity/INDEX_TIER1.json +1294 -0
- package/adapters/antigravity/a2a-config.template.yaml +22 -8
- package/adapters/antigravity/role-skill-index.json +48 -19
- package/adapters/claude/CLAUDE_ADAPTER.md +1 -1
- package/adapters/claude/settings.template.json +7 -3
- package/adapters/cursor/hooks.template.json +3 -1
- package/core/contracts/README.md +4 -1
- package/core/contracts/schemas/INDEX.md +7 -1
- package/core/contracts/schemas/a2a-artifact.json +9 -2
- package/core/contracts/schemas/a2a-jsonrpc-envelope.json +7 -2
- package/core/contracts/schemas/a2a-task-progress.json +15 -4
- package/core/contracts/schemas/a2a-task.json +11 -3
- package/core/contracts/schemas/agent-card.json +48 -1
- package/core/contracts/schemas/agent-skills-discovery.json +91 -0
- package/core/contracts/schemas/compliance-report.json +255 -0
- package/core/contracts/schemas/mcp-server-card.json +193 -0
- package/core/contracts/schemas/seo-content-brief.json +1 -1
- package/core/contracts/schemas/seo-weekly-board.json +1 -1
- package/core/contracts/schemas/series-article.json +1 -1
- package/core/policies/action-boundaries.yaml +334 -2
- package/core/policies/mcp-tool-map.yaml +61 -4
- package/core/roles/3d-graphics-engineer.md +5 -1
- package/core/roles/README.md +1 -1
- package/core/roles/agent-coordinator.md +21 -3
- package/core/roles/agent-discovery-engineer.md +27 -8
- package/core/roles/ai-systems-engineer.md +3 -1
- package/core/roles/aws-engineer.md +6 -8
- package/core/roles/backend-developer.md +5 -5
- package/core/roles/business-analyst.md +4 -2
- package/core/roles/cloudflare-engineer.md +4 -2
- package/core/roles/content-manager.md +3 -1
- package/core/roles/content-writer.md +3 -1
- package/core/roles/data-analyst.md +3 -1
- package/core/roles/data-engineer.md +3 -1
- package/core/roles/devops-engineer.md +9 -9
- package/core/roles/ecommerce-engineer.md +7 -7
- package/core/roles/frontend-developer.md +10 -8
- package/core/roles/game-developer.md +5 -3
- package/core/roles/mmo-engineer.md +8 -9
- package/core/roles/mobile-engineer.md +5 -3
- package/core/roles/product-manager.md +8 -9
- package/core/roles/project-manager.md +10 -13
- package/core/roles/prompt-engineer.md +6 -4
- package/core/roles/qa-engineer.md +9 -9
- package/core/roles/references/vietnam-accounting-specialist-review-checklist.md +6 -6
- package/core/roles/researcher.md +12 -14
- package/core/roles/reverse-engineer.md +5 -2
- package/core/roles/reviewer.md +7 -5
- package/core/roles/role-standard.md +23 -1
- package/core/roles/sdet.md +7 -5
- package/core/roles/security-engineer.md +9 -7
- package/core/roles/seo-analyst.md +9 -7
- package/core/roles/solution-architect.md +8 -9
- package/core/roles/sre.md +8 -6
- package/core/roles/system-engineer.md +20 -20
- package/core/roles/task-planner.md +8 -10
- package/core/roles/teacher.md +8 -6
- package/core/roles/technical-architect.md +10 -8
- package/core/roles/technical-lead.md +9 -7
- package/core/roles/technical-writer.md +8 -6
- package/core/roles/ui-ux-designer.md +8 -7
- package/core/roles/vietnam-accounting-specialist.md +26 -24
- package/core/roles/vietnam-legal-counsel.md +6 -4
- package/core/rules/code.md +11 -6
- package/core/skills/README.md +3 -2
- package/core/skills/agent/agent-a2a-protocol/SKILL.md +25 -93
- package/core/skills/agent/agent-memory-compaction/SKILL.md +27 -0
- package/core/skills/agent/architect-mcp-server/SKILL.md +35 -27
- package/core/skills/agent/configure-agent-commerce/SKILL.md +2 -0
- package/core/skills/agent/configure-agent-commerce/examples/ucp-commerce-manifest-and-endpoints.json +55 -0
- package/core/skills/agent/configure-agent-commerce/references/acp-ucp-agent-commerce-manifest-specs.md +66 -0
- package/core/skills/agent/configure-agent-skills/SKILL.md +60 -68
- package/core/skills/agent/manage-agent-identity/SKILL.md +2 -0
- package/core/skills/agent/manage-agent-identity/examples/agent-identity-spire-workload.yaml +72 -0
- package/core/skills/agent/manage-agent-identity/references/nhi-lifecycle-and-token-rotation.md +45 -0
- package/core/skills/ai/openrouter-task/SKILL.md +5 -5
- package/core/skills/ai-agent/agent-evaluation/resources/eval-benchmarks/eval-cases.json +529 -0
- package/core/skills/ai-agent/agent-evaluation/resources/eval-benchmarks/eval-manifest.yaml +61 -0
- package/core/skills/ai-agent/agent-evaluation/scripts/run-eval-benchmark.py +856 -0
- package/core/skills/ai-agent/agent-evaluation/tests/test_golden_benchmarks.py +248 -0
- package/core/skills/ai-agent/context-optimization/SKILL.md +61 -60
- package/core/skills/ai-agent/context-optimization/examples/context-pruner-and-reorderer.py +85 -0
- package/core/skills/ai-agent/context-optimization/references/token-budgeting-and-attention-allocation.md +47 -0
- package/core/skills/ai-agent/memory-hygiene/SKILL.md +13 -0
- package/core/skills/ai-agent/memory-hygiene/examples/memory-audit-and-compaction-routine.py +90 -0
- package/core/skills/ai-agent/memory-hygiene/references/agent-memory-vault-spec.md +137 -0
- package/core/skills/ai-agent/memory-hygiene/references/owasp-asi06-and-memory-poisoning-defense.md +38 -0
- package/core/skills/backend/add-api-endpoint/examples/express-zod-rfc9457-endpoint.md +329 -0
- package/core/skills/backend/add-api-endpoint/examples/kratos-go-clean-architecture-endpoint.md +405 -0
- package/core/skills/backend/add-api-endpoint/references/idempotency-and-rate-limiting.md +116 -0
- package/core/skills/backend/add-event-handler/SKILL.md +1 -1
- package/core/skills/backend/scaffold-new-service/SKILL.md +2 -1
- package/core/skills/backend/scaffold-new-service/references/deep-modules-and-seams.md +43 -0
- package/core/skills/business/elicit-requirements/SKILL.md +1 -0
- package/core/skills/commerce/handle-checkout-flow/SKILL.md +3 -1
- package/core/skills/commerce/handle-checkout-flow/examples/production-checkout-orchestrator.ts +185 -0
- package/core/skills/commerce/handle-checkout-flow/references/pci-dss-v4-and-agentic-checkout-specs.md +72 -0
- package/core/skills/commerce/integrate-payment-gateway/SKILL.md +3 -1
- package/core/skills/commerce/integrate-payment-gateway/examples/resilient-webhook-and-mpp-handler.ts +164 -0
- package/core/skills/commerce/integrate-payment-gateway/references/mpp-x402-and-webhook-security-specs.md +47 -0
- package/core/skills/commerce/manage-order-fulfillment/SKILL.md +3 -1
- package/core/skills/commerce/manage-order-fulfillment/examples/temporal-fulfillment-saga.ts +104 -0
- package/core/skills/commerce/manage-order-fulfillment/references/event-sourced-fulfillment-and-carrier-webhooks.md +58 -0
- package/core/skills/commerce/manage-product-catalog/SKILL.md +3 -1
- package/core/skills/commerce/manage-product-catalog/examples/hybrid-search-and-governance-pipeline.ts +120 -0
- package/core/skills/commerce/manage-product-catalog/references/semantic-vector-catalog-and-graphrag.md +54 -0
- package/core/skills/content/write-article/SKILL.md +1 -1
- package/core/skills/document/pdf/SKILL.md +1 -0
- package/core/skills/document/pdf/references/pdf-acroforms-and-pdfplumber-specs.md +54 -0
- package/core/skills/document/pdf/scripts/check_fillable_fields.py +144 -0
- package/core/skills/document/pdf/scripts/fill_fillable_fields.py +145 -0
- package/core/skills/documentation/configure-llms-txt/SKILL.md +2 -0
- package/core/skills/documentation/configure-llms-txt/examples/canonical-llms-txt-and-full-txt.md +45 -0
- package/core/skills/documentation/configure-llms-txt/references/llms-txt-and-llms-full-txt-standard.md +37 -0
- package/core/skills/documentation/write-documentation/SKILL.md +3 -1
- package/core/skills/documentation/write-documentation/examples/microservice-production-readme-and-api-docs.md +70 -0
- package/core/skills/documentation/write-documentation/references/diataxis-framework-and-doc-standards.md +62 -0
- package/core/skills/foundation/ai-risk-assessment/SKILL.md +3 -5
- package/core/skills/foundation/ai-risk-assessment/examples/genai-system-risk-register.md +67 -0
- package/core/skills/foundation/ai-risk-assessment/references/nist-ai-rmf-and-eu-ai-act-taxonomy.md +49 -0
- package/core/skills/foundation/conduct-research/SKILL.md +1 -1
- package/core/skills/foundation/discernment-nudge/SKILL.md +1 -0
- package/core/skills/foundation/plan-technical-delivery/SKILL.md +2 -1
- package/core/skills/foundation/release-notes/SKILL.md +2 -3
- package/core/skills/foundation/release-notes/examples/enterprise-platform-release-notes.md +42 -0
- package/core/skills/foundation/release-notes/references/keep-a-changelog-and-semver-governance.md +43 -0
- package/core/skills/foundation/systematic-debugging/SKILL.md +5 -0
- package/core/skills/foundation/write-tests/examples/anti-tautological-tdd-walkthrough.md +204 -0
- package/core/skills/foundation/write-tests/examples/testcontainers-kratos-integration-test.md +186 -0
- package/core/skills/foundation/write-tests/references/contract-and-chaos-testing.md +187 -0
- package/core/skills/frontend/INDEX.json +16 -0
- package/core/skills/frontend/add-page-route/SKILL.md +3 -1
- package/core/skills/frontend/add-page-route/examples/streaming-rsc-page-with-view-transition.tsx +133 -0
- package/core/skills/frontend/add-page-route/references/rsc-routing-and-view-transitions.md +72 -0
- package/core/skills/frontend/add-ui-component/SKILL.md +3 -1
- package/core/skills/frontend/add-ui-component/examples/compound-dialog-and-form-actions.tsx +193 -0
- package/core/skills/frontend/add-ui-component/references/react19-component-standards-and-anti-slop.md +55 -0
- package/core/skills/frontend/component-composition/SKILL.md +2 -1
- package/core/skills/frontend/component-composition/examples/headless-combobox-compound-component.tsx +207 -0
- package/core/skills/frontend/frontend-testing/SKILL.md +3 -1
- package/core/skills/frontend/frontend-testing/examples/playwright-e2e-with-msw-and-axe.spec.ts +87 -0
- package/core/skills/frontend/frontend-testing/references/playwright-msw-and-a11y-testing-standards.md +78 -0
- package/core/skills/frontend/implement-ai-disclosure/SKILL.md +118 -0
- package/core/skills/frontend/implement-webmcp/SKILL.md +3 -1
- package/core/skills/frontend/implement-webmcp/examples/webmcp-provider-and-hitl-modal.tsx +163 -0
- package/core/skills/frontend/implement-webmcp/references/webmcp-architecture-and-hitl-security.md +48 -0
- package/core/skills/frontend/integrate-api-client/SKILL.md +3 -1
- package/core/skills/frontend/integrate-api-client/examples/orval-query-and-streaming-mutation.ts +102 -0
- package/core/skills/frontend/integrate-api-client/references/orval-tanstack-query-and-streaming-specs.md +57 -0
- package/core/skills/frontend/setup-design-system/SKILL.md +3 -1
- package/core/skills/frontend/setup-design-system/examples/tailwind-v4-theme-and-dtcg-tokens.css +87 -0
- package/core/skills/frontend/setup-design-system/references/tailwind-v4-oklch-and-dtcg-tokens.md +61 -0
- package/core/skills/frontend/setup-visual-regression/SKILL.md +3 -1
- package/core/skills/frontend/setup-visual-regression/examples/visual-regression-playwright.config.ts +83 -0
- package/core/skills/frontend/setup-visual-regression/references/visual-regression-docker-and-masking-specs.md +46 -0
- package/core/skills/gamedev/abstract-input-actions/SKILL.md +2 -0
- package/core/skills/gamedev/abstract-input-actions/examples/input-action-manager.ts +85 -0
- package/core/skills/gamedev/abstract-input-actions/references/action-mapping-and-analog-deadzones.md +54 -0
- package/core/skills/gamedev/architect-ecs-systems/SKILL.md +2 -0
- package/core/skills/gamedev/architect-ecs-systems/examples/bevy-flecs-combat-system.rs +73 -0
- package/core/skills/gamedev/architect-ecs-systems/references/data-oriented-design-and-archetype-ecs.md +39 -0
- package/core/skills/gamedev/author-game-ai/SKILL.md +2 -0
- package/core/skills/gamedev/author-game-ai/examples/modular-behavior-tree-ai.ts +98 -0
- package/core/skills/gamedev/author-game-ai/references/behavior-trees-and-utility-ai-curves.md +47 -0
- package/core/skills/gamedev/configure-physics-collision/SKILL.md +2 -0
- package/core/skills/gamedev/configure-physics-collision/examples/kinematic-physics-substepping.cpp +100 -0
- package/core/skills/gamedev/configure-physics-collision/references/continuous-collision-detection-and-substepping.md +50 -0
- package/core/skills/gamedev/develop-gameplay-systems/SKILL.md +2 -0
- package/core/skills/gamedev/develop-gameplay-systems/examples/kinematic-character-controller.gd +86 -0
- package/core/skills/gamedev/develop-gameplay-systems/references/deterministic-gameplay-state-machines.md +42 -0
- package/core/skills/gamedev/implement-save-persistence/SKILL.md +2 -0
- package/core/skills/gamedev/implement-save-persistence/examples/versioned-save-manager.ts +127 -0
- package/core/skills/gamedev/implement-save-persistence/references/versioned-save-schemas-and-checksums.md +44 -0
- package/core/skills/gamedev/render-webgl-threejs/SKILL.md +2 -0
- package/core/skills/gamedev/render-webgl-threejs/examples/production-threejs-webgpu-scene.ts +116 -0
- package/core/skills/gamedev/render-webgl-threejs/references/webgpu-threejs-pbr-pipeline.md +56 -0
- package/core/skills/mmo/analyze-campaign-roi/SKILL.md +2 -0
- package/core/skills/mmo/analyze-campaign-roi/examples/campaign-roi-and-roas-dashboard.py +80 -0
- package/core/skills/mmo/analyze-campaign-roi/references/multi-touch-attribution-and-cpa-analytics.md +33 -0
- package/core/skills/mmo/create-automation-script/SKILL.md +2 -0
- package/core/skills/mmo/create-automation-script/examples/stealth-browser-automation-flow.ts +65 -0
- package/core/skills/mmo/create-automation-script/references/stealth-cdp-and-behavioral-mimicry.md +37 -0
- package/core/skills/mmo/deploy-mmo-infrastructure/SKILL.md +2 -0
- package/core/skills/mmo/deploy-mmo-infrastructure/examples/proxy-health-probe-and-rotation-daemon.py +75 -0
- package/core/skills/mmo/deploy-mmo-infrastructure/references/proxy-pool-rotation-and-anti-detect-specs.md +45 -0
- package/core/skills/mmo/deploy-proxyware-fleet/SKILL.md +2 -0
- package/core/skills/mmo/deploy-proxyware-fleet/examples/docker-compose-depin-light-node-fleet.yaml +52 -0
- package/core/skills/mmo/deploy-proxyware-fleet/references/depin-bandwidth-monetization-node-specs.md +43 -0
- package/core/skills/mmo/generate-mmo-content/SKILL.md +2 -0
- package/core/skills/mmo/generate-mmo-content/examples/pseo-programmatic-page-generator.ts +76 -0
- package/core/skills/mmo/generate-mmo-content/references/pseo-landing-pages-and-social-video-hooks.md +39 -0
- package/core/skills/mmo/manage-mmo-assets/SKILL.md +2 -0
- package/core/skills/mmo/manage-mmo-assets/examples/mmo-asset-vault-manager.py +63 -0
- package/core/skills/mmo/manage-mmo-assets/references/mmo-asset-rbac-and-vault-isolation.md +38 -0
- package/core/skills/mmo/setup-tracking-system/SKILL.md +2 -0
- package/core/skills/mmo/setup-tracking-system/examples/meta-capi-s2s-event-dispatcher.ts +79 -0
- package/core/skills/mmo/setup-tracking-system/references/server-to-server-postback-and-capi-specs.md +45 -0
- package/core/skills/platform/add-telemetry-instrumentation/SKILL.md +2 -0
- package/core/skills/platform/add-telemetry-instrumentation/examples/kratos-otel-middleware-instrumentation.go +87 -0
- package/core/skills/platform/add-telemetry-instrumentation/references/opentelemetry-semantic-conventions-2026.md +37 -0
- package/core/skills/platform/aws-infrastructure/SKILL.md +2 -0
- package/core/skills/platform/aws-infrastructure/examples/opentofu-eks-pod-identity-vpc.tf +101 -0
- package/core/skills/platform/aws-infrastructure/references/opentofu-aws-zero-trust-and-irsa.md +40 -0
- package/core/skills/platform/setup-deployment/SKILL.md +4 -0
- package/core/skills/platform/setup-deployment/examples/kustomize-production-service-manifests.yaml +123 -0
- package/core/skills/platform/setup-deployment/references/interactive-hitl-wizard.md +55 -0
- package/core/skills/platform/setup-deployment/references/k8s-gitops-and-kustomize-invariants.md +40 -0
- package/core/skills/platform/supply-chain-security/SKILL.md +2 -0
- package/core/skills/platform/supply-chain-security/examples/github-actions-sbom-cosign.yaml +57 -0
- package/core/skills/platform/supply-chain-security/references/slsa-provenance-and-sbom-sigstore.md +60 -0
- package/core/skills/product/build-story-map/SKILL.md +2 -0
- package/core/skills/repo-ops/review-code/SKILL.md +2 -2
- package/core/skills/repo-ops/review-code/examples/adversarial-two-axis-pr-review.md +167 -0
- package/core/skills/repo-ops/review-code/examples/ai-vibe-slop-remediation.md +220 -0
- package/core/skills/repo-ops/review-code/references/supply-chain-and-migration-safety.md +103 -0
- package/core/skills/repo-ops/review-service/SKILL.md +1 -1
- package/core/skills/security-data/database-maintenance/SKILL.md +1 -1
- package/core/skills/security-data/manage-secrets/SKILL.md +2 -0
- package/core/skills/security-data/manage-secrets/examples/external-secrets-vault-crds.yaml +53 -0
- package/core/skills/security-data/manage-secrets/references/zero-trust-secret-rotation-and-eso.md +30 -0
- package/core/skills/security-data/manage-vietnam-accounting/SKILL.md +7 -7
- package/core/skills/security-data/prompt-injection-defense/SKILL.md +2 -0
- package/core/skills/security-data/prompt-injection-defense/examples/bounded-tool-execution-wrapper.py +78 -0
- package/core/skills/security-data/prompt-injection-defense/references/prompt-injection-taxonomy-and-delimiters.md +37 -0
- package/core/skills/security-data/reverse-engineer-binary/SKILL.md +2 -0
- package/core/skills/security-data/reverse-engineer-binary/examples/binary-triage-and-vulnerability-dossier.md +58 -0
- package/core/skills/security-data/reverse-engineer-binary/references/ghidra-radare2-and-rea-evidence-ledgers.md +43 -0
- package/core/skills/security-data/security-audit/SKILL.md +3 -1
- package/core/skills/security-data/security-audit/examples/enterprise-service-security-audit-report.md +54 -0
- package/core/skills/security-data/security-audit/references/owasp-asi-and-cvss4-threat-modeling.md +39 -0
- package/core/skills/security-data/skill-preflight-ast-check/SKILL.md +2 -0
- package/core/skills/security-data/skill-preflight-ast-check/references/ast-lethal-trifecta-and-static-vetting.md +38 -0
- package/core/skills/security-data/skill-preflight-ast-check/scripts/scan-skill-ast.py +127 -0
- package/overlays/README.md +1 -1
- package/overlays/security-research/README.md +1 -1
- package/package.json +2 -2
- package/overlays/security-research/skills/reverse-engineer-binary/SKILL.md +0 -129
package/core/skills/backend/add-api-endpoint/examples/kratos-go-clean-architecture-endpoint.md
ADDED
|
@@ -0,0 +1,405 @@
|
|
|
1
|
+
# Worked Example: Go Kratos Clean Architecture Endpoint
|
|
2
|
+
|
|
3
|
+
This worked example demonstrates an enterprise-grade endpoint in Go 1.25+ using the Kratos v2.9.1 microservices framework, strictly adhering to Clean Architecture across `api`, `service`, `biz`, and `data` layers with GORM transaction safety (`InTx`) and table-driven unit tests.
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## 1. Protobuf Contract (`api/payment/v1/payment.proto`)
|
|
8
|
+
|
|
9
|
+
```protobuf
|
|
10
|
+
syntax = "proto3";
|
|
11
|
+
|
|
12
|
+
package payment.v1;
|
|
13
|
+
|
|
14
|
+
option go_package = "payment/api/payment/v1;v1";
|
|
15
|
+
|
|
16
|
+
import "google/api/annotations.proto";
|
|
17
|
+
import "validate/validate.proto";
|
|
18
|
+
|
|
19
|
+
service PaymentService {
|
|
20
|
+
rpc ProcessPayment (ProcessPaymentRequest) returns (ProcessPaymentReply) {
|
|
21
|
+
option (google.api.http) = {
|
|
22
|
+
post: "/v1/payments"
|
|
23
|
+
body: "*"
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
message ProcessPaymentRequest {
|
|
29
|
+
string idempotency_key = 1 [(validate.rules).string = {min_len: 16, max_len: 128}];
|
|
30
|
+
int64 amount_cents = 2 [(validate.rules).int64 = {gt: 0}];
|
|
31
|
+
string currency = 3 [(validate.rules).string = {len: 3}];
|
|
32
|
+
string recipient_id = 4 [(validate.rules).string = {uuid: true}];
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
message ProcessPaymentReply {
|
|
36
|
+
string payment_id = 1;
|
|
37
|
+
string status = 2;
|
|
38
|
+
int64 amount_cents = 3;
|
|
39
|
+
string currency = 4;
|
|
40
|
+
string recipient_id = 5;
|
|
41
|
+
int64 created_at = 6;
|
|
42
|
+
}
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
---
|
|
46
|
+
|
|
47
|
+
## 2. Biz Layer — Pure Business Logic (`internal/biz/payment.go`)
|
|
48
|
+
|
|
49
|
+
The biz layer contains domain models and usecases. It has **zero knowledge of GORM, SQL, or transport protocols**:
|
|
50
|
+
|
|
51
|
+
```go
|
|
52
|
+
package biz
|
|
53
|
+
|
|
54
|
+
import (
|
|
55
|
+
"context"
|
|
56
|
+
"errors"
|
|
57
|
+
"time"
|
|
58
|
+
|
|
59
|
+
"github.com/go-kratos/kratos/v2/log"
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
var (
|
|
63
|
+
ErrInvalidAmount = errors.New("payment amount must be greater than zero")
|
|
64
|
+
ErrDuplicatePayment = errors.New("duplicate payment transaction detected")
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
type Payment struct {
|
|
68
|
+
ID string
|
|
69
|
+
IdempotencyKey string
|
|
70
|
+
AmountCents int64
|
|
71
|
+
Currency string
|
|
72
|
+
RecipientID string
|
|
73
|
+
Status string
|
|
74
|
+
CreatedAt time.Time
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
type PaymentRepo interface {
|
|
78
|
+
Save(ctx context.Context, p *Payment) (*Payment, error)
|
|
79
|
+
GetByIdempotencyKey(ctx context.Context, key string) (*Payment, error)
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
type Transaction interface {
|
|
83
|
+
InTx(ctx context.Context, fn func(ctx context.Context) error) error
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
type PaymentUsecase struct {
|
|
87
|
+
repo PaymentRepo
|
|
88
|
+
tx Transaction
|
|
89
|
+
log *log.Helper
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
func NewPaymentUsecase(repo PaymentRepo, tx Transaction, logger log.Logger) *PaymentUsecase {
|
|
93
|
+
return &PaymentUsecase{
|
|
94
|
+
repo: repo,
|
|
95
|
+
tx: tx,
|
|
96
|
+
log: log.NewHelper(logger),
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
func (uc *PaymentUsecase) ProcessPayment(ctx context.Context, p *Payment) (*Payment, error) {
|
|
101
|
+
if p.AmountCents <= 0 {
|
|
102
|
+
return nil, ErrInvalidAmount
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// Verify idempotency
|
|
106
|
+
existing, err := uc.repo.GetByIdempotencyKey(ctx, p.IdempotencyKey)
|
|
107
|
+
if err == nil && existing != nil {
|
|
108
|
+
uc.log.WithContext(ctx).Infof("Idempotent replay for key: %s", p.IdempotencyKey)
|
|
109
|
+
return existing, nil
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
p.Status = "SETTLED"
|
|
113
|
+
p.CreatedAt = time.Now().UTC()
|
|
114
|
+
|
|
115
|
+
var created *Payment
|
|
116
|
+
err = uc.tx.InTx(ctx, func(ctx context.Context) error {
|
|
117
|
+
var saveErr error
|
|
118
|
+
created, saveErr = uc.repo.Save(ctx, p)
|
|
119
|
+
return saveErr
|
|
120
|
+
})
|
|
121
|
+
|
|
122
|
+
if err != nil {
|
|
123
|
+
return nil, err
|
|
124
|
+
}
|
|
125
|
+
return created, nil
|
|
126
|
+
}
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
---
|
|
130
|
+
|
|
131
|
+
## 3. Data Layer — Persistence (`internal/data/payment.go`)
|
|
132
|
+
|
|
133
|
+
The data layer implements `biz.PaymentRepo` and `biz.Transaction` using GORM:
|
|
134
|
+
|
|
135
|
+
```go
|
|
136
|
+
package data
|
|
137
|
+
|
|
138
|
+
import (
|
|
139
|
+
"context"
|
|
140
|
+
"errors"
|
|
141
|
+
"time"
|
|
142
|
+
|
|
143
|
+
"payment/internal/biz"
|
|
144
|
+
|
|
145
|
+
"github.com/go-kratos/kratos/v2/log"
|
|
146
|
+
"gorm.io/gorm"
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
type PaymentPO struct {
|
|
150
|
+
ID string `gorm:"primaryKey;type:varchar(64)"`
|
|
151
|
+
IdempotencyKey string `gorm:"uniqueIndex;type:varchar(128);not null"`
|
|
152
|
+
AmountCents int64 `gorm:"not null"`
|
|
153
|
+
Currency string `gorm:"type:varchar(3);not null"`
|
|
154
|
+
RecipientID string `gorm:"type:varchar(64);not null"`
|
|
155
|
+
Status string `gorm:"type:varchar(32);not null"`
|
|
156
|
+
CreatedAt time.Time `gorm:"not null"`
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
func (PaymentPO) TableName() string {
|
|
160
|
+
return "payments"
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
type paymentRepo struct {
|
|
164
|
+
data *Data
|
|
165
|
+
log *log.Helper
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
func NewPaymentRepo(data *Data, logger log.Logger) biz.PaymentRepo {
|
|
169
|
+
return &paymentRepo{
|
|
170
|
+
data: data,
|
|
171
|
+
log: log.NewHelper(logger),
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
func (r *paymentRepo) Save(ctx context.Context, p *biz.Payment) (*biz.Payment, error) {
|
|
176
|
+
po := &PaymentPO{
|
|
177
|
+
ID: p.ID,
|
|
178
|
+
IdempotencyKey: p.IdempotencyKey,
|
|
179
|
+
AmountCents: p.AmountCents,
|
|
180
|
+
Currency: p.Currency,
|
|
181
|
+
RecipientID: p.RecipientID,
|
|
182
|
+
Status: p.Status,
|
|
183
|
+
CreatedAt: p.CreatedAt,
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
db := r.data.DB(ctx)
|
|
187
|
+
if err := db.WithContext(ctx).Create(po).Error; err != nil {
|
|
188
|
+
return nil, err
|
|
189
|
+
}
|
|
190
|
+
return p, nil
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
func (r *paymentRepo) GetByIdempotencyKey(ctx context.Context, key string) (*biz.Payment, error) {
|
|
194
|
+
var po PaymentPO
|
|
195
|
+
db := r.data.DB(ctx)
|
|
196
|
+
err := db.WithContext(ctx).Where("idempotency_key = ?", key).First(&po).Error
|
|
197
|
+
if err != nil {
|
|
198
|
+
if errors.Is(err, gorm.ErrRecordNotFound) {
|
|
199
|
+
return nil, nil
|
|
200
|
+
}
|
|
201
|
+
return nil, err
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
return &biz.Payment{
|
|
205
|
+
ID: po.ID,
|
|
206
|
+
IdempotencyKey: po.IdempotencyKey,
|
|
207
|
+
AmountCents: po.AmountCents,
|
|
208
|
+
Currency: po.Currency,
|
|
209
|
+
RecipientID: po.RecipientID,
|
|
210
|
+
Status: po.Status,
|
|
211
|
+
CreatedAt: po.CreatedAt,
|
|
212
|
+
}, nil
|
|
213
|
+
}
|
|
214
|
+
```
|
|
215
|
+
|
|
216
|
+
---
|
|
217
|
+
|
|
218
|
+
## 4. Service Layer — Adapter (`internal/service/payment.go`)
|
|
219
|
+
|
|
220
|
+
Adapts incoming Protobuf DTOs to Biz entities and maps domain errors to gRPC/HTTP status codes:
|
|
221
|
+
|
|
222
|
+
```go
|
|
223
|
+
package service
|
|
224
|
+
|
|
225
|
+
import (
|
|
226
|
+
"context"
|
|
227
|
+
|
|
228
|
+
v1 "payment/api/payment/v1"
|
|
229
|
+
"payment/internal/biz"
|
|
230
|
+
|
|
231
|
+
"github.com/go-kratos/kratos/v2/errors"
|
|
232
|
+
"github.com/go-kratos/kratos/v2/log"
|
|
233
|
+
"github.com/google/uuid"
|
|
234
|
+
)
|
|
235
|
+
|
|
236
|
+
type PaymentService struct {
|
|
237
|
+
v1.UnimplementedPaymentServiceServer
|
|
238
|
+
uc *biz.PaymentUsecase
|
|
239
|
+
log *log.Helper
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
func NewPaymentService(uc *biz.PaymentUsecase, logger log.Logger) *PaymentService {
|
|
243
|
+
return &PaymentService{
|
|
244
|
+
uc: uc,
|
|
245
|
+
log: log.NewHelper(logger),
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
func (s *PaymentService) ProcessPayment(ctx context.Context, req *v1.ProcessPaymentRequest) (*v1.ProcessPaymentReply, error) {
|
|
250
|
+
entity := &biz.Payment{
|
|
251
|
+
ID: uuid.New().String(),
|
|
252
|
+
IdempotencyKey: req.IdempotencyKey,
|
|
253
|
+
AmountCents: req.AmountCents,
|
|
254
|
+
Currency: req.Currency,
|
|
255
|
+
RecipientID: req.RecipientId,
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
res, err := s.uc.ProcessPayment(ctx, entity)
|
|
259
|
+
if err != nil {
|
|
260
|
+
if errors.Is(err, biz.ErrInvalidAmount) {
|
|
261
|
+
return nil, errors.BadRequest("INVALID_AMOUNT", err.Error())
|
|
262
|
+
}
|
|
263
|
+
s.log.WithContext(ctx).Errorf("Internal payment error: %v", err)
|
|
264
|
+
return nil, errors.InternalServer("PAYMENT_FAILED", "Unable to complete transaction")
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
return &v1.ProcessPaymentReply{
|
|
268
|
+
PaymentId: res.ID,
|
|
269
|
+
Status: res.Status,
|
|
270
|
+
AmountCents: res.AmountCents,
|
|
271
|
+
Currency: res.Currency,
|
|
272
|
+
RecipientId: res.RecipientID,
|
|
273
|
+
CreatedAt: res.CreatedAt.Unix(),
|
|
274
|
+
}, nil
|
|
275
|
+
}
|
|
276
|
+
```
|
|
277
|
+
|
|
278
|
+
---
|
|
279
|
+
|
|
280
|
+
## 5. Table-Driven Unit Tests (`internal/biz/payment_test.go`)
|
|
281
|
+
|
|
282
|
+
```go
|
|
283
|
+
package biz_test
|
|
284
|
+
|
|
285
|
+
import (
|
|
286
|
+
"context"
|
|
287
|
+
"testing"
|
|
288
|
+
"time"
|
|
289
|
+
|
|
290
|
+
"payment/internal/biz"
|
|
291
|
+
|
|
292
|
+
"github.com/go-kratos/kratos/v2/log"
|
|
293
|
+
"github.com/stretchr/testify/assert"
|
|
294
|
+
"github.com/stretchr/testify/mock"
|
|
295
|
+
)
|
|
296
|
+
|
|
297
|
+
type MockRepo struct {
|
|
298
|
+
mock.Mock
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
func (m *MockRepo) Save(ctx context.Context, p *biz.Payment) (*biz.Payment, error) {
|
|
302
|
+
args := m.Called(ctx, p)
|
|
303
|
+
if args.Get(0) == nil {
|
|
304
|
+
return nil, args.Error(1)
|
|
305
|
+
}
|
|
306
|
+
return args.Get(0).(*biz.Payment), args.Error(1)
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
func (m *MockRepo) GetByIdempotencyKey(ctx context.Context, key string) (*biz.Payment, error) {
|
|
310
|
+
args := m.Called(ctx, key)
|
|
311
|
+
if args.Get(0) == nil {
|
|
312
|
+
return nil, args.Error(1)
|
|
313
|
+
}
|
|
314
|
+
return args.Get(0).(*biz.Payment), args.Error(1)
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
type MockTx struct{}
|
|
318
|
+
|
|
319
|
+
func (m *MockTx) InTx(ctx context.Context, fn func(ctx context.Context) error) error {
|
|
320
|
+
return fn(ctx)
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
func TestProcessPayment(t *testing.T) {
|
|
324
|
+
tests := []struct {
|
|
325
|
+
name string
|
|
326
|
+
input *biz.Payment
|
|
327
|
+
setupMock func(r *MockRepo)
|
|
328
|
+
expectError error
|
|
329
|
+
checkResult func(t *testing.T, res *biz.Payment)
|
|
330
|
+
}{
|
|
331
|
+
{
|
|
332
|
+
name: "Success - New Payment Settled",
|
|
333
|
+
input: &biz.Payment{
|
|
334
|
+
IdempotencyKey: "test-key-1234567890",
|
|
335
|
+
AmountCents: 5000,
|
|
336
|
+
Currency: "USD",
|
|
337
|
+
RecipientID: "rec-123",
|
|
338
|
+
},
|
|
339
|
+
setupMock: func(r *MockRepo) {
|
|
340
|
+
r.On("GetByIdempotencyKey", mock.Anything, "test-key-1234567890").Return(nil, nil)
|
|
341
|
+
r.On("Save", mock.Anything, mock.MatchedBy(func(p *biz.Payment) bool {
|
|
342
|
+
return p.AmountCents == 5000 && p.Status == "SETTLED"
|
|
343
|
+
})).Return(&biz.Payment{
|
|
344
|
+
ID: "pay-uuid-001",
|
|
345
|
+
Status: "SETTLED",
|
|
346
|
+
AmountCents: 5000,
|
|
347
|
+
CreatedAt: time.Now(),
|
|
348
|
+
}, nil)
|
|
349
|
+
},
|
|
350
|
+
expectError: nil,
|
|
351
|
+
checkResult: func(t *testing.T, res *biz.Payment) {
|
|
352
|
+
assert.Equal(t, "SETTLED", res.Status)
|
|
353
|
+
assert.Equal(t, int64(5000), res.AmountCents)
|
|
354
|
+
},
|
|
355
|
+
},
|
|
356
|
+
{
|
|
357
|
+
name: "Error - Invalid Amount Rejected",
|
|
358
|
+
input: &biz.Payment{
|
|
359
|
+
AmountCents: -100,
|
|
360
|
+
},
|
|
361
|
+
setupMock: func(r *MockRepo) {},
|
|
362
|
+
expectError: biz.ErrInvalidAmount,
|
|
363
|
+
checkResult: func(t *testing.T, res *biz.Payment) {
|
|
364
|
+
assert.Nil(t, res)
|
|
365
|
+
},
|
|
366
|
+
},
|
|
367
|
+
{
|
|
368
|
+
name: "Success - Idempotent Replay Cached Record",
|
|
369
|
+
input: &biz.Payment{
|
|
370
|
+
IdempotencyKey: "replayed-key-9999",
|
|
371
|
+
AmountCents: 1000,
|
|
372
|
+
},
|
|
373
|
+
setupMock: func(r *MockRepo) {
|
|
374
|
+
r.On("GetByIdempotencyKey", mock.Anything, "replayed-key-9999").Return(&biz.Payment{
|
|
375
|
+
ID: "cached-pay-id",
|
|
376
|
+
Status: "SETTLED",
|
|
377
|
+
AmountCents: 1000,
|
|
378
|
+
}, nil)
|
|
379
|
+
},
|
|
380
|
+
expectError: nil,
|
|
381
|
+
checkResult: func(t *testing.T, res *biz.Payment) {
|
|
382
|
+
assert.Equal(t, "cached-pay-id", res.ID)
|
|
383
|
+
},
|
|
384
|
+
},
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
for _, tc := range tests {
|
|
388
|
+
t.Run(tc.name, func(t *testing.T) {
|
|
389
|
+
repo := new(MockRepo)
|
|
390
|
+
tc.setupMock(repo)
|
|
391
|
+
uc := biz.NewPaymentUsecase(repo, &MockTx{}, log.DefaultLogger)
|
|
392
|
+
|
|
393
|
+
res, err := uc.ProcessPayment(context.Background(), tc.input)
|
|
394
|
+
|
|
395
|
+
if tc.expectError != nil {
|
|
396
|
+
assert.ErrorIs(t, err, tc.expectError)
|
|
397
|
+
} else {
|
|
398
|
+
assert.NoError(t, err)
|
|
399
|
+
}
|
|
400
|
+
tc.checkResult(t, res)
|
|
401
|
+
repo.AssertExpectations(t)
|
|
402
|
+
})
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
```
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
# Idempotency, Rate Limiting & Deadline Propagation — Reference
|
|
2
|
+
|
|
3
|
+
This reference documents 2027 production standards for enterprise-grade API endpoints: IETF Idempotency-Key handling, distributed Redis atomic locking, sliding window rate limiting, and context deadline propagation.
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## 1. IETF Idempotency-Key Specification & Replay Semantics
|
|
8
|
+
|
|
9
|
+
Idempotency ensures that executing an HTTP mutating operation (e.g., `POST /v1/payments`, `POST /v1/orders`) multiple times with the same key produces the identical side-effect and returns the identical response.
|
|
10
|
+
|
|
11
|
+
### 1.1 Protocol Invariants (IETF Draft `draft-ietf-httpapi-idempotency-key-header`)
|
|
12
|
+
1. **Header Identification**: Clients supply the `Idempotency-Key: <unique-token>` header (typically UUID v4 or ULID, 16–128 characters).
|
|
13
|
+
2. **Payload Fingerprinting**: Store a SHA-256 digest of the request method, URL path, and raw JSON request body alongside the key.
|
|
14
|
+
3. **State Transitions**:
|
|
15
|
+
- `STARTED`: The request is currently processing. A concurrent request with the same key returns `409 Conflict` (or waits if lock acquisition with timeout is supported).
|
|
16
|
+
- `COMPLETED`: The operation completed successfully. Replaying requests return the cached HTTP status code, headers, and response payload with an `Idempotent-Replayed: true` header.
|
|
17
|
+
- `MISMATCH`: If a request arrives with an existing key but a differing payload SHA-256 digest, immediately reject with `422 Unprocessable Entity` or `400 Bad Request` (`Idempotency-Key collision with conflicting payload`).
|
|
18
|
+
4. **Time-To-Live (TTL)**: Keys persist for a configured retention window (minimum 24 hours).
|
|
19
|
+
|
|
20
|
+
### 1.2 Redis Distributed State Machine (Atomic Lua Script)
|
|
21
|
+
|
|
22
|
+
```lua
|
|
23
|
+
-- KEYS[1]: idemp:{key}
|
|
24
|
+
-- ARGV[1]: request_hash (SHA-256)
|
|
25
|
+
-- ARGV[2]: ttl_seconds (e.g., 86400)
|
|
26
|
+
local record = redis.call("HGETALL", KEYS[1])
|
|
27
|
+
if #record == 0 then
|
|
28
|
+
-- Key not seen before: initialize state to STARTED
|
|
29
|
+
redis.call("HSET", KEYS[1], "status", "STARTED", "hash", ARGV[1])
|
|
30
|
+
redis.call("EXPIRE", KEYS[1], ARGV[2])
|
|
31
|
+
return { "NEW" }
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
local status, stored_hash
|
|
35
|
+
for i = 1, #record, 2 do
|
|
36
|
+
if record[i] == "status" then status = record[i+1] end
|
|
37
|
+
if record[i] == "hash" then stored_hash = record[i+1] end
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
if stored_hash ~= ARGV[1] then
|
|
41
|
+
return { "MISMATCH" }
|
|
42
|
+
end
|
|
43
|
+
|
|
44
|
+
if status == "STARTED" then
|
|
45
|
+
return { "IN_PROGRESS" }
|
|
46
|
+
elseif status == "COMPLETED" then
|
|
47
|
+
local response = redis.call("HGET", KEYS[1], "response")
|
|
48
|
+
local status_code = redis.call("HGET", KEYS[1], "status_code")
|
|
49
|
+
return { "CACHED", status_code, response }
|
|
50
|
+
end
|
|
51
|
+
|
|
52
|
+
return { "UNKNOWN" }
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
---
|
|
56
|
+
|
|
57
|
+
## 2. Sliding Window Rate Limiting
|
|
58
|
+
|
|
59
|
+
Rate limiting protects downstream services from Denial of Service (DoS) and noisy neighbor starvation while providing actionable backoff telemetry to clients.
|
|
60
|
+
|
|
61
|
+
### 2.1 Standard Telemetry Headers (IETF RFC 6585 / draft-ietf-httpapi-ratelimit-headers)
|
|
62
|
+
Every response (success or rejected) must include standard headers:
|
|
63
|
+
- `RateLimit-Limit`: Maximum requests permitted within window.
|
|
64
|
+
- `RateLimit-Remaining`: Requests remaining within active window.
|
|
65
|
+
- `RateLimit-Reset`: Seconds remaining until quota reset.
|
|
66
|
+
- `Retry-After`: Included on `429 Too Many Requests`, indicating wait time before retry.
|
|
67
|
+
|
|
68
|
+
### 2.2 Redis Sorted Set (ZSET) Sliding Log Algorithm
|
|
69
|
+
The sliding log algorithm eliminates the edge-burst vulnerability inherent in fixed-window counters:
|
|
70
|
+
|
|
71
|
+
```typescript
|
|
72
|
+
import { Redis } from "ioredis";
|
|
73
|
+
|
|
74
|
+
export async function checkSlidingRateLimit(
|
|
75
|
+
redis: Redis,
|
|
76
|
+
identifier: string,
|
|
77
|
+
limit: number,
|
|
78
|
+
windowSeconds: number
|
|
79
|
+
): Promise<{ allowed: boolean; remaining: number; resetAfter: number }> {
|
|
80
|
+
const key = `ratelimit:${identifier}`;
|
|
81
|
+
const now = Date.now();
|
|
82
|
+
const windowStart = now - windowSeconds * 1000;
|
|
83
|
+
|
|
84
|
+
const pipeline = redis.pipeline();
|
|
85
|
+
pipeline.zremrangebyscore(key, 0, windowStart); // Drop expired hits
|
|
86
|
+
pipeline.zadd(key, now, `${now}-${Math.random()}`); // Record current request
|
|
87
|
+
pipeline.zcard(key); // Total hits in window
|
|
88
|
+
pipeline.expire(key, windowSeconds); // Keep key alive
|
|
89
|
+
|
|
90
|
+
const results = await pipeline.exec();
|
|
91
|
+
const currentCount = (results?.[2]?.[1] as number) || 0;
|
|
92
|
+
const allowed = currentCount <= limit;
|
|
93
|
+
|
|
94
|
+
return {
|
|
95
|
+
allowed,
|
|
96
|
+
remaining: Math.max(0, limit - currentCount),
|
|
97
|
+
resetAfter: windowSeconds
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
---
|
|
103
|
+
|
|
104
|
+
## 3. Context Deadline Propagation & Cancellation Safety
|
|
105
|
+
|
|
106
|
+
Distributed API systems must prevent "zombie compute" where downstream databases and microservices continue working after the upstream client has timed out or disconnected.
|
|
107
|
+
|
|
108
|
+
### 3.1 Strict Timeout Hierarchy
|
|
109
|
+
1. **Client Gateway / Ingress Timeout**: e.g., 5.0 seconds.
|
|
110
|
+
2. **Service Route Handler Timeout**: Derived from request context, capped at Gateway - 500ms (e.g., 4.5 seconds).
|
|
111
|
+
3. **Database / RPC Downstream Timeout**: Capped at Route Handler - 500ms (e.g., 3.0 seconds).
|
|
112
|
+
|
|
113
|
+
### 3.2 Cancellation Rules
|
|
114
|
+
- **Context Propagation**: Always pass `ctx` (`context.Context` in Go, `AbortSignal` in TypeScript/Node.js) to every database query, RPC call, and HTTP client invocation.
|
|
115
|
+
- **Early Exit**: Inspect `ctx.Err()` or `signal.aborted` before starting CPU-intensive work or acquiring heavyweight mutexes.
|
|
116
|
+
- **Rollback Safety**: Ensure database transactions cleanly rollback when `context.Canceled` or `context.DeadlineExceeded` occurs. Never commit an uncompleted transaction.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: add-event-handler
|
|
3
|
-
description: Add or modify event publishers, consumers, or subscriber flows by following the repo's event contract, delivery semantics, idempotency rules, and rollout constraints. Use
|
|
3
|
+
description: Add or modify event publishers, consumers, or subscriber flows by following the repo's event contract, delivery semantics, idempotency rules, and rollout constraints. Use when publishing or consuming events, implementing Transactional Outbox patterns, enforcing deduplication, or extending event-driven service workflows.
|
|
4
4
|
version: 1.0.0
|
|
5
5
|
allowed-tools: [read_file, write_file, edit_file, create_file, search_code, run_tests, run_linter, run_build, execute_command]
|
|
6
6
|
---
|
|
@@ -25,8 +25,9 @@ Use this skill to bootstrap new microservices, workers, or bounded components us
|
|
|
25
25
|
- **Sandbox readiness**: generate a multi-stage rootless `Dockerfile` (`USER nonroot`, read-only rootfs compatibility) and local test harness compatible with Level 0 air-gapped sandboxes (`--network=none`) per `core/policies/execution-sandbox.md`
|
|
26
26
|
- **Observability from commit 1**: implement `/health/live`, `/health/ready` probes and initialize OpenTelemetry tracer bootstrap with trace context propagation
|
|
27
27
|
- **Dependency injection**: use compile-time DI (Wire, Fx, or repo standard) for all constructor injection; no global state or `init()` singletons
|
|
28
|
+
- **Ousterhout Deep Modules & Seam Discipline**: design thin, stable public interfaces hiding deep implementations; apply *The Deletion Test*, *Design It Twice*, and the Two-Adapter rule (*1 adapter = hypothesis, 2+ adapters = proven seam*), keeping tests anchored to the public interface seam
|
|
28
29
|
- **Zero secrets in scaffold**: declare environment configurations and secret bindings via external secret stores; reject hardcoded credentials
|
|
29
|
-
- detailed directory layouts, Dockerfiles, and
|
|
30
|
+
- detailed directory layouts, Dockerfiles, and deep-module design guides: [`references/service-scaffolding-guide.md`](references/service-scaffolding-guide.md) and [`references/deep-modules-and-seams.md`](references/deep-modules-and-seams.md)
|
|
30
31
|
|
|
31
32
|
## Suggested Process
|
|
32
33
|
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
# Ousterhout Deep Modules, Seams & Interface-First Testing Reference
|
|
2
|
+
|
|
3
|
+
Use these structural design heuristics (synthesized from John Ousterhout's *A Philosophy of Software Design*, Michael Feathers' *Working Effectively with Legacy Code*, and `mattpocock/skills`) when architecting new services, boundaries, or TypeScript/backend modules.
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## 1. Core Design Vocabulary
|
|
8
|
+
|
|
9
|
+
- **Module:** Any cohesive unit with an exported interface and a hidden implementation (package, service, microservice client, domain class).
|
|
10
|
+
- **Deep Module vs Shallow Module:**
|
|
11
|
+
- **Deep Module:** Exposes a small, intuitive interface hiding substantial implementation complexity. Maximizes **Leverage** (callers learn very little to accomplish a lot) and **Locality** (behavior changes require editing one module, not ten).
|
|
12
|
+
- **Shallow Module (Reject):** Exposes a large or mirror-image interface whose body only forwards calls or adds boilerplate wrapper indirection, inflating context window overhead.
|
|
13
|
+
- **Seam:** A boundary point where system behavior can be altered or substituted without editing source code at the call site — the exact boundary where a module's public interface sits.
|
|
14
|
+
- **Adapter:** A concrete implementation satisfying the contract at a seam.
|
|
15
|
+
|
|
16
|
+
---
|
|
17
|
+
|
|
18
|
+
## 2. Architectural Guardrails
|
|
19
|
+
|
|
20
|
+
### 2.1 The Two-Adapter Rule ("Two Adapters Prove a Seam")
|
|
21
|
+
- Creating an abstract interface or repository wrapper around **one** concrete implementation proves only a *hypothetical seam* (speculative generality / Middle Man smell).
|
|
22
|
+
- Require **two or more concrete adapters** (e.g. primary database/provider plus fake/in-memory adapter or multiple carrier APIs) before introducing an abstraction seam.
|
|
23
|
+
|
|
24
|
+
### 2.2 The Deletion Test
|
|
25
|
+
Evaluate every intermediate wrapper, helper, or facade with a thought experiment:
|
|
26
|
+
- *If deleting the module causes complexity to simply disappear without touching callers* $\rightarrow$ it was a useless shallow pass-through wrapper; inline and delete it.
|
|
27
|
+
- *If deleting the module forces complex invariants and branching to fragment across $N$ call sites* $\rightarrow$ it is a justified Deep Module protecting callers.
|
|
28
|
+
|
|
29
|
+
### 2.3 Design It Twice
|
|
30
|
+
Before locking a new cross-module contract or service interface, sketch **two genuinely different structural designs** (not cosmetic renamings) and compare caller ergonomics, seam testability, and blast radius before picking the cleaner boundary.
|
|
31
|
+
|
|
32
|
+
---
|
|
33
|
+
|
|
34
|
+
## 3. Interface Is The Test Surface (Seam-Based TDD)
|
|
35
|
+
- Both production callers and automated tests must traverse the **same public interface seam**.
|
|
36
|
+
- Prohibit unit tests that reach past the interface seam to assert private fields, internal helper invocation counts, or tautological mock behavior mirroring the implementation.
|
|
37
|
+
- Prefer real in-memory adapters or sandbox containers behind clean ports over deep mock trees.
|
|
38
|
+
|
|
39
|
+
---
|
|
40
|
+
|
|
41
|
+
## 4. TypeScript Deep Module Conventions (Node / Astro / Next.js / Workers)
|
|
42
|
+
- **Root Entrypoint Enforcement (`dependency-cruiser`):** Configure architectural lint rules (`check:deps`) forbidding cross-module imports into internal subpaths (`src/modules/<mod>/internal/**`), allowing imports solely through each module's public root entrypoint while avoiding indiscriminate barrel re-export chains that trigger circular imports or bundle bloat.
|
|
43
|
+
- **Type-Safe Test Builders (`fromPartial()` over `as any`):** Replace unsafe `as any` or bare type assertions in test fixtures with strongly typed partial builders (e.g. `fromPartial(...)` via `@total-typescript/shoehorn` or strict helper factories) so interface evolutions surface compile-time breaks immediately.
|
|
@@ -24,6 +24,7 @@ Use this skill to extract, clarify, and validate business requirements from stak
|
|
|
24
24
|
2. *Probing phase*: drill down into edge cases, volumes, exceptions, and business rules ("What happens when an approval exceeds 48 hours?")
|
|
25
25
|
3. *Closed confirmation phase*: lock specific thresholds, states, and acceptance boundaries ("Is 50,000 USD the absolute hard ceiling for Level 2 approval?")
|
|
26
26
|
- **Apply the Colombo Method for Tacit Knowledge**: adopt a deliberate, structured curiosity posture to surface hidden assumptions; ask "naive" boundary questions that force stakeholders to articulate unwritten organizational habits and tribal knowledge
|
|
27
|
+
- **Socratic Decision-Tree Grilling & Repo-First Lookup**: model ambiguous scope as a design decision tree, resolve facts answerable from codebase/docs via search before asking stakeholders, compute the unresolved **Decision Frontier**, and present batched numbered questions with a clear `(Recommended)` default option
|
|
27
28
|
- **Mandate 9 BABOK v3 Requirement Quality Criteria**: every requirement item must pass the 9 characteristics:
|
|
28
29
|
- *Atomic*: captures a single requirement, never joined with compound "and/or" clauses
|
|
29
30
|
- *Complete*: includes context, preconditions, error states, and measurable outcomes
|
|
@@ -185,5 +185,7 @@ Skip emission for single-checkout experiments that do not cross a role boundary.
|
|
|
185
185
|
- **manage-order-fulfillment**: Hand off the confirmed order for packing and shipping
|
|
186
186
|
- **add-ui-component**: Build the cart and checkout UI components
|
|
187
187
|
- **write-tests**: Write integration tests for the purchase funnel
|
|
188
|
+
- Companion reference: `references/pci-dss-v4-and-agentic-checkout-specs.md`
|
|
189
|
+
- Companion example: `examples/production-checkout-orchestrator.ts`
|
|
188
190
|
|
|
189
|
-
Last updated: 2026-
|
|
191
|
+
Last updated: 2026-11-08
|