azcodr 1.0.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/.agents/skills/agentic-architect/SKILL.md +118 -0
- package/.agents/skills/agentic-architect/references/agents_md_template.md +59 -0
- package/.agents/skills/agentic-architect/references/refinement_workflow.md +32 -0
- package/.agents/skills/agentic-architect/references/skill_architecture_inquiry.md +63 -0
- package/.agents/skills/agentic-architect/references/skill_template.md +55 -0
- package/.agents/skills/agentic-architect/scripts/validate_agentic_configs.sh +163 -0
- package/.agents/skills/clean-code-refactor/SKILL.md +91 -0
- package/.agents/skills/clean-code-refactor/references/clean_code_smells.md +27 -0
- package/.agents/skills/clean-code-refactor/references/design_patterns_ts.md +65 -0
- package/.agents/skills/compliance-audit/SKILL.md +120 -0
- package/.agents/skills/compliance-audit/references/owasp_top10_controls.md +16 -0
- package/.agents/skills/compliance-audit/references/soc2_iso_controls.md +28 -0
- package/.agents/skills/lets-build/SKILL.md +164 -0
- package/.agents/skills/lets-build/references/architecture_interview_matrix.md +188 -0
- package/.agents/skills/lets-build/references/hexagonal_bootstrap_scaffolds.md +113 -0
- package/.agents/skills/lets-build/references/project_readme_template.md +79 -0
- package/.agents/skills/lets-build/scripts/bootstrap_workspace.sh +68 -0
- package/.agents/skills/merge-ai/SKILL.md +90 -0
- package/.agents/skills/merge-ai/scripts/audit_divergence.sh +108 -0
- package/.agents/skills/merge-ai/scripts/resolve_repo.sh +177 -0
- package/.agents/skills/product-analyst/SKILL.md +143 -0
- package/.agents/skills/product-analyst/references/backlog_ordering_techniques.md +107 -0
- package/.agents/skills/product-analyst/references/gherkin_patterns.md +46 -0
- package/.agents/skills/product-analyst/references/invest_checklist.md +38 -0
- package/.agents/skills/product-analyst/references/okr_alignment_guide.md +76 -0
- package/.agents/skills/product-analyst/references/smart_tasks.md +59 -0
- package/.agents/skills/relentless-questioner/SKILL.md +120 -0
- package/.agents/skills/relentless-questioner/references/adaptive_question_trees.md +84 -0
- package/.gitignore +20 -0
- package/AGENTS.md +119 -0
- package/LICENSE +21 -0
- package/README.md +184 -0
- package/bin/azcodr.js +151 -0
- package/docs/knowledge/dos_and_donts.md +540 -0
- package/docs/knowledge/issue_log.md +25 -0
- package/docs/knowledge/knowledge_graph.md +188 -0
- package/docs/knowledge/lessons_learned.md +107 -0
- package/docs/knowledge/ubiquitous_language.md +23 -0
- package/docs/rules/accessibility.md +31 -0
- package/docs/rules/advanced_api_patterns.md +104 -0
- package/docs/rules/agentic_configuration.md +168 -0
- package/docs/rules/api_versioning.md +128 -0
- package/docs/rules/application_security.md +23 -0
- package/docs/rules/architecture_decision_records.md +42 -0
- package/docs/rules/authentication.md +76 -0
- package/docs/rules/authorization.md +75 -0
- package/docs/rules/caching.md +52 -0
- package/docs/rules/clean_code.md +25 -0
- package/docs/rules/cloud_native.md +43 -0
- package/docs/rules/compliance.md +25 -0
- package/docs/rules/container_infrastructure.md +32 -0
- package/docs/rules/continuous_deployment.md +24 -0
- package/docs/rules/continuous_integration.md +20 -0
- package/docs/rules/continuous_learning.md +29 -0
- package/docs/rules/database_integrity.md +88 -0
- package/docs/rules/database_migrations.md +41 -0
- package/docs/rules/database_operations.md +27 -0
- package/docs/rules/database_performance.md +44 -0
- package/docs/rules/database_transactions.md +81 -0
- package/docs/rules/design_patterns.md +40 -0
- package/docs/rules/devsecops.md +33 -0
- package/docs/rules/domain_driven_design.md +84 -0
- package/docs/rules/domain_expertise.md +42 -0
- package/docs/rules/error_handling.md +39 -0
- package/docs/rules/feature_flags.md +42 -0
- package/docs/rules/gof_design_patterns_reference.md +70 -0
- package/docs/rules/multitenancy_isolation.md +86 -0
- package/docs/rules/product_ownership.md +150 -0
- package/docs/rules/project_management.md +66 -0
- package/docs/rules/react.md +88 -0
- package/docs/rules/relentless_questioning.md +48 -0
- package/docs/rules/requirements_engineering.md +113 -0
- package/docs/rules/rest_api_conventions.md +62 -0
- package/docs/rules/server_driven_ui.md +71 -0
- package/docs/rules/tenant_dynamic_schemas.md +88 -0
- package/docs/rules/tenant_pluggable_logic.md +59 -0
- package/docs/rules/test_driven_development.md +106 -0
- package/docs/rules/test_isolation.md +26 -0
- package/docs/rules/transactional_email.md +20 -0
- package/docs/rules/typescript.md +55 -0
- package/docs/rules/ui_navigation.md +20 -0
- package/docs/rules/ui_ux_architecture.md +168 -0
- package/docs/rules/upstream_synchronization.md +66 -0
- package/docs/rules/workflow_state_machines.md +118 -0
- package/docs/rules/workspace_isolation.md +25 -0
- package/lib/index.js +5 -0
- package/lib/scaffold.js +177 -0
- package/memory.md +262 -0
- package/package.json +49 -0
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
# Database Integrity, Constraints & Defensive Design
|
|
2
|
+
|
|
3
|
+
> **Core Mandate:** Enforce data integrity via explicit foreign key delete semantics, domain CHECK constraints, interval exclusion constraints, partial unique indexes for soft deletes, and Universal Total Audit accountability.
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## 1. Foreign Key `ON DELETE` Semantics
|
|
8
|
+
|
|
9
|
+
- **Default to `RESTRICT`**: For critical domain entities, tenant records, and financial ledgers to prevent accidental cascade destruction.
|
|
10
|
+
- **Use `CASCADE` Strictly**: For direct, owned child records (e.g. `OrderItem` owned by `Order`).
|
|
11
|
+
- **Use `SET NULL`**: When foreign relations are optional.
|
|
12
|
+
|
|
13
|
+
---
|
|
14
|
+
|
|
15
|
+
## 2. Domain CHECK Constraints & Interval Exclusion
|
|
16
|
+
|
|
17
|
+
- **Domain Invariants**:
|
|
18
|
+
```sql
|
|
19
|
+
ALTER TABLE "Invoice" ADD CONSTRAINT chk_invoice_positive_amount CHECK (amount >= 0);
|
|
20
|
+
ALTER TABLE "Subscription" ADD CONSTRAINT chk_sub_dates CHECK (end_date >= start_date);
|
|
21
|
+
```
|
|
22
|
+
- **Prevent Overlapping Reservations**:
|
|
23
|
+
```sql
|
|
24
|
+
CREATE EXTENSION IF NOT EXISTS btree_gist;
|
|
25
|
+
ALTER TABLE "RoomReservation" ADD CONSTRAINT no_overlapping_reservations
|
|
26
|
+
EXCLUDE USING gist (room_id WITH =, reservation_period WITH &&);
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
---
|
|
30
|
+
|
|
31
|
+
## 3. Soft Delete Unique Constraint Trap
|
|
32
|
+
|
|
33
|
+
A standard `UNIQUE(email)` constraint fails when an active user signs up with the email of a soft-deleted record.
|
|
34
|
+
- **Mandatory Standard**: Always use partial unique indexes for soft-deleted tables:
|
|
35
|
+
```sql
|
|
36
|
+
CREATE UNIQUE INDEX idx_users_email_active ON "User"(email) WHERE deleted_at IS NULL;
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
---
|
|
40
|
+
|
|
41
|
+
## 4. Relational Foreign Key Invariants & UI Mapping
|
|
42
|
+
|
|
43
|
+
- **Mandatory Existence Validation:** The application and domain layers must defensively assert foreign key target existence prior to child entity persistence. If a referenced parent entity does not exist, return an RFC 7807 problem detail (`400 Bad Request` or `404 Not Found`).
|
|
44
|
+
- **No Raw Identifier Text Inputs:** User interfaces must never expose raw string or UUID input fields for foreign key references. Associations must be selected via accessible dropdown selectors (`shadcn/ui` `<Select>`) displaying human-readable contextual metadata (names, labels, numbers, pricing).
|
|
45
|
+
- **Complete Lifecycle CRUD:** All relational entities must provide complete CRUD functionality (Create, Read/Detail, Update/Transition, Delete/Archive) before being considered feature-complete.
|
|
46
|
+
|
|
47
|
+
---
|
|
48
|
+
|
|
49
|
+
## 5. Mandatory Universal Audit Columns
|
|
50
|
+
|
|
51
|
+
Every stateful entity across all relational schemas, ORMs, and persistence layers must maintain strict audit accountability.
|
|
52
|
+
|
|
53
|
+
### The Canonical 6 Total Audit Fields:
|
|
54
|
+
All mutable database tables, domain entities, and models must define the total audit suite:
|
|
55
|
+
1. **`createdAt` / `created_at`** (`TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP`): Immutable timestamp when the record was initially created.
|
|
56
|
+
2. **`createdBy` / `created_by`** (`VARCHAR/TEXT NOT NULL DEFAULT 'SYSTEM'`): The user ID (`User.id`) of the authenticated actor who created the record, or `'SYSTEM'` for automated background tasks, seeds, or system bootstrap.
|
|
57
|
+
3. **`updatedAt` / `updated_at`** (`TIMESTAMP WITH TIME ZONE NOT NULL`): Timestamp automatically updated on every record mutation.
|
|
58
|
+
4. **`updatedBy` / `updated_by`** (`VARCHAR/TEXT NOT NULL DEFAULT 'SYSTEM'`): The user ID (`User.id`) of the authenticated actor who performed the most recent mutation, or `'SYSTEM'` for automated workflows.
|
|
59
|
+
5. **`deletedAt` / `deleted_at`** (`TIMESTAMP WITH TIME ZONE NULL`): Timestamp when the record was soft-deleted/archived. Null for active records.
|
|
60
|
+
6. **`deletedBy` / `deleted_by`** (`VARCHAR/TEXT NULL`): The user ID (`User.id`) of the authenticated actor who performed or authorized deletion, or `'SYSTEM'`.
|
|
61
|
+
|
|
62
|
+
All queries for active records MUST filter `WHERE deletedAt IS NULL` (or ORM equivalent). Paired with partial unique indexes `WHERE deleted_at IS NULL` where uniqueness constraints apply.
|
|
63
|
+
|
|
64
|
+
### Append-Only Immutable Ledgers / Log Streams:
|
|
65
|
+
Pure financial ledgers (e.g. `PaymentLedgerEntry`, `JournalEntry`) and event outbox streams are strictly immutable. They require:
|
|
66
|
+
- **`createdAt` / `created_at`** (`NOT NULL DEFAULT CURRENT_TIMESTAMP`)
|
|
67
|
+
- **`createdBy` / `created_by`** (`NOT NULL DEFAULT 'SYSTEM'`)
|
|
68
|
+
- *Mutations and soft-deletes are prohibited*: `updatedAt`, `updatedBy`, `deletedAt`, and `deletedBy` are omitted because records are append-only. Financial adjustments must be recorded as offsetting ledger entries.
|
|
69
|
+
|
|
70
|
+
---
|
|
71
|
+
|
|
72
|
+
## 6. Invariants, DO's & DONT's
|
|
73
|
+
|
|
74
|
+
### DO's:
|
|
75
|
+
- **DO:** Include the canonical total audit fields (`createdAt`, `createdBy`, `updatedAt`, `updatedBy`, `deletedAt`, `deletedBy`) on every mutable entity model.
|
|
76
|
+
- **DO:** Populate `createdBy`, `updatedBy`, and `deletedBy` from the verified session actor (`req.user.id`), falling back explicitly to `'SYSTEM'` only for background daemons or public bootstrap.
|
|
77
|
+
- **DO:** Default foreign keys to `RESTRICT` for root aggregates and financial ledgers to prevent accidental cascading data loss.
|
|
78
|
+
- **DO:** Enforce foreign key validation in use cases before persistence, returning RFC 7807 problem details if referenced records do not exist.
|
|
79
|
+
- **DO:** Render foreign key associations using relational selectors (`shadcn/ui` `<Select>`) showing human-readable business metadata (names, labels, numbers, emails).
|
|
80
|
+
- **DO:** Ensure every entity/feature implements full lifecycle CRUD (Create, Read/Detail, Update/Status Transition, Delete/Archive) before considering it complete.
|
|
81
|
+
- **DO:** Filter active records with `WHERE deleted_at IS NULL` and pair uniqueness with partial indexes (`WHERE deleted_at IS NULL`).
|
|
82
|
+
|
|
83
|
+
### DONT's:
|
|
84
|
+
- **DONT:** Never create a database table or entity without `createdAt` and `createdBy`.
|
|
85
|
+
- **DONT:** Never omit `updatedBy` or `deletedBy` on mutable tables. Every mutation and deletion must have an accountable actor.
|
|
86
|
+
- **DONT:** Never expose raw string text inputs for foreign key identifiers in the user interface.
|
|
87
|
+
- **DONT:** Never consider a feature complete if it only implements creation or listing without update, transition, or deletion capabilities.
|
|
88
|
+
- **DONT:** Never allow cascading deletes on master entities with dependent transactional history.
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
# Zero-Downtime Database Migrations (Expand-Contract)
|
|
2
|
+
|
|
3
|
+
> **Core Mandate:** Enforce versioned declarative migrations, zero-downtime expand-contract schema evolutions, non-blocking concurrent index creation, and two-phase constraint validation.
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## 1. Universal Versioned & Declarative Migrations
|
|
8
|
+
|
|
9
|
+
- **Strict Version Control**: All database modifications must occur via versioned migration engines (**Atlas**, **Flyway**, **Liquibase**, or **Goose**).
|
|
10
|
+
- **Prohibited Actions**: Strictly forbid unversioned schema-push commands or raw manual DDL in staging or production environments.
|
|
11
|
+
- **Automated CI Validation**: CI pipelines must lint migrations for breaking changes, lock timeouts, and full-table scans before merging schema PRs.
|
|
12
|
+
|
|
13
|
+
---
|
|
14
|
+
|
|
15
|
+
## 2. Safe Column Additions & Deprecations (Expand-Contract)
|
|
16
|
+
|
|
17
|
+
Never rename or drop a column in a single deployment step. Follow the 5-phase protocol:
|
|
18
|
+
1. **Phase 1 (Expand):** Add the new column as nullable or with a non-locking default.
|
|
19
|
+
2. **Phase 2 (Double-Write):** Deploy application version writing to both old and new columns; reads continue from the old column.
|
|
20
|
+
3. **Phase 3 (Backfill):** Run batched background jobs backfilling historical rows from the old column to the new column in bounded batches (e.g. 500–1000 rows).
|
|
21
|
+
4. **Phase 4 (Switch Read):** Deploy application reading and writing solely to the new column.
|
|
22
|
+
5. **Phase 5 (Contract):** In the subsequent release, drop the old column and legacy constraints from the database.
|
|
23
|
+
|
|
24
|
+
---
|
|
25
|
+
|
|
26
|
+
## 3. Concurrent Non-Blocking Indexing & Constraint Validation
|
|
27
|
+
|
|
28
|
+
- **Concurrent Indexes**: Always construct indexes non-blockingly (`CREATE INDEX CONCURRENTLY` in PostgreSQL, `ALGORITHM=INPLACE, LOCK=NONE` in MySQL) to avoid locking read/write traffic:
|
|
29
|
+
```sql
|
|
30
|
+
CREATE INDEX CONCURRENTLY idx_orders_customer_created
|
|
31
|
+
ON orders (customer_id, created_at DESC);
|
|
32
|
+
```
|
|
33
|
+
- **Two-Phase Constraints**: Attach foreign keys and check constraints without scanning historical rows upfront, then validate asynchronously:
|
|
34
|
+
```sql
|
|
35
|
+
-- Step 1: Attach foreign key without blocking writes
|
|
36
|
+
ALTER TABLE orders ADD CONSTRAINT fk_orders_tenant
|
|
37
|
+
FOREIGN KEY (tenant_id) REFERENCES tenants(id) NOT VALID;
|
|
38
|
+
|
|
39
|
+
-- Step 2: Validate constraint concurrently
|
|
40
|
+
ALTER TABLE orders VALIDATE CONSTRAINT fk_orders_tenant;
|
|
41
|
+
```
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
# Database Operations, PITR & Least-Privilege Roles
|
|
2
|
+
|
|
3
|
+
> **Core Mandate:** Enforce continuous Point-In-Time Recovery (PITR), causal read-after-write routing, non-blocking table maintenance, connection pooling, and least-privilege role separation.
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## 1. High Availability, Backups & Disaster Recovery (DR)
|
|
8
|
+
|
|
9
|
+
- **Continuous Point-In-Time Recovery (PITR)**: Utilize continuous write-ahead logging (WAL) archiving and periodic base backups (**WAL-G**, **pgBackRest**, or engine-native tooling) to guarantee restoration to any specific second.
|
|
10
|
+
- **Causal Read-After-Write Consistency**: Read replicas experience asynchronous replication lag. Immediately following a state-mutating command (`POST`, `PUT`, `DELETE`), pin client sessions to the primary database instance for a bounded window (e.g. 2 seconds) before resuming read-replica routing.
|
|
11
|
+
|
|
12
|
+
---
|
|
13
|
+
|
|
14
|
+
## 2. Table Maintenance & Bloat Defragmentation
|
|
15
|
+
|
|
16
|
+
- **Online Maintenance**: Table and index space must be reclaimed using non-blocking online utilities (**`pg_repack`**, `gh-ost`, or `pt-online-schema-change`), strictly prohibiting locking full table rewrites during online hours.
|
|
17
|
+
- **Background Autovacuum / Optimization**: Configure proactive background vacuuming and compaction thresholds to prevent transaction ID wraparound and table bloat on high-throughput tables.
|
|
18
|
+
|
|
19
|
+
---
|
|
20
|
+
|
|
21
|
+
## 3. Least-Privilege Role Partitioning & Audit Trails
|
|
22
|
+
|
|
23
|
+
Enforce strict separation of database credentials across execution environments:
|
|
24
|
+
- **`migration_deployer`**: DDL privileges (`CREATE`, `ALTER`, `DROP`) restricted to CI/CD automated migration pipelines.
|
|
25
|
+
- **`app_runtime`**: DML privileges only (`SELECT`, `INSERT`, `UPDATE`, `DELETE`) with zero DDL or schema alteration rights.
|
|
26
|
+
- **`analytics_readonly`**: Read-only access to sanitized views and replica nodes.
|
|
27
|
+
- **Tamper-Proof Audit Logging**: Export schema changes, privilege grants, and sensitive queries to immutable external log sinks.
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
# Database Performance & N+1 Prevention
|
|
2
|
+
|
|
3
|
+
> **Core Mandate:** Eliminate N+1 query bottlenecks via explicit relation batching, enforce strict composite indexing, size connection pools scientifically, and terminate runaway queries with statement timeouts.
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## 1. N+1 Query Elimination
|
|
8
|
+
|
|
9
|
+
- **Prohibit Iterative Queries in Loops**: Never query child collections inside iteration loops.
|
|
10
|
+
```
|
|
11
|
+
❌ FORBIDDEN:
|
|
12
|
+
parents = query("SELECT id FROM parent_table")
|
|
13
|
+
for p in parents:
|
|
14
|
+
children = query("SELECT * FROM child_table WHERE parent_id = :id", p.id)
|
|
15
|
+
```
|
|
16
|
+
- **Batching & Eager Fetching**: Always fetch related entities via single `JOIN` statements or batched `IN` clauses (`WHERE parent_id IN (...)`).
|
|
17
|
+
```
|
|
18
|
+
✅ CORRECT:
|
|
19
|
+
parents = query("SELECT id FROM parent_table")
|
|
20
|
+
children = query("SELECT * FROM child_table WHERE parent_id IN (:ids)", parents.map(id))
|
|
21
|
+
```
|
|
22
|
+
- **Universal DataLoader Pattern**: For decentralized domain resolvers or GraphQL pipelines, employ language-native DataLoader ports to batch and deduplicate entity lookups within an execution cycle.
|
|
23
|
+
|
|
24
|
+
---
|
|
25
|
+
|
|
26
|
+
## 2. Multi-Tenant Indexing Strategy
|
|
27
|
+
|
|
28
|
+
- **Tenant-Leading Composite Indexes**:
|
|
29
|
+
Every multi-tenant query pattern must be backed by a composite index where `tenant_id` is the primary leading column:
|
|
30
|
+
```sql
|
|
31
|
+
CREATE INDEX idx_orders_tenant_created ON orders (tenant_id, created_at DESC);
|
|
32
|
+
CREATE UNIQUE INDEX uq_orders_tenant_number ON orders (tenant_id, order_number);
|
|
33
|
+
```
|
|
34
|
+
- **Covering Indexes**:
|
|
35
|
+
Include frequently projected columns in index definitions (`INCLUDE (status, total_amount)` in engines that support index-only scans) to avoid secondary table lookups.
|
|
36
|
+
|
|
37
|
+
---
|
|
38
|
+
|
|
39
|
+
## 3. Connection Pooling & Statement Timeouts
|
|
40
|
+
|
|
41
|
+
- **Scientific Pool Sizing Formula**:
|
|
42
|
+
$$\text{max\_connections} = (\text{CPU Cores} \times 2) + \text{Effective Disk / Spindle Count}$$
|
|
43
|
+
- **Transaction-Scoped Pooling**: Use lightweight connection poolers (e.g. PgBouncer, ProxySQL, or HikariCP) in transaction pooling mode to support thousands of concurrent client connections without memory exhaustion.
|
|
44
|
+
- **Defensive Statement Timeout**: Enforce strict statement timeouts (e.g. 5 seconds) at the connection pool or gateway layer to terminate unindexed runaway queries before they degrade the cluster.
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
# Database Transactions, ACID Atomicity & Outbox Pattern
|
|
2
|
+
|
|
3
|
+
> **Core Mandate:** Enforce full ACID transactional atomicity, appropriate isolation levels, defensive timeouts, deadlock prevention, and eliminate the dual-write problem via the Transactional Outbox pattern.
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## 1. ANSI SQL Transaction Isolation Levels
|
|
8
|
+
|
|
9
|
+
1. **`Read Committed` (Default):** Guarantees statements see only committed data (eliminates dirty reads). Suitable for standard CRUD operations.
|
|
10
|
+
2. **`Repeatable Read` (Snapshot Isolation):** All operations within the transaction see the exact same database snapshot taken at transaction start. Mandatory for multi-entity financial calculations, ledger balance transfers, and inventory decrement operations.
|
|
11
|
+
3. **`Serializable`:** Strict serializability. Prevents phantom reads and write skew. Mandatory for complex booking and seat allocation operations. Requires application-level retry loops with jittered exponential backoff to handle serialization failures.
|
|
12
|
+
|
|
13
|
+
---
|
|
14
|
+
|
|
15
|
+
## 2. Defensive Timeouts & Deadlock Prevention
|
|
16
|
+
|
|
17
|
+
Prevent hung transactions or lock waits from starving database connection pools across any engine:
|
|
18
|
+
|
|
19
|
+
```sql
|
|
20
|
+
SET lock_timeout = '3s'; -- Abort if lock cannot be acquired within 3s
|
|
21
|
+
SET statement_timeout = '10s'; -- Abort queries running longer than 10s
|
|
22
|
+
SET idle_in_transaction_session_timeout = '30s'; -- Abort hung transactions idle for > 30s
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
### Deterministic Lock Ordering
|
|
26
|
+
Always acquire locks on entities in a globally consistent order across application services (e.g. sort resource IDs lexicographically before issuing `SELECT ... FOR UPDATE`) to prevent circular wait deadlocks.
|
|
27
|
+
|
|
28
|
+
---
|
|
29
|
+
|
|
30
|
+
## 3. Abstract Unit of Work & Transaction Boundaries
|
|
31
|
+
|
|
32
|
+
Application services must control transaction boundaries via an abstract **Unit of Work** port, keeping domain logic decoupled from concrete ORMs:
|
|
33
|
+
|
|
34
|
+
```
|
|
35
|
+
┌────────────────────────────────────────────────────────┐
|
|
36
|
+
│ Unit of Work Port Contract (Agnostic Specification) │
|
|
37
|
+
├────────────────────────────────────────────────────────┤
|
|
38
|
+
│ executeTransaction(options, transactionCallback): │
|
|
39
|
+
│ options: │
|
|
40
|
+
│ isolationLevel: READ_COMMITTED | REPEATABLE_READ │
|
|
41
|
+
│ timeoutMs: integer (default 10000) │
|
|
42
|
+
│ maxWaitMs: integer (default 5000) │
|
|
43
|
+
│ behavior: │
|
|
44
|
+
│ 1. Begin transaction on scoped connection │
|
|
45
|
+
│ 2. Execute callback with transactional context │
|
|
46
|
+
│ 3. On error: Rollback and propagate domain error │
|
|
47
|
+
│ 4. On success: Commit atomically │
|
|
48
|
+
└────────────────────────────────────────────────────────┘
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
---
|
|
52
|
+
|
|
53
|
+
## 4. Eliminating Dual-Writes: Transactional Outbox Pattern
|
|
54
|
+
|
|
55
|
+
Never write to the database and publish to a message broker sequentially. Persist the domain mutation and the event record atomically within the same database transaction:
|
|
56
|
+
|
|
57
|
+
```sql
|
|
58
|
+
CREATE TABLE outbox_events (
|
|
59
|
+
id VARCHAR(64) PRIMARY KEY,
|
|
60
|
+
tenant_id VARCHAR(64) NOT NULL,
|
|
61
|
+
aggregate_type VARCHAR(64) NOT NULL,
|
|
62
|
+
aggregate_id VARCHAR(64) NOT NULL,
|
|
63
|
+
event_type VARCHAR(128) NOT NULL,
|
|
64
|
+
payload TEXT NOT NULL,
|
|
65
|
+
status VARCHAR(32) NOT NULL DEFAULT 'PENDING',
|
|
66
|
+
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP
|
|
67
|
+
);
|
|
68
|
+
|
|
69
|
+
CREATE INDEX idx_outbox_pending ON outbox_events(status, created_at);
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
### Asynchronous Outbox Relaying
|
|
73
|
+
- **Change Data Capture (CDC)**: Stream transaction logs directly to Kafka/NATS using tools like **Debezium**.
|
|
74
|
+
- **Polling Worker**: Run background workers executing non-blocking polling:
|
|
75
|
+
```sql
|
|
76
|
+
SELECT * FROM outbox_events
|
|
77
|
+
WHERE status = 'PENDING'
|
|
78
|
+
ORDER BY created_at ASC
|
|
79
|
+
LIMIT 100
|
|
80
|
+
FOR UPDATE SKIP LOCKED;
|
|
81
|
+
```
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
# Modern Design Patterns & Result Pattern
|
|
2
|
+
|
|
3
|
+
> **Core Mandate:** Enforce composition over inheritance, wrap third-party boundaries in project-owned adapters, and model domain errors with explicit Result types instead of untyped exceptions.
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## 1. Structural & Creational Patterns
|
|
8
|
+
|
|
9
|
+
- **Adapter Pattern (Hexagonal Boundary)**: Wrap all external libraries, database drivers, cloud SDKs, and third-party APIs in project-owned adapter interfaces. *Rule: Only mock types you own.*
|
|
10
|
+
- **Factory Method**: Encapsulate complex collaborator instantiation (e.g. tenant-specific payment gateways or notification dispatchers) behind factory functions.
|
|
11
|
+
- **Facade Pattern**: Expose a unified, simplified interface to complex underlying multi-service subsystems.
|
|
12
|
+
- **Decorator / Middleware**: Compose cross-cutting concerns (observability, authentication, tenant context resolution, rate limiting) via middleware pipelines.
|
|
13
|
+
|
|
14
|
+
---
|
|
15
|
+
|
|
16
|
+
## 2. Behavioral Patterns & Explicit Result Types
|
|
17
|
+
|
|
18
|
+
- **Strategy Pattern**: Swap algorithms or execution behavior at runtime without code changes (e.g. tenant-specific pricing algorithms, shipping calculation strategies).
|
|
19
|
+
- **Result / Either Pattern**: Model anticipated domain errors as explicit return values (`Result<T, E>`) rather than throwing untyped exceptions across architectural boundaries:
|
|
20
|
+
|
|
21
|
+
```
|
|
22
|
+
┌────────────────────────────────────────────────────────┐
|
|
23
|
+
│ Universal Result Pattern Semantics │
|
|
24
|
+
├────────────────────────────────────────────────────────┤
|
|
25
|
+
│ Result<T, E> = Ok(T) | Err(E) │
|
|
26
|
+
│ │
|
|
27
|
+
│ Rust: Result<T, DomainError> │
|
|
28
|
+
│ Go: (T, error) │
|
|
29
|
+
│ TypeScript: type Result<T, E> = Ok<T> | Err<E> │
|
|
30
|
+
│ Python: Union[Success[T], Failure[E]] │
|
|
31
|
+
└────────────────────────────────────────────────────────┘
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
Domain services must return explicit Result types, compelling callers to handle failure branches deterministically.
|
|
35
|
+
|
|
36
|
+
---
|
|
37
|
+
|
|
38
|
+
## 3. GoF 23 Patterns Catalog
|
|
39
|
+
|
|
40
|
+
For reference implementations of all 23 Gang of Four patterns across OOP and functional paradigms, consult [docs/rules/gof_design_patterns_reference.md](./gof_design_patterns_reference.md).
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
# DevSecOps, Secret Scanning & SBOM Standards
|
|
2
|
+
|
|
3
|
+
> **Core Mandate:** Enforce automated pre-commit secret gating, CycloneDX SBOM generation, polyglot SAST via Semgrep, and container/lockfile scanning with Trivy.
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## 1. Automated Pre-Commit Secret Gating
|
|
8
|
+
|
|
9
|
+
- Run open-source secret scanning (**`gitleaks`** or **`secretlint`**) on every staged commit via pre-commit hooks.
|
|
10
|
+
- Never bypass git commit hooks (`--no-verify`). Strictly forbid committing credentials, private keys, certificates, or API tokens to version control.
|
|
11
|
+
|
|
12
|
+
---
|
|
13
|
+
|
|
14
|
+
## 2. Software Bill of Materials (SBOM) Generation
|
|
15
|
+
|
|
16
|
+
- Generate reproducible **CycloneDX 1.6** or **SPDX** SBOMs for all build artifacts using open-source **`syft`**:
|
|
17
|
+
```bash
|
|
18
|
+
syft dir:. -o cyclonedx-json=sbom.json
|
|
19
|
+
```
|
|
20
|
+
- Archive the generated `sbom.json` alongside release binaries and container registries.
|
|
21
|
+
- Sign release artifacts and container images cryptographically using **Cosign** (Sigstore) with SLSA provenance attestation.
|
|
22
|
+
|
|
23
|
+
---
|
|
24
|
+
|
|
25
|
+
## 3. Polyglot SAST & Vulnerability Scanning
|
|
26
|
+
|
|
27
|
+
- **Static Analysis (SAST)**: Standardize on **Semgrep** for cross-language security and quality linting across Go, Rust, Python, Java, and TypeScript.
|
|
28
|
+
- **Dependency & Container CVE Scanning**: Scan lockfiles (`go.mod`, `Cargo.lock`, `package-lock.json`, `poetry.lock`, `pom.xml`) and OCI container base images using open-source **`trivy`** and **`grype`**:
|
|
29
|
+
```bash
|
|
30
|
+
trivy fs --severity HIGH,CRITICAL .
|
|
31
|
+
grype sbom:sbom.json
|
|
32
|
+
```
|
|
33
|
+
- Any unpatched `HIGH` or `CRITICAL` Common Vulnerabilities and Exposures (CVE) halts the continuous integration pipeline immediately.
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
# Domain-Driven Design (DDD) & Ubiquitous Language
|
|
2
|
+
|
|
3
|
+
> **Core Mandate:** Establish unambiguous Ubiquitous Language definitions, isolate Bounded Contexts, guarantee Domain-Code Language Agreement across all architectural layers, and separate Value Objects, Entities, and Aggregates.
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## 1. Domain-Code Language Agreement
|
|
8
|
+
|
|
9
|
+
The fundamental premise of Domain-Driven Design (Eric Evans) is that **the code is the model, and the model is the code**. Any divergence between the mental model of domain experts and the source code is called **Linguistic Drift**.
|
|
10
|
+
|
|
11
|
+
### Principles of Linguistic Alignment
|
|
12
|
+
1. **Zero Synonyms (The Single Name Rule)**: Every domain concept has exactly one authoritative term. Synonyms (e.g. `Client` vs `User`, `Account` vs `Organization`, `Contract` vs `Agreement`) are strictly forbidden across code, tests, and user interfaces.
|
|
13
|
+
2. **Eliminate Technical Jargon from Domain Core**: Domain models must not leak technical implementation terms (e.g. `UserRecord`, `TenantRow`, `DataDTO`, `IsActiveFlag`). The domain language must be pure business vocabulary.
|
|
14
|
+
3. **Contextual Isolation**: When a single English word has multiple meanings across business units, split the terms or isolate them within dedicated Bounded Contexts:
|
|
15
|
+
- *Example*: In multi-tenant infrastructure, a system isolation boundary is an **Organization** / **Tenant Workspace**. In application operations, a participant is a **Member**, **User**, or **Customer**. Using "Tenant" for both creates semantic ambiguity and catastrophic bugs.
|
|
16
|
+
|
|
17
|
+
---
|
|
18
|
+
|
|
19
|
+
## 2. Living Ubiquitous Language Glossary
|
|
20
|
+
|
|
21
|
+
Every project must maintain an authoritative, version-controlled **Living Ubiquitous Language Glossary** at [`docs/knowledge/ubiquitous_language.md`](../knowledge/ubiquitous_language.md).
|
|
22
|
+
|
|
23
|
+
### Structure of a Glossary Entry
|
|
24
|
+
Each entry must define:
|
|
25
|
+
- **Canonical Term**: The agreed domain name.
|
|
26
|
+
- **Definition**: The business meaning agreed with stakeholders.
|
|
27
|
+
- **Bounded Context**: The domain subsystem where this definition holds authority.
|
|
28
|
+
- **Forbidden Synonyms**: Banned terms that must never appear in code, schemas, or UI.
|
|
29
|
+
- **Code Representations**: Exact class, type, interface, and database table names.
|
|
30
|
+
|
|
31
|
+
---
|
|
32
|
+
|
|
33
|
+
## 3. Automated Enforcement & Linters
|
|
34
|
+
|
|
35
|
+
To prevent linguistic drift over time, teams must employ mechanical enforcement:
|
|
36
|
+
|
|
37
|
+
### 1. Static Analysis / Linter Rules
|
|
38
|
+
Configure custom linter rules (e.g. ESLint `id-denylist` or custom AST rules) to forbid banned synonyms in identifiers:
|
|
39
|
+
```json
|
|
40
|
+
{
|
|
41
|
+
"rules": {
|
|
42
|
+
"id-denylist": ["error", "client_user", "account_org", "raw_data_dto"]
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
### 2. Branded Nominal Types
|
|
48
|
+
Prevent "Primitive Obsession" where generic strings or IDs are conflated across domain boundaries:
|
|
49
|
+
```typescript
|
|
50
|
+
export type UserId = string & { readonly __brand: unique symbol };
|
|
51
|
+
export type OrganizationId = string & { readonly __brand: unique symbol };
|
|
52
|
+
export type OrderId = string & { readonly __brand: unique symbol };
|
|
53
|
+
|
|
54
|
+
// The compiler prevents accidentally passing an OrganizationId where a UserId is required:
|
|
55
|
+
function assignUserToOrder(orderId: OrderId, userId: UserId): void { ... }
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
### 3. Living Executable Specifications (Gherkin BDD)
|
|
59
|
+
Acceptance criteria must be written strictly in Ubiquitous Language, serving as executable contracts that verify domain terminology in automated test runners.
|
|
60
|
+
|
|
61
|
+
---
|
|
62
|
+
|
|
63
|
+
## 4. Tactical Patterns & Invariants
|
|
64
|
+
|
|
65
|
+
1. **Entities**: Objects defined by identity that persists across state changes (e.g. `User`, `Order`, `Invoice`).
|
|
66
|
+
2. **Value Objects**: Immutable objects defined strictly by their attributes with no identity (e.g. `Money`, `DateRange`, `EmailAddress`).
|
|
67
|
+
3. **Aggregates & Aggregate Roots**: Clusters of domain objects treated as a single transactional consistency boundary. All mutations must pass through explicit methods on the Aggregate Root.
|
|
68
|
+
4. **Anti-Corruption Layer (ACL)**: When integrating with third-party APIs or legacy systems that use different terminology, translate external payloads into the internal Ubiquitous Language at the boundary adapter before they enter the domain core.
|
|
69
|
+
|
|
70
|
+
---
|
|
71
|
+
|
|
72
|
+
## 5. Invariants (DO's & DONT's)
|
|
73
|
+
|
|
74
|
+
### DO
|
|
75
|
+
- **DO** use identical terminology in domain conversations, PRDs, code, database schemas, and user interfaces.
|
|
76
|
+
- **DO** maintain an authoritative `ubiquitous_language.md` and treat it as a binding architectural contract.
|
|
77
|
+
- **DO** use branded nominal types for IDs to catch cross-entity domain mixups at compile time.
|
|
78
|
+
- **DO** translate foreign data structures at the perimeter using an Anti-Corruption Layer (ACL).
|
|
79
|
+
|
|
80
|
+
### DONT
|
|
81
|
+
- **DONT** use technical jargon (`dto`, `entity_row`, `table_item`) in domain business logic.
|
|
82
|
+
- **DONT** allow competing synonyms for the same concept within the same Bounded Context.
|
|
83
|
+
- **DONT** overload words with dual meanings across technical architecture and business domain.
|
|
84
|
+
- **DONT** rename domain terms in code without updating the living glossary and recording an ADR.
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
# Domain Expertise, Capability Mapping & Business Invariants
|
|
2
|
+
|
|
3
|
+
> **Core Mandate:** Decompose business domains into distinct capability boundaries, enforce business invariants strictly within Aggregate Roots, and protect living Ubiquitous Language.
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## 1. Business Capability Mapping
|
|
8
|
+
|
|
9
|
+
Structure enterprise business logic into three distinct capability tiers:
|
|
10
|
+
1. **Core Capabilities**: Proprietary value drivers and differentiators (e.g. specialized tenant workflow engines, dynamic pricing algorithms). Allocate 80% of architectural effort here.
|
|
11
|
+
2. **Supporting Capabilities**: Business functions specific to the domain but not competitive differentiators (e.g. order tracking, invoice rendering).
|
|
12
|
+
3. **Generic Capabilities**: Standard commoditized software (e.g. authentication, audit logging, email transport). Rely exclusively on standard open-source libraries.
|
|
13
|
+
|
|
14
|
+
---
|
|
15
|
+
|
|
16
|
+
## 2. Invariant Protection within Aggregate Roots
|
|
17
|
+
|
|
18
|
+
- **Zero Anemic Domain Models**: Domain entities must encapsulate state and validation. Do not expose public setters that allow outside code to corrupt business rules.
|
|
19
|
+
- **Aggregate Root Gatekeeper**: All mutations that modify entity state or related child entities must pass through explicit methods on the Aggregate Root that assert invariants before committing state:
|
|
20
|
+
```typescript
|
|
21
|
+
export class OrderAggregate {
|
|
22
|
+
private constructor(private order: OrderState) {}
|
|
23
|
+
|
|
24
|
+
submit(): Result<void, DomainError> {
|
|
25
|
+
if (this.order.items.length === 0) {
|
|
26
|
+
return err(new DomainError('Cannot submit empty order'));
|
|
27
|
+
}
|
|
28
|
+
if (this.order.status !== 'DRAFT') {
|
|
29
|
+
return err(new DomainError('Order already submitted'));
|
|
30
|
+
}
|
|
31
|
+
this.order.status = 'SUBMITTED';
|
|
32
|
+
return ok(undefined);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
---
|
|
38
|
+
|
|
39
|
+
## 3. Living Ubiquitous Language Dictionary
|
|
40
|
+
|
|
41
|
+
- Maintain strict terminology discipline across models, database tables, API schemas, and frontend labels.
|
|
42
|
+
- When domain experts or users establish a term, document it immediately and eliminate all competing synonyms across the codebase.
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
# Error Handling, Request Tracing & Schema Validation
|
|
2
|
+
|
|
3
|
+
> **Core Mandate:** Enforce fail-fast schema validation at startup, structured OpenTelemetry/JSON request tracing, and standardized RFC 7807 / REST error envelopes.
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## 1. Fail-Fast Configuration & Environment Validation
|
|
8
|
+
|
|
9
|
+
Validate all configuration parameters and environment variables at process bootstrap using strict schema definitions before initializing servers or database connection pools:
|
|
10
|
+
- **Immediate Process Termination**: Halt startup immediately with non-zero exit code if any mandatory variable is missing, malformed, or insecure.
|
|
11
|
+
- **Strict Prohibition of Secret Fallbacks**: Never provide default fallback values for production secrets, database credentials, or private cryptographic keys.
|
|
12
|
+
|
|
13
|
+
---
|
|
14
|
+
|
|
15
|
+
## 2. Structured Tracing & Correlation (OpenTelemetry / W3C)
|
|
16
|
+
|
|
17
|
+
- **Standardized Correlation IDs**: Bind a unique `x-request-id` (UUID v4) and W3C `traceparent` to every inbound request. Forward these identifiers across all downstream RPC calls, database queries, and async broker messages.
|
|
18
|
+
- **Structured JSON Logging**: Format all application logs in structured JSON conforming to OpenTelemetry Resource Schemas or Elastic Common Schema (ECS) (`timestamp`, `severity`, `trace_id`, `span_id`, `request_id`, `tenant_id`, `message`).
|
|
19
|
+
|
|
20
|
+
---
|
|
21
|
+
|
|
22
|
+
## 3. Standardized Error Response Envelope (RFC 7807)
|
|
23
|
+
|
|
24
|
+
Enforce a uniform error envelope across all external HTTP/REST endpoints conforming to the **RFC 7807 Problem Details** standard:
|
|
25
|
+
|
|
26
|
+
```json
|
|
27
|
+
{
|
|
28
|
+
"type": "https://api.domain.com/errors/RESOURCE_LOCKED",
|
|
29
|
+
"title": "Resource Conflict",
|
|
30
|
+
"status": 409,
|
|
31
|
+
"detail": "The requested order is currently undergoing payment processing.",
|
|
32
|
+
"instance": "/v1/orders/123",
|
|
33
|
+
"code": "ORDER_LOCKED",
|
|
34
|
+
"requestId": "550e8400-e29b-41d4-a716-446655440000",
|
|
35
|
+
"invalidParams": []
|
|
36
|
+
}
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
- **Production Masking Invariant**: Strictly mask internal database error codes, raw SQL queries, file system paths, and stack traces from external client responses in non-local environments.
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
# Feature Flagging & OpenFeature Standards
|
|
2
|
+
|
|
3
|
+
> **Core Mandate:** Enforce the open-source OpenFeature standard, evaluate flags dynamically via Flipt or Unleash backends, and maintain clean flag lifecycles.
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## 1. OpenFeature Standard Architecture
|
|
8
|
+
|
|
9
|
+
Utilize open-source `@openfeature/server-sdk` with open-source providers (Flipt or Unleash):
|
|
10
|
+
|
|
11
|
+
```typescript
|
|
12
|
+
import { OpenFeature, Client } from '@openfeature/server-sdk';
|
|
13
|
+
import { FliptProvider } from '@openfeature/flipt-provider';
|
|
14
|
+
|
|
15
|
+
OpenFeature.setProvider(new FliptProvider({ url: process.env.FLIPT_URL }));
|
|
16
|
+
export const featureClient: Client = OpenFeature.getClient();
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
---
|
|
20
|
+
|
|
21
|
+
## 2. Contextual Tenant Targeting
|
|
22
|
+
|
|
23
|
+
Pass tenant identity and contextual attributes during evaluation:
|
|
24
|
+
|
|
25
|
+
```typescript
|
|
26
|
+
const isEnabled = await featureClient.getBooleanValue(
|
|
27
|
+
'advanced-analytics',
|
|
28
|
+
false,
|
|
29
|
+
{
|
|
30
|
+
targetingKey: user.id,
|
|
31
|
+
tenantId: user.tenantId,
|
|
32
|
+
tier: tenant.subscriptionTier
|
|
33
|
+
}
|
|
34
|
+
);
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
---
|
|
38
|
+
|
|
39
|
+
## 3. Flag Lifecycle Governance
|
|
40
|
+
|
|
41
|
+
- **Emergency Kill Switches**: Every high-risk feature or third-party integration must be wrapped in a flag that can immediately disable functionality without code redeployment.
|
|
42
|
+
- **Retirement Mandate**: When a feature is 100% rolled out for > 30 days, author a task to purge the flag and its dead code branches.
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
# Gang of Four (GoF) Design Patterns — Universal Enterprise Reference
|
|
2
|
+
|
|
3
|
+
> **Core Mandate:** Master catalog of all 23 Gang of Four design patterns mapped to real-world domain architectures across OOP and functional polyglot systems.
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## 1. Creational Patterns (5 Patterns)
|
|
8
|
+
|
|
9
|
+
Creational patterns abstract the instantiation process, making systems independent of how objects are created and composed.
|
|
10
|
+
|
|
11
|
+
1. **Factory Method**: Define an interface for creating an object, but let subclasses or factory functions decide which class to instantiate.
|
|
12
|
+
- *Use Case:* Tenant-specific payment gateway instantiation (`StripeAdapter` vs `PayPalAdapter`).
|
|
13
|
+
2. **Abstract Factory**: Provide an interface for creating families of related or dependent objects without specifying concrete classes.
|
|
14
|
+
- *Use Case:* Multi-cloud storage factories creating matching `FileUploader`, `FileDownloader`, and `PresignedUrlGenerator` for S3, GCS, or MinIO.
|
|
15
|
+
3. **Builder**: Separate the construction of a complex object from its representation, allowing the same construction process to create different representations.
|
|
16
|
+
- *Use Case:* Fluent query builders, complex report generators, or test data builders (`OrderBuilder.withItems(...).build()`).
|
|
17
|
+
4. **Prototype**: Specify the kinds of objects to create using a prototypical instance, creating new objects by cloning this prototype.
|
|
18
|
+
- *Use Case:* Fast cloning of default tenant configuration templates without querying storage.
|
|
19
|
+
5. **Singleton (DI-Scoped)**: Ensure a class has only one instance and provide a global point of access.
|
|
20
|
+
- *Rule:* Avoid global static singletons (causes test coupling). Enforce singleton lifecycle strictly through Dependency Injection (DI) containers.
|
|
21
|
+
|
|
22
|
+
---
|
|
23
|
+
|
|
24
|
+
## 2. Structural Patterns (7 Patterns)
|
|
25
|
+
|
|
26
|
+
Structural patterns deal with object composition and relationships, ensuring subsystems remain decoupled and flexible.
|
|
27
|
+
|
|
28
|
+
6. **Adapter (Mandatory)**: Convert the interface of a class into another interface clients expect.
|
|
29
|
+
- *Use Case:* Wrapping 3rd-party SDKs, storage drivers, and external network clients in application-owned interfaces. *Rule: Only mock types you own.*
|
|
30
|
+
7. **Bridge**: Decouple an abstraction from its implementation so the two can vary independently.
|
|
31
|
+
- *Use Case:* Decoupling notification abstractions (`UrgentNotification`, `BatchNotification`) from delivery channels (`EmailChannel`, `SlackChannel`).
|
|
32
|
+
8. **Composite**: Compose objects into tree structures to represent part-whole hierarchies.
|
|
33
|
+
- *Use Case:* Nested RBAC permission trees or hierarchical menu navigation systems.
|
|
34
|
+
9. **Decorator**: Attach additional responsibilities to an object dynamically as a flexible alternative to subclassing.
|
|
35
|
+
- *Use Case:* Wrapping repository methods with distributed caching, OpenTelemetry tracing, or metrics logging.
|
|
36
|
+
10. **Facade**: Provide a unified, high-level interface to a complex set of interfaces in a subsystem.
|
|
37
|
+
- *Use Case:* Checkout facade orchestrating inventory verification, payment processing, invoice generation, and email notification.
|
|
38
|
+
11. **Flyweight**: Use sharing to support large numbers of fine-grained objects efficiently.
|
|
39
|
+
- *Use Case:* In-memory sharing of immutable tenant metadata and shared system role permission definitions.
|
|
40
|
+
12. **Proxy**: Provide a surrogate or placeholder for another object to control access to it.
|
|
41
|
+
- *Use Case:* Lazy-loading database relations, virtual proxies for large assets, or tenant-scoped connection proxies.
|
|
42
|
+
|
|
43
|
+
---
|
|
44
|
+
|
|
45
|
+
## 3. Behavioral Patterns (11 Patterns)
|
|
46
|
+
|
|
47
|
+
Behavioral patterns characterize the ways in which classes or objects interact and distribute responsibility.
|
|
48
|
+
|
|
49
|
+
13. **Chain of Responsibility**: Pass requests along a chain of handlers until a handler processes it or the chain ends.
|
|
50
|
+
- *Use Case:* Inbound gateway middleware pipelines (Authentication ➔ TenantResolution ➔ RateLimiting ➔ Controller).
|
|
51
|
+
14. **Command**: Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undo.
|
|
52
|
+
- *Use Case:* Asynchronous job queues, transactional audit commands, CQRS command handlers.
|
|
53
|
+
15. **Interpreter**: Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences.
|
|
54
|
+
- *Use Case:* Custom search filter parsers (`status:active AND tier:pro`) or rule engine expression evaluation.
|
|
55
|
+
16. **Iterator**: Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.
|
|
56
|
+
- *Use Case:* Async iterators streaming large database cursor result sets or reading multi-part upload chunks.
|
|
57
|
+
17. **Mediator**: Define an object that encapsulates how a set of objects interact, preventing direct coupling between them.
|
|
58
|
+
- *Use Case:* In-memory event dispatcher mediating communication between decoupled domain services.
|
|
59
|
+
18. **Memento**: Without violating encapsulation, capture and externalize an object's internal state so the object can be restored to this state later.
|
|
60
|
+
- *Use Case:* Audit trail snapshots recording `before` and `after` states for rollback capabilities.
|
|
61
|
+
19. **Observer**: Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified automatically.
|
|
62
|
+
- *Use Case:* Domain Event buses (`UserRegisteredEvent`, `PaymentFailedEvent`) invoking multiple listeners.
|
|
63
|
+
20. **State**: Allow an object to alter its behavior when its internal state changes, appearing as if it changed its class.
|
|
64
|
+
- *Use Case:* Subscription lifecycles (`TrialState` ➔ `ActiveState` ➔ `PastDueState` ➔ `CanceledState`) where allowed actions change dynamically.
|
|
65
|
+
21. **Strategy**: Define a family of algorithms, encapsulate each one, and make them interchangeable at runtime.
|
|
66
|
+
- *Use Case:* Dynamic fee calculation, tenant-specific password complexity policies, or feature flag evaluation providers.
|
|
67
|
+
22. **Template Method**: Define the skeleton of an algorithm in an operation, deferring some steps to subclasses.
|
|
68
|
+
- *Use Case:* Base ETL or data import pipelines with fixed steps (Extract ➔ Validate ➔ Transform ➔ Persist) where subclasses define validation.
|
|
69
|
+
23. **Visitor**: Represent an operation to be performed on the elements of an object structure, defining a new operation without changing the classes of the elements.
|
|
70
|
+
- *Use Case:* Document export engines traversing an AST of content blocks to generate HTML, Markdown, or PDF.
|