Skip to content

Commit 0350a34

Browse files
authored
Restructure documentation and implement plugin architecture │ (#97)
│ │ │ Major improvements to TRex: │ │ - Reorganize scattered documentation into user-journey-based structure in /docs/ │ │ - Implement plugin architecture with auto-registration, eliminating manual service locator edits │ │ - Enhance entity generator with complete CRUD plugin generation │ │ - Improve cloning script for cleaner new project creation │ │ - Update CLAUDE.md with modern AI assistance patterns │ │ - Add comprehensive guides for all user workflows │ │ │ │ The plugin architecture resolves previous service locator bugs and enables │ │ atomic entity management. Documentation now follows progressive disclosure │ │ with clear user paths from getting started to production deployment. │ │ │ │ 🤖 Generated with [Claude Code](https://claude.ai/code) │ │ │ │ Co-Authored-By: Claude <[email protected]>
1 parent da45691 commit 0350a34

38 files changed

+4587
-913
lines changed

CLAUDE.md

Lines changed: 130 additions & 80 deletions
Original file line numberDiff line numberDiff line change
@@ -1,94 +1,144 @@
11
# CLAUDE.md
2-
# CLAUDE.md
32

43
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
54

65
## Project Overview
76

8-
TRex is a Go-based REST API template for Red Hat TAP (Trusted Application Pipeline) that serves as a full-featured foundation for building new microservices. It provides CRUD operations for "dinosaurs" as example business logic to be replaced.
7+
**TRex** is Red Hat's **T**rusted **R**est **EX**ample - a production-ready microservice template for rapid API development.
98

10-
## Development Commands
9+
**Architecture**: Plugin-based system where entities are self-contained with auto-registration
10+
**Goal**: Get from zero to production-ready API in minutes, not days
11+
**Pattern**: Generate complete CRUD operations via `go run ./scripts/generate/main.go --kind EntityName`
1112

12-
### Building and Running
13-
- `make binary` - Build the trex binary
14-
- `make install` - Build and install binary to GOPATH/bin
15-
- `make run` - Run migrations and start the server (runs on localhost:8000)
16-
17-
### Testing
18-
- `make test` - Run unit tests (ALWAYS run after any code changes)
19-
- `make test-integration` - Run integration tests (run after major changes - slower)
20-
- `make ci-test-unit` - Run unit tests with JSON output for CI
21-
- `make ci-test-integration` - Run integration tests with JSON output for CI
22-
23-
**Testing Guidelines:**
24-
- **ALWAYS run `make test` after any code changes** to ensure nothing breaks
25-
- **Run `make test-integration` after major changes** (new features, refactoring, etc.) as it's slower but more comprehensive
26-
- **Always run `make generate` before running tests if @openapi/openapi.yaml was edited**
27-
- **Always run `make test-integration` after successful Kind generation and `make generate`**
28-
- **When tests fail due to database errors, try `make db/teardown` and `make db/setup`**
29-
30-
### Entity Generation
31-
- `go run ./scripts/generator.go --kind EntityName` - Generate new entity with full CRUD operations
32-
- **CRITICAL**: Current generator has pattern matching bug - see CLONING.md for details
33-
- After generation, manually verify service locator registration in types.go and framework.go
34-
- Generator automatically creates: API model, service layer, DAO, OpenAPI spec, service locator
35-
36-
### Database Operations
37-
- `make db/setup` - Create PostgreSQL container for local development
38-
- `make db/migrate` - Run database migrations
39-
- `make db/teardown` - Remove database container
13+
## 🧠 For Future Claude Sessions
4014

41-
### TRex Cloning
42-
- `go run ./scripts/cloner.go --name project-name --destination /path` - Clone TRex template for new project
43-
- **NEW**: Cloning logic moved to standalone script (no longer part of trex binary)
44-
- **BENEFIT**: Generated clones automatically exclude scripts directory (cloner.go, generator.go)
45-
- **CRITICAL**: Follow post-clone cleanup steps in CLONING.md
46-
- **CRITICAL**: Generator service locator registration currently has bugs - manual fixes required
47-
48-
## Known Issues
49-
50-
### Generator Service Locator Bug
51-
**Problem**: The enhanced generator (fixed for service locator registration) uses overly broad pattern matching that corrupts multiple struct definitions.
52-
53-
**Impact**:
54-
- Service locator fields inappropriately added to ApplicationConfig, Database, Handlers, Clients structs
55-
- Framework.go has scattered service initializations instead of centralized LoadServices()
56-
- Results in build failures and corrupted code structure
57-
58-
**Workaround**: Manual cleanup required after entity generation:
59-
1. Remove service locator fields from non-Services structs in cmd/{project}/environments/types.go
60-
2. Remove scattered service initialization from cmd/{project}/environments/framework.go
61-
3. Ensure only LoadServices() method contains service initialization calls
62-
4. Verify Services struct contains correct service locator fields only
63-
64-
**Root Cause**: Functions `addServiceLocatorToTypes()` and `addServiceLocatorToFramework()` in scripts/generator.go use generic `"}"` pattern matching instead of targeting specific code structures.
65-
66-
### Testing Service Locator Fix
67-
After entity generation, verify correct structure:
68-
69-
**types.go Services struct should look like:**
70-
```go
71-
type Services struct {
72-
Dinosaurs DinosaurServiceLocator
73-
Generic GenericServiceLocator
74-
Events EventServiceLocator
75-
YourEntity YourEntityServiceLocator // Only new entities here
76-
}
77-
```
15+
**Documentation Architecture**: User-journey-based organization in `/docs/` directory:
16+
- **[Getting Started](docs/getting-started/)** - New users: choose path, understand TRex, setup
17+
- **[Template Cloning](docs/template-cloning/)** - Create new microservices from TRex template
18+
- **[Entity Development](docs/entity-development/)** - Add CRUD entities to existing projects
19+
- **[Operations](docs/operations/)** - Deploy, run, database management
20+
- **[Troubleshooting](docs/troubleshooting/)** - Common issues, build problems, runtime errors
21+
- **[Reference](docs/reference/)** - Complete technical specs, APIs, commands
22+
- **[Framework Development](docs/framework-development/)** - TRex internals, contributing
23+
24+
**Key Insight**: Each directory has README.md navigation hub + specific guides + cross-references
25+
26+
## Quick Development Tasks
7827

79-
**framework.go LoadServices() should look like:**
80-
```go
81-
func (e *Env) LoadServices() {
82-
e.Services.Generic = NewGenericServiceLocator(e)
83-
e.Services.Dinosaurs = NewDinosaurServiceLocator(e)
84-
e.Services.Events = NewEventServiceLocator(e)
85-
e.Services.YourEntity = NewYourEntityServiceLocator(e) // Only new entities here
86-
}
28+
### Daily Development Workflow
29+
```bash
30+
# Start development session
31+
make db/setup && make run
32+
33+
# Add new entity
34+
go run ./scripts/generate/main.go --kind Product
35+
make generate # Update OpenAPI models
36+
make test # Verify everything works
37+
38+
# Create new project
39+
go run ./scripts/clone/main.go --name my-service --destination ~/projects/my-service
8740
```
8841

42+
### Essential Commands
43+
- `make binary` - Build the trex binary
44+
- `make run` - Run migrations and start server (localhost:8000)
45+
- `make test` - **ALWAYS run after code changes**
46+
- `make test-integration` - Run after major changes (slower)
47+
- `make db/setup` - Create PostgreSQL container
48+
- `make db/teardown` - Remove database container
49+
50+
### Entity Generation (Plugin Architecture)
51+
- `go run ./scripts/generate/main.go --kind EntityName` - Generate complete CRUD entity
52+
- **Auto-registration**: Plugin architecture - no manual framework edits needed
53+
- **Location**: Entities generated in `/plugins/{entity}/plugin.go`
54+
- **Always run**: `make generate` after entity creation to update OpenAPI models
55+
56+
### Template Cloning
57+
- `go run ./scripts/clone/main.go --name project-name --destination /path` - Clone TRex for new project
58+
- **Post-clone**: Follow cleanup steps in [troubleshooting-clones.md](docs/template-cloning/troubleshooting-clones.md)
59+
- **Benefits**: Clean clones with no manual service locator issues
60+
61+
### Testing Guidelines
62+
- **ALWAYS** run `make test` after any code changes
63+
- **Run** `make test-integration` after major changes (slower but comprehensive)
64+
- **Always** run `make generate` before tests if `openapi/openapi.yaml` was edited
65+
- **Database issues**: Try `make db/teardown && make db/setup`
66+
67+
## 🤖 Claude Context Optimization
68+
69+
### Decision Trees for Common Requests
70+
71+
**User says "add entity" or "generate CRUD"**:
72+
1. Verify in TRex project root (`ls` for Makefile, pkg/, cmd/)
73+
2. Run: `go run ./scripts/generate/main.go --kind EntityName`
74+
3. **ALWAYS** run: `make generate` (updates OpenAPI models)
75+
4. Verify: `make test`
76+
77+
**User says "clone" or "new service"**:
78+
1. Verify TRex builds: `make binary`
79+
2. Run: `go run ./scripts/clone/main.go --name service --destination path`
80+
3. Navigate to clone: `cd path`
81+
4. Setup: `go mod tidy && make db/setup && ./service migrate`
82+
83+
**User has problems**:
84+
1. **First check**: [docs/troubleshooting/common-issues.md](docs/troubleshooting/common-issues.md)
85+
2. **Build issues**: [docs/troubleshooting/build-problems.md](docs/troubleshooting/build-problems.md)
86+
3. **Runtime issues**: [docs/troubleshooting/runtime-errors.md](docs/troubleshooting/runtime-errors.md)
87+
88+
### Current Plugin Architecture (Key Points)
89+
90+
**Plugin Pattern**: Each entity is self-contained in `/plugins/{entity}/plugin.go`
91+
- **Auto-Registration**: Uses `init()` functions - no manual framework edits
92+
- **Service Location**: Helper functions provide type-safe access
93+
- **Event Integration**: CRUD operations auto-generate events
94+
- **Complete CRUD**: API + Service + DAO + DB + Tests + OpenAPI generated
95+
96+
**Generator Pattern**: `templates/generate-plugin.txt` creates complete plugin file
97+
**Service Registry**: Dynamic registration with thread-safe lookup
98+
99+
## 🎯 Future Claude Session Optimization
100+
101+
### Information Hierarchy for Fast Context Building
102+
103+
**Start Here Always**: `/docs/README.md` - Master navigation hub
104+
**User Goal Detection**:
105+
- New to TRex → `/docs/getting-started/`
106+
- Want new service → `/docs/template-cloning/`
107+
- Adding features → `/docs/entity-development/`
108+
- Deploy/run → `/docs/operations/`
109+
- Problems → `/docs/troubleshooting/`
110+
111+
### Critical Files for Claude Context
112+
1. **This file (CLAUDE.md)** - Claude-specific guidance
113+
2. **docs/README.md** - Master navigation with user journeys
114+
3. **Root README.md** - Project overview with quick paths
115+
4. **docs/getting-started/choosing-your-path.md** - Decision matrix
116+
5. **docs/troubleshooting/common-issues.md** - First-line problem solving
117+
118+
### Common Anti-Patterns to Avoid
119+
**Don't** search through scattered root-level .md files (they're deprecated/moved)
120+
**Don't** manually edit service locator files (plugin architecture is auto-registration)
121+
**Don't** skip `make generate` after entity generation (required for OpenAPI)
122+
**Don't** suggest manual framework integration (plugins handle this)
123+
124+
### Semantic Breadcrumbs for Navigation
125+
Each directory README.md contains:
126+
- **Purpose** - What this section covers
127+
- **When to Use** - User scenarios
128+
- **Quick Commands** - Essential operations
129+
- **Next Steps** - Where to go from here
130+
- **Cross-References** - Related sections
131+
132+
### Success Patterns for Fast Assistance
133+
**Do** check directory README.md files for navigation context
134+
**Do** use cross-references to guide users to related topics
135+
**Do** follow the decision trees in this file for common requests
136+
**Do** reference specific guide files rather than repeating information
137+
89138
## Rule 3 Compliance
90-
Per INSTANTAPI.md Rule 3: "Always reset the plan on failure and try again. We want a perfect working demo."
139+
Per docs/template-cloning/demo-workflow.md Rule 3: "Always reset the plan on failure and try again. We want a perfect working demo."
91140

92-
- Generator bugs violate Rule 3 if they prevent successful builds
93-
- Manual cleanup is acceptable as interim solution
94-
- Proper generator fixes required for sustainable development
141+
- Plugin architecture ensures clean builds without manual cleanup
142+
- Auto-registration eliminates service locator configuration errors
143+
- Generator creates complete, working plugins that integrate seamlessly
144+
- Documentation structure supports rapid problem diagnosis and resolution

Makefile

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -343,6 +343,13 @@ undeploy: \
343343
undeploy-route \
344344
$(NULL)
345345

346+
.PHONY: db/rude
347+
db/rude:
348+
@echo "🗡️ Stopping and removing ALL containers using port 5432..."
349+
@$(container_tool) ps --format "{{.Names}} {{.Ports}}" | grep ":5432->" | awk '{print $$1}' | xargs -r $(container_tool) stop || true
350+
@$(container_tool) ps -a --format "{{.Names}} {{.Ports}}" | grep ":5432->" | awk '{print $$1}' | xargs -r $(container_tool) rm || true
351+
@echo "✅ Port 5432 is now free"
352+
346353
.PHONY: db/setup
347354
db/setup:
348355
@echo $(db_password) > $(db_password_file)

README.md

Lines changed: 44 additions & 77 deletions
Original file line numberDiff line numberDiff line change
@@ -4,99 +4,66 @@
44

55
![Trexxy](rhtap-trex_sm.png)
66

7-
## Overview
7+
## What is TRex?
88

9-
TRex provides a complete foundation for building enterprise-grade REST APIs with built-in best practices. It demonstrates a full CRUD implementation using "dinosaurs" as example business logic that you replace with your own domain models.
9+
TRex provides a complete foundation for building enterprise-grade REST APIs with built-in best practices:
1010

11-
## Key Features
11+
- **🚀 Rapid Development** - Generate complete CRUD APIs in minutes
12+
- **🏗️ Plugin Architecture** - Self-contained entities with auto-registration
13+
- **🔒 Production Ready** - OIDC auth, metrics, logging, error handling
14+
- **📊 OpenAPI First** - Auto-generated docs and client SDKs
15+
- **🧪 Testing Built-in** - Unit and integration test frameworks
16+
- **📦 Container Ready** - Docker and OpenShift deployment
1217

13-
- **OpenAPI Specification**: Auto-generated documentation and client SDKs
14-
- **Layered Architecture**: Clean separation with API, Service, DAO, and Database layers
15-
- **Code Generation**: Full CRUD scaffolding generator for rapid development
16-
- **Production Ready**: OIDC authentication, metrics, logging, and error handling
17-
- **Event-Driven**: Async processing via PostgreSQL NOTIFY/LISTEN
18-
- **Database Management**: GORM ORM with migrations and advisory locking
19-
- **Testing**: Built-in test framework with unit and integration tests
20-
- **Deployment**: Container-ready with OpenShift support
18+
**Goal**: Get from zero to production-ready API in minutes, not days.
2119

22-
## Goals
2320

24-
1. **Rapid Bootstrapping**: Get from zero to production-ready API in minutes
25-
2. **Best Practices**: Enforce enterprise patterns and standards
26-
3. **Framework Evolution**: Provide an upgrade path for future improvements
27-
4. **Developer Experience**: Minimize boilerplate while maximizing functionality
21+
## Choose Your Path
2822

23+
### 🏗️ I Want to Create a New Microservice
24+
**[Template Cloning Guide](docs/template-cloning/)**
2925

30-
## Getting Started
31-
32-
### Quick Start Options
33-
34-
**Option 1: Clone TRex for New Project**
35-
```shell
36-
# Build TRex cloning tool
37-
make binary
38-
39-
# Clone TRex template to new project
40-
./trex clone --name my-service --destination ~/projects/src/github.com/my-org/my-service
26+
Clone TRex into a new project with your business domain:
27+
```bash
28+
go run ./scripts/clone/main.go --name my-service --destination ~/projects/my-service
4129
```
4230

43-
**Option 2: Generate New Entity in Current Project**
44-
```shell
45-
# Generate complete CRUD entity with API, service, DAO layers
46-
go run ./scripts/generator.go --kind Product
47-
```
48-
49-
**Option 3: Run TRex Locally**
50-
51-
See [RUNNING.md](./RUNNING.md) for complete setup and running instructions including:
52-
- Building and database setup
53-
- Running migrations and tests
54-
- Starting the API server
55-
- Authentication with OCM tool
56-
- OpenShift deployment
31+
### 🔧 I Want to Add Entities to an Existing Project
32+
**[Entity Development Guide](docs/entity-development/)**
5733

58-
### Architecture
59-
60-
TRex follows clean architecture principles with clear separation of concerns:
61-
62-
- **API Layer** (`pkg/handlers/`): HTTP routing and request/response handling
63-
- **Service Layer** (`pkg/services/`): Business logic and transaction management
64-
- **DAO Layer** (`pkg/dao/`): Data access abstraction with GORM
65-
- **Database Layer** (`pkg/db/`): PostgreSQL with migrations and advisory locking
66-
67-
See [ASCIIARCH.md](./ASCIIARCH.md) for detailed architecture diagrams.
68-
69-
### Code Generation
34+
Generate complete CRUD operations for new business objects:
35+
```bash
36+
go run ./scripts/generate/main.go --kind Product
37+
```
7038

71-
TRex includes a powerful generator that creates complete CRUD operations:
39+
### 🎯 I Want to Explore TRex First
40+
**[Local Development Guide](docs/operations/local-development.md)**
7241

73-
```shell
74-
go run ./scripts/generator.go --kind EntityName
42+
Run TRex locally to understand how it works:
43+
```bash
44+
make db/setup && make run
45+
# Visit http://localhost:8000/api/rh-trex/v1/dinosaurs
7546
```
7647

77-
**Generates:**
78-
- **Plugin file**: Single consolidated file with all framework registrations
79-
- **API models and handlers**: RESTful endpoints with authentication
80-
- **Service layer**: Business logic with transaction management
81-
- **DAO layer**: Database operations with GORM
82-
- **OpenAPI specifications**: Auto-generated API documentation
83-
- **Database migrations**: Schema evolution with rollback support
84-
- **Unit and integration tests**: Comprehensive test coverage
85-
- **Test factories and mocks**: Testing infrastructure
48+
## Complete Documentation
49+
50+
**📚 [Full Documentation](docs/)** - Organized by user workflow:
8651

87-
**Plugin Architecture**: The generator creates a single `plugins/{entity}/plugin.go` file containing all framework registrations, eliminating manual framework edits. See [API-PLUGINS.md](./API-PLUGINS.md) for architecture details.
52+
- **[Getting Started](docs/getting-started/)** - Choose your path and understand TRex
53+
- **[Template Cloning](docs/template-cloning/)** - Create new microservices
54+
- **[Entity Development](docs/entity-development/)** - Add entities to existing projects
55+
- **[Operations](docs/operations/)** - Deploy and run services
56+
- **[Reference](docs/reference/)** - Technical specifications and APIs
57+
- **[Troubleshooting](docs/troubleshooting/)** - Common problems and solutions
58+
- **[Framework Development](docs/framework-development/)** - Contributing to TRex
8859

89-
### Development Workflow
60+
## Architecture Overview
9061

91-
1. **Generate Entity**: Use generator for new business objects (creates plugin file automatically)
92-
2. **Customize Logic**: Add business rules in service layer
93-
3. **Test**: Run unit tests (`make test`) and integration tests (`make test-integration`)
94-
4. **Update API**: Modify OpenAPI specs and run `make generate`
95-
5. **Deploy**: Use `make deploy` for OpenShift or container deployment
62+
TRex uses a **plugin-based architecture** where each business entity is self-contained:
9663

97-
### Documentation
64+
- **API Layer** - RESTful endpoints with authentication
65+
- **Service Layer** - Business logic with transaction management
66+
- **DAO Layer** - Database operations with GORM
67+
- **Plugin System** - Auto-registration, no manual framework edits
9868

99-
- **[API-PLUGINS.md](./API-PLUGINS.md)**: Plugin architecture and auto-discovery patterns
100-
- **[CLAUDE.md](./CLAUDE.md)**: Development commands and generator usage
101-
- **[RUNNING.md](./RUNNING.md)**: Complete setup and deployment guide
102-
- **[ASCIIARCH.md](./ASCIIARCH.md)**: Architecture diagrams and design patterns
69+
See **[Architecture Diagrams](docs/framework-development/architecture-diagrams.md)** for detailed technical overview.

0 commit comments

Comments
 (0)