Compare commits
1 Commits
5fdbb729bd
...
dda5060474
| Author | SHA1 | Date | |
|---|---|---|---|
| dda5060474 |
@@ -13,11 +13,21 @@ linters:
|
|||||||
- errcheck
|
- errcheck
|
||||||
- govet
|
- govet
|
||||||
- staticcheck
|
- staticcheck
|
||||||
|
- revive
|
||||||
- gosec
|
- gosec
|
||||||
disable:
|
disable:
|
||||||
- gocritic # Can be enabled later for stricter checks
|
- gocritic # Can be enabled later for stricter checks
|
||||||
|
|
||||||
linters-settings:
|
linters-settings:
|
||||||
|
revive:
|
||||||
|
rules:
|
||||||
|
- name: exported
|
||||||
|
severity: warning
|
||||||
|
arguments:
|
||||||
|
- checkPrivateReceivers
|
||||||
|
# Disable stuttering check - interface names like ConfigProvider are acceptable
|
||||||
|
- name: package-comments
|
||||||
|
severity: warning
|
||||||
gosec:
|
gosec:
|
||||||
severity: medium
|
severity: medium
|
||||||
errcheck:
|
errcheck:
|
||||||
@@ -33,6 +43,10 @@ issues:
|
|||||||
linters:
|
linters:
|
||||||
- errcheck
|
- errcheck
|
||||||
- gosec
|
- gosec
|
||||||
|
# ConfigProvider stuttering is acceptable - it's a common pattern for interfaces
|
||||||
|
- path: pkg/config/config\.go
|
||||||
|
linters:
|
||||||
|
- revive
|
||||||
|
|
||||||
output:
|
output:
|
||||||
print-issued-lines: true
|
print-issued-lines: true
|
||||||
|
|||||||
@@ -184,7 +184,6 @@ When working on this project, follow this workflow:
|
|||||||
- Meet the acceptance criteria
|
- Meet the acceptance criteria
|
||||||
- Use the implementation notes as guidance
|
- Use the implementation notes as guidance
|
||||||
- Follow the patterns established in `playbook.md`
|
- Follow the patterns established in `playbook.md`
|
||||||
- Implement tests
|
|
||||||
|
|
||||||
### 6. Verify Alignment
|
### 6. Verify Alignment
|
||||||
- Ensure code follows Clean/Hexagonal Architecture principles
|
- Ensure code follows Clean/Hexagonal Architecture principles
|
||||||
@@ -197,8 +196,6 @@ When working on this project, follow this workflow:
|
|||||||
- **ALWAYS commit** after successful implementation
|
- **ALWAYS commit** after successful implementation
|
||||||
- Ensure the code builds (`go build`)
|
- Ensure the code builds (`go build`)
|
||||||
- Ensure all tests pass (`go test`)
|
- Ensure all tests pass (`go test`)
|
||||||
- Ensure there are no linter issues (`make lint`)
|
|
||||||
- Ensure there are no fmt issues (`make fmt-check`)
|
|
||||||
- Verify all acceptance criteria are met
|
- Verify all acceptance criteria are met
|
||||||
- Write a clear, descriptive commit message
|
- Write a clear, descriptive commit message
|
||||||
|
|
||||||
@@ -304,7 +301,6 @@ If you make architectural decisions or significant changes:
|
|||||||
2. Update architecture documents if structure changes
|
2. Update architecture documents if structure changes
|
||||||
3. Update stories if implementation details change
|
3. Update stories if implementation details change
|
||||||
4. Keep documentation in sync with code
|
4. Keep documentation in sync with code
|
||||||
5. Do not use any emojis
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
4
Makefile
4
Makefile
@@ -49,11 +49,11 @@ help:
|
|||||||
# Development commands
|
# Development commands
|
||||||
test:
|
test:
|
||||||
@echo "Running tests..."
|
@echo "Running tests..."
|
||||||
CGO_ENABLED=1 $(GO) test -v ./...
|
CGO_ENABLED=1 $(GO) test -v -race ./...
|
||||||
|
|
||||||
test-coverage:
|
test-coverage:
|
||||||
@echo "Running tests with coverage..."
|
@echo "Running tests with coverage..."
|
||||||
CGO_ENABLED=1 $(GO) test -v -coverprofile=coverage.out ./...
|
CGO_ENABLED=1 $(GO) test -v -race -coverprofile=coverage.out ./...
|
||||||
$(GO) tool cover -html=coverage.out -o coverage.html
|
$(GO) tool cover -html=coverage.out -o coverage.html
|
||||||
@echo "Coverage report generated: coverage.html"
|
@echo "Coverage report generated: coverage.html"
|
||||||
|
|
||||||
|
|||||||
24
README.md
24
README.md
@@ -4,7 +4,7 @@
|
|||||||
|
|
||||||
A modular, extensible platform built with Go that provides a solid foundation for building scalable, secure, and observable applications. The platform supports plugin-based architecture, enabling teams to build feature modules independently while sharing core services.
|
A modular, extensible platform built with Go that provides a solid foundation for building scalable, secure, and observable applications. The platform supports plugin-based architecture, enabling teams to build feature modules independently while sharing core services.
|
||||||
|
|
||||||
## Architecture Overview
|
## 🏗️ Architecture Overview
|
||||||
|
|
||||||
Go Platform follows **Clean/Hexagonal Architecture** principles with clear separation between:
|
Go Platform follows **Clean/Hexagonal Architecture** principles with clear separation between:
|
||||||
|
|
||||||
@@ -23,7 +23,7 @@ Go Platform follows **Clean/Hexagonal Architecture** principles with clear separ
|
|||||||
- **Security-by-Design**: JWT authentication, RBAC/ABAC, and audit logging
|
- **Security-by-Design**: JWT authentication, RBAC/ABAC, and audit logging
|
||||||
- **Observability**: OpenTelemetry, structured logging, and Prometheus metrics
|
- **Observability**: OpenTelemetry, structured logging, and Prometheus metrics
|
||||||
|
|
||||||
## Directory Structure
|
## 📁 Directory Structure
|
||||||
|
|
||||||
```
|
```
|
||||||
goplt/
|
goplt/
|
||||||
@@ -59,7 +59,7 @@ goplt/
|
|||||||
└── ci.yml
|
└── ci.yml
|
||||||
```
|
```
|
||||||
|
|
||||||
## Quick Start
|
## 🚀 Quick Start
|
||||||
|
|
||||||
### Prerequisites
|
### Prerequisites
|
||||||
|
|
||||||
@@ -107,7 +107,7 @@ export DATABASE_DSN="postgres://user:pass@localhost/dbname"
|
|||||||
export LOGGING_LEVEL=debug
|
export LOGGING_LEVEL=debug
|
||||||
```
|
```
|
||||||
|
|
||||||
## Development
|
## 🛠️ Development
|
||||||
|
|
||||||
### Make Commands
|
### Make Commands
|
||||||
|
|
||||||
@@ -150,7 +150,7 @@ Run all checks:
|
|||||||
make verify
|
make verify
|
||||||
```
|
```
|
||||||
|
|
||||||
## Documentation
|
## 📚 Documentation
|
||||||
|
|
||||||
Comprehensive documentation is available in the `docs/` directory:
|
Comprehensive documentation is available in the `docs/` directory:
|
||||||
|
|
||||||
@@ -172,7 +172,7 @@ make docs-docker
|
|||||||
|
|
||||||
Documentation will be available at `http://127.0.0.1:8000`
|
Documentation will be available at `http://127.0.0.1:8000`
|
||||||
|
|
||||||
## Architecture
|
## 🏛️ Architecture
|
||||||
|
|
||||||
### Core Kernel
|
### Core Kernel
|
||||||
|
|
||||||
@@ -223,7 +223,7 @@ Key configuration sections:
|
|||||||
- **Logging**: Log level, format, and output destination
|
- **Logging**: Log level, format, and output destination
|
||||||
- **Authentication**: JWT settings and token configuration
|
- **Authentication**: JWT settings and token configuration
|
||||||
|
|
||||||
## Testing
|
## 🧪 Testing
|
||||||
|
|
||||||
The project follows table-driven testing patterns and includes:
|
The project follows table-driven testing patterns and includes:
|
||||||
|
|
||||||
@@ -232,7 +232,7 @@ The project follows table-driven testing patterns and includes:
|
|||||||
- Mock generation for interfaces
|
- Mock generation for interfaces
|
||||||
- Test coverage reporting
|
- Test coverage reporting
|
||||||
|
|
||||||
## Contributing
|
## 🤝 Contributing
|
||||||
|
|
||||||
1. Create a feature branch: `git checkout -b feature/my-feature`
|
1. Create a feature branch: `git checkout -b feature/my-feature`
|
||||||
2. Make your changes following the project's architecture principles
|
2. Make your changes following the project's architecture principles
|
||||||
@@ -240,11 +240,11 @@ The project follows table-driven testing patterns and includes:
|
|||||||
4. Commit your changes with clear messages
|
4. Commit your changes with clear messages
|
||||||
5. Push to your branch and create a pull request
|
5. Push to your branch and create a pull request
|
||||||
|
|
||||||
## License
|
## 📄 License
|
||||||
|
|
||||||
[Add license information here]
|
[Add license information here]
|
||||||
|
|
||||||
## Links
|
## 🔗 Links
|
||||||
|
|
||||||
- [Architecture Documentation](docs/content/architecture/)
|
- [Architecture Documentation](docs/content/architecture/)
|
||||||
- [ADRs](docs/content/adr/)
|
- [ADRs](docs/content/adr/)
|
||||||
@@ -254,3 +254,7 @@ The project follows table-driven testing patterns and includes:
|
|||||||
## 📞 Support
|
## 📞 Support
|
||||||
|
|
||||||
For questions and support, please refer to the documentation or create an issue in the repository.
|
For questions and support, please refer to the documentation or create an issue in the repository.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**Built with ❤️ using Go**
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ func main() {
|
|||||||
fx.Invoke(di.RegisterLifecycleHooks),
|
fx.Invoke(di.RegisterLifecycleHooks),
|
||||||
// Force HTTP server to be created (which triggers all dependencies)
|
// Force HTTP server to be created (which triggers all dependencies)
|
||||||
// This ensures database, health, metrics, etc. are all created
|
// This ensures database, health, metrics, etc. are all created
|
||||||
fx.Invoke(func(_ *server.Server, _ *database.Client) {
|
fx.Invoke(func(srv *server.Server, dbClient *database.Client) {
|
||||||
// Both server and database are created, hooks are registered
|
// Both server and database are created, hooks are registered
|
||||||
// This ensures all providers execute
|
// This ensures all providers execute
|
||||||
}),
|
}),
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
environment: development
|
environment: development
|
||||||
|
|
||||||
server:
|
server:
|
||||||
port: 8080
|
port: 3000
|
||||||
host: "0.0.0.0"
|
host: "0.0.0.0"
|
||||||
read_timeout: 30s
|
read_timeout: 30s
|
||||||
write_timeout: 30s
|
write_timeout: 30s
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
# Go‑Platform Boilerplate Play‑book
|
# Go‑Platform Boilerplate Play‑book
|
||||||
**“Plug‑in‑friendly SaaS/Enterprise Platform – Go Edition”**
|
**“Plug‑in‑friendly SaaS/Enterprise Platform – Go Edition”**
|
||||||
|
|
||||||
## 1 ARCHITECTURAL IMPERATIVES (Go‑flavoured)
|
## 1️⃣ ARCHITECTURAL IMPERATIVES (Go‑flavoured)
|
||||||
|
|
||||||
| Principle | Go‑specific rationale | Enforcement Technique |
|
| Principle | Go‑specific rationale | Enforcement Technique |
|
||||||
|-----------|-----------------------|------------------------|
|
|-----------|-----------------------|------------------------|
|
||||||
@@ -18,7 +18,7 @@
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 2 CORE KERNEL (What every Go‑platform must ship)
|
## 2️⃣ CORE KERNEL (What every Go‑platform must ship)
|
||||||
|
|
||||||
| Module | Public Interfaces (exported from `pkg/`) | Recommended Packages | Brief Implementation Sketch |
|
| Module | Public Interfaces (exported from `pkg/`) | Recommended Packages | Brief Implementation Sketch |
|
||||||
|--------|-------------------------------------------|----------------------|------------------------------|
|
|--------|-------------------------------------------|----------------------|------------------------------|
|
||||||
@@ -40,7 +40,7 @@ All *public* interfaces live under `pkg/` so that plug‑ins can import them wit
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 3 MODULE (PLUGIN) FRAMEWORK
|
## 3️⃣ MODULE (PLUGIN) FRAMEWORK
|
||||||
|
|
||||||
### 3.1 Interface that every module must implement
|
### 3.1 Interface that every module must implement
|
||||||
|
|
||||||
@@ -167,7 +167,7 @@ A **code‑gen** tool (`go generate ./...`) can scan each module’s `module.yam
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 4 SAMPLE FEATURE MODULE – **Blog**
|
## 4️⃣ SAMPLE FEATURE MODULE – **Blog**
|
||||||
|
|
||||||
```
|
```
|
||||||
modules/
|
modules/
|
||||||
@@ -312,7 +312,7 @@ func (r *PostRepo) Create(ctx context.Context, p *Post) (*Post, error) {
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 5 INFRASTRUCTURE ADAPTERS (swap‑able, per‑environment)
|
## 5️⃣ INFRASTRUCTURE ADAPTERS (swap‑able, per‑environment)
|
||||||
|
|
||||||
| Concern | Implementation (Go) | Where it lives |
|
| Concern | Implementation (Go) | Where it lives |
|
||||||
|---------|---------------------|----------------|
|
|---------|---------------------|----------------|
|
||||||
@@ -328,7 +328,7 @@ All adapters expose an **interface** in `pkg/infra/…` and are registered in th
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 6 OBSERVABILITY STACK
|
## 6️⃣ OBSERVABILITY STACK
|
||||||
|
|
||||||
| Layer | Library | What it does |
|
| Layer | Library | What it does |
|
||||||
|-------|---------|--------------|
|
|-------|---------|--------------|
|
||||||
@@ -372,7 +372,7 @@ func PromMetrics() gin.HandlerFunc {
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 7 CONFIGURATION & ENVIRONMENT
|
## 7️⃣ CONFIGURATION & ENVIRONMENT
|
||||||
|
|
||||||
```
|
```
|
||||||
config/
|
config/
|
||||||
@@ -405,7 +405,7 @@ All services receive a `*Config` via DI.
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 8 CI / CD PIPELINE (GitHub Actions)
|
## 8️⃣ CI / CD PIPELINE (GitHub Actions)
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
name: CI
|
name: CI
|
||||||
@@ -469,7 +469,7 @@ jobs:
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 9 TESTING STRATEGY
|
## 9️⃣ TESTING STRATEGY
|
||||||
|
|
||||||
| Test type | Tools | Typical coverage |
|
| Test type | Tools | Typical coverage |
|
||||||
|-----------|-------|------------------|
|
|-----------|-------|------------------|
|
||||||
@@ -523,7 +523,7 @@ func TestCreatePost_Integration(t *testing.T) {
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 10 COMMON PITFALLS & SOLUTIONS (Go‑centric)
|
## 10️⃣ COMMON PITFALLS & SOLUTIONS (Go‑centric)
|
||||||
|
|
||||||
| Pitfall | Symptom | Remedy |
|
| Pitfall | Symptom | Remedy |
|
||||||
|---------|----------|--------|
|
|---------|----------|--------|
|
||||||
@@ -540,7 +540,7 @@ func TestCreatePost_Integration(t *testing.T) {
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 11 QUICK‑START STEPS (What to code first)
|
## 11️⃣ QUICK‑START STEPS (What to code first)
|
||||||
|
|
||||||
1. **Bootstrap repo**
|
1. **Bootstrap repo**
|
||||||
```bash
|
```bash
|
||||||
@@ -586,7 +586,7 @@ After step 10 you have a **complete, production‑grade scaffolding** that:
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 12 REFERENCE IMPLEMENTATION (public)
|
## 12️⃣ REFERENCE IMPLEMENTATION (public)
|
||||||
|
|
||||||
If you prefer to start from a **real open‑source baseline**, check out the following community projects that already adopt most of the ideas above:
|
If you prefer to start from a **real open‑source baseline**, check out the following community projects that already adopt most of the ideas above:
|
||||||
|
|
||||||
@@ -602,7 +602,7 @@ Fork one, strip the business logic, and rename the packages to match *your* `git
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 13 FINAL CHECKLIST (before you ship)
|
## 13️⃣ FINAL CHECKLIST (before you ship)
|
||||||
|
|
||||||
- [ ] Core modules compiled & registered in `internal/di`.
|
- [ ] Core modules compiled & registered in `internal/di`.
|
||||||
- [ ] `module.IModule` interface and static registry in place.
|
- [ ] `module.IModule` interface and static registry in place.
|
||||||
@@ -617,4 +617,4 @@ Fork one, strip the business logic, and rename the packages to match *your* `git
|
|||||||
- [ ] Sample plug‑in (Blog) builds, loads, registers routes, and passes integration test.
|
- [ ] Sample plug‑in (Blog) builds, loads, registers routes, and passes integration test.
|
||||||
- [ ] Documentation: `README.md`, `docs/architecture.md`, `docs/extension-points.md`.
|
- [ ] Documentation: `README.md`, `docs/architecture.md`, `docs/extension-points.md`.
|
||||||
|
|
||||||
> **Congratulations!** You now have a **robust, extensible Go platform boilerplate** that can be the foundation for any SaaS, internal toolset, or micro‑service ecosystem you wish to build. Happy coding!
|
> **Congratulations!** You now have a **robust, extensible Go platform boilerplate** that can be the foundation for any SaaS, internal toolset, or micro‑service ecosystem you wish to build. Happy coding! 🚀
|
||||||
@@ -1,4 +1,3 @@
|
|||||||
// Package ent provides code generation for Ent schema definitions.
|
|
||||||
package ent
|
package ent
|
||||||
|
|
||||||
//go:generate go run -mod=mod entgo.io/ent/cmd/ent generate ./schema
|
//go:generate go run -mod=mod entgo.io/ent/cmd/ent generate ./schema
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
// Package schema defines the Ent schema for audit log entities.
|
|
||||||
package schema
|
package schema
|
||||||
|
|
||||||
import "entgo.io/ent"
|
import "entgo.io/ent"
|
||||||
|
|||||||
@@ -19,7 +19,6 @@ import (
|
|||||||
"git.dcentral.systems/toolz/goplt/pkg/errorbus"
|
"git.dcentral.systems/toolz/goplt/pkg/errorbus"
|
||||||
"git.dcentral.systems/toolz/goplt/pkg/logger"
|
"git.dcentral.systems/toolz/goplt/pkg/logger"
|
||||||
"go.opentelemetry.io/otel/trace"
|
"go.opentelemetry.io/otel/trace"
|
||||||
"go.opentelemetry.io/otel/trace/noop"
|
|
||||||
"go.uber.org/fx"
|
"go.uber.org/fx"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -131,7 +130,7 @@ func ProvideDatabase() fx.Option {
|
|||||||
log.Info("Database migrations completed successfully")
|
log.Info("Database migrations completed successfully")
|
||||||
return nil
|
return nil
|
||||||
},
|
},
|
||||||
OnStop: func(_ context.Context) error {
|
OnStop: func(ctx context.Context) error {
|
||||||
return dbClient.Close()
|
return dbClient.Close()
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
@@ -148,7 +147,7 @@ func ProvideErrorBus() fx.Option {
|
|||||||
|
|
||||||
// Register lifecycle hook to close the bus on shutdown
|
// Register lifecycle hook to close the bus on shutdown
|
||||||
lc.Append(fx.Hook{
|
lc.Append(fx.Hook{
|
||||||
OnStop: func(_ context.Context) error {
|
OnStop: func(ctx context.Context) error {
|
||||||
return bus.Close()
|
return bus.Close()
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
@@ -182,7 +181,7 @@ func ProvideTracer() fx.Option {
|
|||||||
enabled := cfg.GetBool("tracing.enabled")
|
enabled := cfg.GetBool("tracing.enabled")
|
||||||
if !enabled {
|
if !enabled {
|
||||||
// Return no-op tracer
|
// Return no-op tracer
|
||||||
return noop.NewTracerProvider(), nil
|
return trace.NewNoopTracerProvider(), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
serviceName := cfg.GetString("tracing.service_name")
|
serviceName := cfg.GetString("tracing.service_name")
|
||||||
@@ -249,7 +248,8 @@ func ProvideHTTPServer() fx.Option {
|
|||||||
|
|
||||||
// Register lifecycle hooks
|
// Register lifecycle hooks
|
||||||
lc.Append(fx.Hook{
|
lc.Append(fx.Hook{
|
||||||
OnStart: func(_ context.Context) error {
|
OnStart: func(ctx context.Context) error {
|
||||||
|
|
||||||
// Get server address from config
|
// Get server address from config
|
||||||
port := cfg.GetInt("server.port")
|
port := cfg.GetInt("server.port")
|
||||||
if port == 0 {
|
if port == 0 {
|
||||||
@@ -300,7 +300,7 @@ func ProvideHTTPServer() fx.Option {
|
|||||||
)
|
)
|
||||||
// Continue anyway - server might still be starting
|
// Continue anyway - server might still be starting
|
||||||
} else {
|
} else {
|
||||||
_ = resp.Body.Close()
|
resp.Body.Close()
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Info("HTTP server started successfully",
|
log.Info("HTTP server started successfully",
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
// Package schema defines the Ent schema for domain entities.
|
|
||||||
package schema
|
package schema
|
||||||
|
|
||||||
import (
|
import (
|
||||||
@@ -47,3 +46,4 @@ func (AuditLog) Indexes() []ent.Index {
|
|||||||
index.Fields("action"),
|
index.Fields("action"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -30,3 +30,4 @@ func (Permission) Edges() []ent.Edge {
|
|||||||
edge.To("role_permissions", RolePermission.Type),
|
edge.To("role_permissions", RolePermission.Type),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -37,3 +37,4 @@ func (Role) Edges() []ent.Edge {
|
|||||||
edge.To("user_roles", UserRole.Type),
|
edge.To("user_roles", UserRole.Type),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -32,3 +32,4 @@ func (RolePermission) Edges() []ent.Edge {
|
|||||||
Field("permission_id"),
|
Field("permission_id"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -41,3 +41,4 @@ func (User) Edges() []ent.Edge {
|
|||||||
edge.To("user_roles", UserRole.Type),
|
edge.To("user_roles", UserRole.Type),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -32,3 +32,4 @@ func (UserRole) Edges() []ent.Edge {
|
|||||||
Field("role_id"),
|
Field("role_id"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
// Package errorbus provides a channel-based error bus implementation.
|
|
||||||
package errorbus
|
package errorbus
|
||||||
|
|
||||||
import (
|
import (
|
||||||
@@ -17,13 +16,12 @@ type ChannelBus struct {
|
|||||||
done chan struct{}
|
done chan struct{}
|
||||||
wg sync.WaitGroup
|
wg sync.WaitGroup
|
||||||
once sync.Once
|
once sync.Once
|
||||||
closeOnce sync.Once
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type errorWithContext struct {
|
type errorWithContext struct {
|
||||||
err error
|
err error
|
||||||
ctx context.Context
|
ctx context.Context
|
||||||
stack []byte
|
stack []byte
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewChannelBus creates a new channel-based error bus.
|
// NewChannelBus creates a new channel-based error bus.
|
||||||
@@ -158,11 +156,10 @@ func (b *ChannelBus) Close() error {
|
|||||||
close(b.done)
|
close(b.done)
|
||||||
})
|
})
|
||||||
b.wg.Wait()
|
b.wg.Wait()
|
||||||
b.closeOnce.Do(func() {
|
close(b.errors)
|
||||||
close(b.errors)
|
|
||||||
})
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Ensure ChannelBus implements ErrorPublisher
|
// Ensure ChannelBus implements ErrorPublisher
|
||||||
var _ errorbus.ErrorPublisher = (*ChannelBus)(nil)
|
var _ errorbus.ErrorPublisher = (*ChannelBus)(nil)
|
||||||
|
|
||||||
|
|||||||
@@ -1,199 +0,0 @@
|
|||||||
package errorbus
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"errors"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"git.dcentral.systems/toolz/goplt/pkg/logger"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestNewChannelBus(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
mockLogger := &mockLogger{}
|
|
||||||
bus := NewChannelBus(mockLogger, 100)
|
|
||||||
|
|
||||||
if bus == nil {
|
|
||||||
t.Fatal("Expected bus, got nil")
|
|
||||||
}
|
|
||||||
|
|
||||||
if bus.errors == nil {
|
|
||||||
t.Error("Expected errors channel, got nil")
|
|
||||||
}
|
|
||||||
|
|
||||||
if bus.logger == nil {
|
|
||||||
t.Error("Expected logger, got nil")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Clean up
|
|
||||||
_ = bus.Close()
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestNewChannelBus_DefaultBufferSize(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
mockLogger := &mockLogger{}
|
|
||||||
bus := NewChannelBus(mockLogger, 0)
|
|
||||||
|
|
||||||
if bus == nil {
|
|
||||||
t.Fatal("Expected bus, got nil")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Clean up
|
|
||||||
_ = bus.Close()
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestChannelBus_Publish(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
mockLogger := &mockLogger{}
|
|
||||||
bus := NewChannelBus(mockLogger, 10)
|
|
||||||
|
|
||||||
testErr := errors.New("test error")
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
// Publish error
|
|
||||||
bus.Publish(ctx, testErr)
|
|
||||||
|
|
||||||
// Wait a bit for the error to be processed
|
|
||||||
time.Sleep(100 * time.Millisecond)
|
|
||||||
|
|
||||||
// Verify error was logged
|
|
||||||
if len(mockLogger.errors) == 0 {
|
|
||||||
t.Error("Expected error to be logged")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Clean up
|
|
||||||
_ = bus.Close()
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestChannelBus_Publish_NilError(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
mockLogger := &mockLogger{}
|
|
||||||
bus := NewChannelBus(mockLogger, 10)
|
|
||||||
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
// Publish nil error (should be ignored)
|
|
||||||
bus.Publish(ctx, nil)
|
|
||||||
|
|
||||||
// Wait a bit
|
|
||||||
time.Sleep(50 * time.Millisecond)
|
|
||||||
|
|
||||||
// Verify nil error was not logged
|
|
||||||
if len(mockLogger.errors) > 0 {
|
|
||||||
t.Error("Expected nil error to be ignored")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Clean up
|
|
||||||
_ = bus.Close()
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestChannelBus_Publish_WithContext(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
mockLogger := &mockLogger{}
|
|
||||||
bus := NewChannelBus(mockLogger, 10)
|
|
||||||
|
|
||||||
testErr := errors.New("test error")
|
|
||||||
ctx := context.WithValue(context.Background(), "request_id", "test-request-id")
|
|
||||||
|
|
||||||
bus.Publish(ctx, testErr)
|
|
||||||
|
|
||||||
// Wait for processing
|
|
||||||
time.Sleep(100 * time.Millisecond)
|
|
||||||
|
|
||||||
// Verify error was logged with context
|
|
||||||
if len(mockLogger.errors) == 0 {
|
|
||||||
t.Error("Expected error to be logged")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Clean up
|
|
||||||
_ = bus.Close()
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestChannelBus_Close(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
mockLogger := &mockLogger{}
|
|
||||||
bus := NewChannelBus(mockLogger, 10)
|
|
||||||
|
|
||||||
// Publish some errors
|
|
||||||
for i := 0; i < 5; i++ {
|
|
||||||
bus.Publish(context.Background(), errors.New("test error"))
|
|
||||||
}
|
|
||||||
|
|
||||||
// Close and wait
|
|
||||||
if err := bus.Close(); err != nil {
|
|
||||||
t.Errorf("Close failed: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Verify channel is closed
|
|
||||||
select {
|
|
||||||
case <-bus.errors:
|
|
||||||
// Channel is closed, this is expected
|
|
||||||
default:
|
|
||||||
t.Error("Expected errors channel to be closed")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestChannelBus_Close_MultipleTimes(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
mockLogger := &mockLogger{}
|
|
||||||
bus := NewChannelBus(mockLogger, 10)
|
|
||||||
|
|
||||||
// Close first time
|
|
||||||
if err := bus.Close(); err != nil {
|
|
||||||
t.Errorf("First Close failed: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Close second time should be safe (uses sync.Once)
|
|
||||||
// The channel is already closed, but Close() should handle this gracefully
|
|
||||||
if err := bus.Close(); err != nil {
|
|
||||||
t.Errorf("Second Close failed: %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestChannelBus_ChannelFull(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
mockLogger := &mockLogger{}
|
|
||||||
// Use small buffer to test channel full scenario
|
|
||||||
bus := NewChannelBus(mockLogger, 1)
|
|
||||||
|
|
||||||
// Fill the channel
|
|
||||||
bus.Publish(context.Background(), errors.New("error1"))
|
|
||||||
|
|
||||||
// This should not block (channel is full, should log directly)
|
|
||||||
bus.Publish(context.Background(), errors.New("error2"))
|
|
||||||
|
|
||||||
// Wait a bit
|
|
||||||
time.Sleep(100 * time.Millisecond)
|
|
||||||
|
|
||||||
// Clean up
|
|
||||||
_ = bus.Close()
|
|
||||||
}
|
|
||||||
|
|
||||||
// mockLogger implements logger.Logger for testing.
|
|
||||||
type mockLogger struct {
|
|
||||||
errors []string
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *mockLogger) Debug(msg string, fields ...logger.Field) {}
|
|
||||||
func (m *mockLogger) Info(msg string, fields ...logger.Field) {}
|
|
||||||
func (m *mockLogger) Warn(msg string, fields ...logger.Field) {}
|
|
||||||
func (m *mockLogger) Error(msg string, fields ...logger.Field) {
|
|
||||||
m.errors = append(m.errors, msg)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *mockLogger) With(fields ...logger.Field) logger.Logger {
|
|
||||||
return m
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *mockLogger) WithContext(ctx context.Context) logger.Logger {
|
|
||||||
return m
|
|
||||||
}
|
|
||||||
@@ -1,4 +1,3 @@
|
|||||||
// Package health provides health check implementations for various components.
|
|
||||||
package health
|
package health
|
||||||
|
|
||||||
import (
|
import (
|
||||||
@@ -24,3 +23,4 @@ func NewDatabaseChecker(client *database.Client) health.HealthChecker {
|
|||||||
func (d *DatabaseChecker) Check(ctx context.Context) error {
|
func (d *DatabaseChecker) Check(ctx context.Context) error {
|
||||||
return d.client.Ping(ctx)
|
return d.client.Ping(ctx)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,106 +0,0 @@
|
|||||||
package health
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"git.dcentral.systems/toolz/goplt/internal/infra/database"
|
|
||||||
"git.dcentral.systems/toolz/goplt/pkg/health"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestNewDatabaseChecker(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
dsn := "postgres://goplt:goplt_password@localhost:5432/goplt?sslmode=disable"
|
|
||||||
if testing.Short() {
|
|
||||||
t.Skip("Skipping database test in short mode")
|
|
||||||
}
|
|
||||||
|
|
||||||
cfg := database.Config{
|
|
||||||
DSN: dsn,
|
|
||||||
MaxConnections: 10,
|
|
||||||
MaxIdleConns: 5,
|
|
||||||
}
|
|
||||||
|
|
||||||
client, err := database.NewClient(cfg)
|
|
||||||
if err != nil {
|
|
||||||
t.Skipf("Skipping test - database not available: %v", err)
|
|
||||||
}
|
|
||||||
defer func() {
|
|
||||||
if err := client.Close(); err != nil {
|
|
||||||
t.Logf("Failed to close client: %v", err)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
checker := NewDatabaseChecker(client)
|
|
||||||
|
|
||||||
if checker == nil {
|
|
||||||
t.Fatal("Expected checker, got nil")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Verify it implements the interface
|
|
||||||
var _ health.HealthChecker = checker
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestDatabaseChecker_Check_Healthy(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
dsn := "postgres://goplt:goplt_password@localhost:5432/goplt?sslmode=disable"
|
|
||||||
if testing.Short() {
|
|
||||||
t.Skip("Skipping database test in short mode")
|
|
||||||
}
|
|
||||||
|
|
||||||
cfg := database.Config{
|
|
||||||
DSN: dsn,
|
|
||||||
MaxConnections: 10,
|
|
||||||
MaxIdleConns: 5,
|
|
||||||
}
|
|
||||||
|
|
||||||
client, err := database.NewClient(cfg)
|
|
||||||
if err != nil {
|
|
||||||
t.Skipf("Skipping test - database not available: %v", err)
|
|
||||||
}
|
|
||||||
defer func() {
|
|
||||||
if err := client.Close(); err != nil {
|
|
||||||
t.Logf("Failed to close client: %v", err)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
checker := NewDatabaseChecker(client)
|
|
||||||
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
||||||
defer cancel()
|
|
||||||
|
|
||||||
if err := checker.Check(ctx); err != nil {
|
|
||||||
t.Errorf("Expected healthy check, got error: %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestDatabaseChecker_Check_Unhealthy(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
// Create a client with invalid DSN to simulate unhealthy state
|
|
||||||
cfg := database.Config{
|
|
||||||
DSN: "postgres://invalid:invalid@localhost:9999/invalid?sslmode=disable",
|
|
||||||
MaxConnections: 10,
|
|
||||||
MaxIdleConns: 5,
|
|
||||||
}
|
|
||||||
|
|
||||||
client, err := database.NewClient(cfg)
|
|
||||||
if err == nil {
|
|
||||||
// If connection succeeds, we can't test unhealthy state
|
|
||||||
// So we'll just verify the checker is created
|
|
||||||
defer func() {
|
|
||||||
if err := client.Close(); err != nil {
|
|
||||||
t.Logf("Failed to close client: %v", err)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
t.Skip("Could not create unhealthy client for testing")
|
|
||||||
}
|
|
||||||
|
|
||||||
// For this test, we'll create a mock client that will fail on ping
|
|
||||||
// Since we can't easily create an unhealthy client, we'll skip this test
|
|
||||||
// if we can't create an invalid connection
|
|
||||||
t.Skip("Skipping unhealthy test - requires invalid database connection")
|
|
||||||
}
|
|
||||||
@@ -60,7 +60,7 @@ func (r *Registry) Check(ctx context.Context) health.HealthStatus {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// LivenessCheck performs a basic liveness check (no dependencies).
|
// LivenessCheck performs a basic liveness check (no dependencies).
|
||||||
func (r *Registry) LivenessCheck(_ context.Context) health.HealthStatus {
|
func (r *Registry) LivenessCheck(ctx context.Context) health.HealthStatus {
|
||||||
// Liveness is always healthy if the service is running
|
// Liveness is always healthy if the service is running
|
||||||
return health.HealthStatus{
|
return health.HealthStatus{
|
||||||
Status: health.StatusHealthy,
|
Status: health.StatusHealthy,
|
||||||
@@ -71,3 +71,4 @@ func (r *Registry) LivenessCheck(_ context.Context) health.HealthStatus {
|
|||||||
func (r *Registry) ReadinessCheck(ctx context.Context) health.HealthStatus {
|
func (r *Registry) ReadinessCheck(ctx context.Context) health.HealthStatus {
|
||||||
return r.Check(ctx)
|
return r.Check(ctx)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,191 +0,0 @@
|
|||||||
package health
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"errors"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"git.dcentral.systems/toolz/goplt/pkg/health"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestNewRegistry(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
registry := NewRegistry()
|
|
||||||
if registry == nil {
|
|
||||||
t.Fatal("Expected registry, got nil")
|
|
||||||
}
|
|
||||||
|
|
||||||
if registry.checkers == nil {
|
|
||||||
t.Error("Expected checkers map, got nil")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestRegistry_Register(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
registry := NewRegistry()
|
|
||||||
|
|
||||||
mockChecker := &mockChecker{
|
|
||||||
checkFunc: func(ctx context.Context) error {
|
|
||||||
return nil
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
registry.Register("test", mockChecker)
|
|
||||||
|
|
||||||
// Verify checker is registered
|
|
||||||
registry.mu.RLock()
|
|
||||||
checker, ok := registry.checkers["test"]
|
|
||||||
registry.mu.RUnlock()
|
|
||||||
|
|
||||||
if !ok {
|
|
||||||
t.Error("Expected checker to be registered")
|
|
||||||
}
|
|
||||||
|
|
||||||
if checker != mockChecker {
|
|
||||||
t.Error("Registered checker does not match")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestRegistry_Check_AllHealthy(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
registry := NewRegistry()
|
|
||||||
|
|
||||||
registry.Register("healthy1", &mockChecker{
|
|
||||||
checkFunc: func(ctx context.Context) error {
|
|
||||||
return nil
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
registry.Register("healthy2", &mockChecker{
|
|
||||||
checkFunc: func(ctx context.Context) error {
|
|
||||||
return nil
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
||||||
defer cancel()
|
|
||||||
|
|
||||||
status := registry.Check(ctx)
|
|
||||||
|
|
||||||
if status.Status != health.StatusHealthy {
|
|
||||||
t.Errorf("Expected status healthy, got %s", status.Status)
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(status.Components) != 2 {
|
|
||||||
t.Errorf("Expected 2 components, got %d", len(status.Components))
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, component := range status.Components {
|
|
||||||
if component.Status != health.StatusHealthy {
|
|
||||||
t.Errorf("Expected component %s to be healthy, got %s", component.Name, component.Status)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestRegistry_Check_OneUnhealthy(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
registry := NewRegistry()
|
|
||||||
|
|
||||||
registry.Register("healthy", &mockChecker{
|
|
||||||
checkFunc: func(ctx context.Context) error {
|
|
||||||
return nil
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
registry.Register("unhealthy", &mockChecker{
|
|
||||||
checkFunc: func(ctx context.Context) error {
|
|
||||||
return errors.New("component failed")
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
||||||
defer cancel()
|
|
||||||
|
|
||||||
status := registry.Check(ctx)
|
|
||||||
|
|
||||||
if status.Status != health.StatusUnhealthy {
|
|
||||||
t.Errorf("Expected status unhealthy, got %s", status.Status)
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(status.Components) != 2 {
|
|
||||||
t.Errorf("Expected 2 components, got %d", len(status.Components))
|
|
||||||
}
|
|
||||||
|
|
||||||
unhealthyFound := false
|
|
||||||
for _, component := range status.Components {
|
|
||||||
if component.Name == "unhealthy" {
|
|
||||||
unhealthyFound = true
|
|
||||||
if component.Status != health.StatusUnhealthy {
|
|
||||||
t.Errorf("Expected unhealthy component to be unhealthy, got %s", component.Status)
|
|
||||||
}
|
|
||||||
if component.Error == "" {
|
|
||||||
t.Error("Expected error message for unhealthy component")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if !unhealthyFound {
|
|
||||||
t.Error("Expected to find unhealthy component")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestRegistry_LivenessCheck(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
registry := NewRegistry()
|
|
||||||
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
||||||
defer cancel()
|
|
||||||
|
|
||||||
status := registry.LivenessCheck(ctx)
|
|
||||||
|
|
||||||
if status.Status != health.StatusHealthy {
|
|
||||||
t.Errorf("Expected liveness check to be healthy, got %s", status.Status)
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(status.Components) != 0 {
|
|
||||||
t.Errorf("Expected no components in liveness check, got %d", len(status.Components))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestRegistry_ReadinessCheck(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
registry := NewRegistry()
|
|
||||||
|
|
||||||
registry.Register("test", &mockChecker{
|
|
||||||
checkFunc: func(ctx context.Context) error {
|
|
||||||
return nil
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
||||||
defer cancel()
|
|
||||||
|
|
||||||
status := registry.ReadinessCheck(ctx)
|
|
||||||
|
|
||||||
if status.Status != health.StatusHealthy {
|
|
||||||
t.Errorf("Expected readiness check to be healthy, got %s", status.Status)
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(status.Components) != 1 {
|
|
||||||
t.Errorf("Expected 1 component in readiness check, got %d", len(status.Components))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// mockChecker is a mock implementation of HealthChecker for testing.
|
|
||||||
type mockChecker struct {
|
|
||||||
checkFunc func(ctx context.Context) error
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *mockChecker) Check(ctx context.Context) error {
|
|
||||||
if m.checkFunc != nil {
|
|
||||||
return m.checkFunc(ctx)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
@@ -1,4 +1,3 @@
|
|||||||
// Package database provides database client and connection management.
|
|
||||||
package database
|
package database
|
||||||
|
|
||||||
import (
|
import (
|
||||||
@@ -21,11 +20,11 @@ type Client struct {
|
|||||||
|
|
||||||
// Config holds database configuration.
|
// Config holds database configuration.
|
||||||
type Config struct {
|
type Config struct {
|
||||||
DSN string
|
DSN string
|
||||||
MaxConnections int
|
MaxConnections int
|
||||||
MaxIdleConns int
|
MaxIdleConns int
|
||||||
ConnMaxLifetime time.Duration
|
ConnMaxLifetime time.Duration
|
||||||
ConnMaxIdleTime time.Duration
|
ConnMaxIdleTime time.Duration
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewClient creates a new Ent client with connection pooling.
|
// NewClient creates a new Ent client with connection pooling.
|
||||||
@@ -47,7 +46,7 @@ func NewClient(cfg Config) (*Client, error) {
|
|||||||
defer cancel()
|
defer cancel()
|
||||||
|
|
||||||
if err := db.PingContext(ctx); err != nil {
|
if err := db.PingContext(ctx); err != nil {
|
||||||
_ = db.Close()
|
db.Close()
|
||||||
return nil, fmt.Errorf("failed to ping database: %w", err)
|
return nil, fmt.Errorf("failed to ping database: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -73,7 +72,7 @@ func (c *Client) Close() error {
|
|||||||
|
|
||||||
// Migrate runs database migrations.
|
// Migrate runs database migrations.
|
||||||
func (c *Client) Migrate(ctx context.Context) error {
|
func (c *Client) Migrate(ctx context.Context) error {
|
||||||
return c.Schema.Create(ctx)
|
return c.Client.Schema.Create(ctx)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Ping checks database connectivity.
|
// Ping checks database connectivity.
|
||||||
@@ -85,3 +84,4 @@ func (c *Client) Ping(ctx context.Context) error {
|
|||||||
func (c *Client) DB() *sql.DB {
|
func (c *Client) DB() *sql.DB {
|
||||||
return c.db
|
return c.db
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,160 +0,0 @@
|
|||||||
package database
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestNewClient_InvalidDSN(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
cfg := Config{
|
|
||||||
DSN: "invalid-dsn",
|
|
||||||
MaxConnections: 10,
|
|
||||||
MaxIdleConns: 5,
|
|
||||||
}
|
|
||||||
|
|
||||||
client, err := NewClient(cfg)
|
|
||||||
if err == nil {
|
|
||||||
if client != nil {
|
|
||||||
_ = client.Close()
|
|
||||||
}
|
|
||||||
t.Error("Expected error for invalid DSN, got nil")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestNewClient_ValidConfig(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
// This test requires a real database connection
|
|
||||||
// Skip if DSN is not set
|
|
||||||
dsn := "postgres://goplt:goplt_password@localhost:5432/goplt?sslmode=disable"
|
|
||||||
if testing.Short() {
|
|
||||||
t.Skip("Skipping database test in short mode")
|
|
||||||
}
|
|
||||||
|
|
||||||
cfg := Config{
|
|
||||||
DSN: dsn,
|
|
||||||
MaxConnections: 10,
|
|
||||||
MaxIdleConns: 5,
|
|
||||||
ConnMaxLifetime: 5 * time.Minute,
|
|
||||||
ConnMaxIdleTime: 10 * time.Minute,
|
|
||||||
}
|
|
||||||
|
|
||||||
client, err := NewClient(cfg)
|
|
||||||
if err != nil {
|
|
||||||
t.Skipf("Skipping test - database not available: %v", err)
|
|
||||||
}
|
|
||||||
defer func() {
|
|
||||||
if err := client.Close(); err != nil {
|
|
||||||
t.Logf("Failed to close client: %v", err)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
if client == nil {
|
|
||||||
t.Fatal("Expected client, got nil")
|
|
||||||
}
|
|
||||||
|
|
||||||
if client.Client == nil {
|
|
||||||
t.Error("Expected Ent client, got nil")
|
|
||||||
}
|
|
||||||
|
|
||||||
if client.db == nil {
|
|
||||||
t.Error("Expected sql.DB, got nil")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestClient_Ping(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
dsn := "postgres://goplt:goplt_password@localhost:5432/goplt?sslmode=disable"
|
|
||||||
if testing.Short() {
|
|
||||||
t.Skip("Skipping database test in short mode")
|
|
||||||
}
|
|
||||||
|
|
||||||
cfg := Config{
|
|
||||||
DSN: dsn,
|
|
||||||
MaxConnections: 10,
|
|
||||||
MaxIdleConns: 5,
|
|
||||||
}
|
|
||||||
|
|
||||||
client, err := NewClient(cfg)
|
|
||||||
if err != nil {
|
|
||||||
t.Skipf("Skipping test - database not available: %v", err)
|
|
||||||
}
|
|
||||||
defer func() {
|
|
||||||
if err := client.Close(); err != nil {
|
|
||||||
t.Logf("Failed to close client: %v", err)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
||||||
defer cancel()
|
|
||||||
|
|
||||||
if err := client.Ping(ctx); err != nil {
|
|
||||||
t.Errorf("Ping failed: %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestClient_Close(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
dsn := "postgres://goplt:goplt_password@localhost:5432/goplt?sslmode=disable"
|
|
||||||
if testing.Short() {
|
|
||||||
t.Skip("Skipping database test in short mode")
|
|
||||||
}
|
|
||||||
|
|
||||||
cfg := Config{
|
|
||||||
DSN: dsn,
|
|
||||||
MaxConnections: 10,
|
|
||||||
MaxIdleConns: 5,
|
|
||||||
}
|
|
||||||
|
|
||||||
client, err := NewClient(cfg)
|
|
||||||
if err != nil {
|
|
||||||
t.Skipf("Skipping test - database not available: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
||||||
defer cancel()
|
|
||||||
|
|
||||||
if err := client.Close(); err != nil {
|
|
||||||
t.Errorf("Close failed: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Ping should fail after close
|
|
||||||
if err := client.Ping(ctx); err == nil {
|
|
||||||
t.Error("Expected Ping to fail after Close, got nil error")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestClient_DB(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
dsn := "postgres://goplt:goplt_password@localhost:5432/goplt?sslmode=disable"
|
|
||||||
if testing.Short() {
|
|
||||||
t.Skip("Skipping database test in short mode")
|
|
||||||
}
|
|
||||||
|
|
||||||
cfg := Config{
|
|
||||||
DSN: dsn,
|
|
||||||
MaxConnections: 10,
|
|
||||||
MaxIdleConns: 5,
|
|
||||||
}
|
|
||||||
|
|
||||||
client, err := NewClient(cfg)
|
|
||||||
if err != nil {
|
|
||||||
t.Skipf("Skipping test - database not available: %v", err)
|
|
||||||
}
|
|
||||||
defer func() {
|
|
||||||
if err := client.Close(); err != nil {
|
|
||||||
t.Logf("Failed to close client: %v", err)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
db := client.DB()
|
|
||||||
if db == nil {
|
|
||||||
t.Error("Expected sql.DB from DB(), got nil")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,4 +1,3 @@
|
|||||||
// Package metrics provides Prometheus metrics collection and instrumentation.
|
|
||||||
package metrics
|
package metrics
|
||||||
|
|
||||||
import (
|
import (
|
||||||
@@ -13,9 +12,9 @@ import (
|
|||||||
// Metrics holds all Prometheus metrics.
|
// Metrics holds all Prometheus metrics.
|
||||||
type Metrics struct {
|
type Metrics struct {
|
||||||
httpRequestDuration *prometheus.HistogramVec
|
httpRequestDuration *prometheus.HistogramVec
|
||||||
httpRequestTotal *prometheus.CounterVec
|
httpRequestTotal *prometheus.CounterVec
|
||||||
httpErrorsTotal *prometheus.CounterVec
|
httpErrorsTotal *prometheus.CounterVec
|
||||||
registry *prometheus.Registry
|
registry *prometheus.Registry
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewMetrics creates a new metrics registry with all metrics.
|
// NewMetrics creates a new metrics registry with all metrics.
|
||||||
@@ -95,3 +94,4 @@ func (m *Metrics) Handler() http.Handler {
|
|||||||
func (m *Metrics) Registry() *prometheus.Registry {
|
func (m *Metrics) Registry() *prometheus.Registry {
|
||||||
return m.registry
|
return m.registry
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,125 +0,0 @@
|
|||||||
package metrics
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net/http"
|
|
||||||
"net/http/httptest"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestNewMetrics(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
metrics := NewMetrics()
|
|
||||||
if metrics == nil {
|
|
||||||
t.Fatal("Expected metrics, got nil")
|
|
||||||
}
|
|
||||||
|
|
||||||
if metrics.registry == nil {
|
|
||||||
t.Error("Expected registry, got nil")
|
|
||||||
}
|
|
||||||
|
|
||||||
if metrics.httpRequestDuration == nil {
|
|
||||||
t.Error("Expected httpRequestDuration, got nil")
|
|
||||||
}
|
|
||||||
|
|
||||||
if metrics.httpRequestTotal == nil {
|
|
||||||
t.Error("Expected httpRequestTotal, got nil")
|
|
||||||
}
|
|
||||||
|
|
||||||
if metrics.httpErrorsTotal == nil {
|
|
||||||
t.Error("Expected httpErrorsTotal, got nil")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestMetrics_HTTPMiddleware(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
metrics := NewMetrics()
|
|
||||||
|
|
||||||
// Set Gin to test mode
|
|
||||||
gin.SetMode(gin.TestMode)
|
|
||||||
|
|
||||||
router := gin.New()
|
|
||||||
router.Use(metrics.HTTPMiddleware())
|
|
||||||
|
|
||||||
router.GET("/test", func(c *gin.Context) {
|
|
||||||
c.JSON(http.StatusOK, gin.H{"message": "test"})
|
|
||||||
})
|
|
||||||
|
|
||||||
req := httptest.NewRequest(http.MethodGet, "/test", nil)
|
|
||||||
w := httptest.NewRecorder()
|
|
||||||
|
|
||||||
router.ServeHTTP(w, req)
|
|
||||||
|
|
||||||
if w.Code != http.StatusOK {
|
|
||||||
t.Errorf("Expected status 200, got %d", w.Code)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Verify metrics were recorded
|
|
||||||
// We can't easily verify the internal metrics without exposing them,
|
|
||||||
// but we can verify the middleware doesn't panic
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestMetrics_HTTPMiddleware_Error(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
metrics := NewMetrics()
|
|
||||||
|
|
||||||
gin.SetMode(gin.TestMode)
|
|
||||||
|
|
||||||
router := gin.New()
|
|
||||||
router.Use(metrics.HTTPMiddleware())
|
|
||||||
|
|
||||||
router.GET("/error", func(c *gin.Context) {
|
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "test error"})
|
|
||||||
})
|
|
||||||
|
|
||||||
req := httptest.NewRequest(http.MethodGet, "/error", nil)
|
|
||||||
w := httptest.NewRecorder()
|
|
||||||
|
|
||||||
router.ServeHTTP(w, req)
|
|
||||||
|
|
||||||
if w.Code != http.StatusInternalServerError {
|
|
||||||
t.Errorf("Expected status 500, got %d", w.Code)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestMetrics_Handler(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
metrics := NewMetrics()
|
|
||||||
|
|
||||||
handler := metrics.Handler()
|
|
||||||
if handler == nil {
|
|
||||||
t.Error("Expected handler, got nil")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Test that the handler can be called
|
|
||||||
req := httptest.NewRequest(http.MethodGet, "/metrics", nil)
|
|
||||||
w := httptest.NewRecorder()
|
|
||||||
|
|
||||||
handler.ServeHTTP(w, req)
|
|
||||||
|
|
||||||
if w.Code != http.StatusOK {
|
|
||||||
t.Errorf("Expected status 200, got %d", w.Code)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Verify Prometheus format
|
|
||||||
body := w.Body.String()
|
|
||||||
// Prometheus handler may return empty body if no metrics are registered yet
|
|
||||||
// This is acceptable - we just verify the handler works
|
|
||||||
_ = body
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestMetrics_Registry(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
metrics := NewMetrics()
|
|
||||||
|
|
||||||
registry := metrics.Registry()
|
|
||||||
if registry == nil {
|
|
||||||
t.Error("Expected registry, got nil")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,4 +1,3 @@
|
|||||||
// Package observability provides OpenTelemetry tracing setup and configuration.
|
|
||||||
package observability
|
package observability
|
||||||
|
|
||||||
import (
|
import (
|
||||||
@@ -14,23 +13,22 @@ import (
|
|||||||
sdktrace "go.opentelemetry.io/otel/sdk/trace"
|
sdktrace "go.opentelemetry.io/otel/sdk/trace"
|
||||||
semconv "go.opentelemetry.io/otel/semconv/v1.26.0"
|
semconv "go.opentelemetry.io/otel/semconv/v1.26.0"
|
||||||
"go.opentelemetry.io/otel/trace"
|
"go.opentelemetry.io/otel/trace"
|
||||||
"go.opentelemetry.io/otel/trace/noop"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// Config holds OpenTelemetry configuration.
|
// Config holds OpenTelemetry configuration.
|
||||||
type Config struct {
|
type Config struct {
|
||||||
Enabled bool
|
Enabled bool
|
||||||
ServiceName string
|
ServiceName string
|
||||||
ServiceVersion string
|
ServiceVersion string
|
||||||
Environment string
|
Environment string
|
||||||
OTLPEndpoint string
|
OTLPEndpoint string
|
||||||
}
|
}
|
||||||
|
|
||||||
// InitTracer initializes OpenTelemetry tracing.
|
// InitTracer initializes OpenTelemetry tracing.
|
||||||
func InitTracer(ctx context.Context, cfg Config) (trace.TracerProvider, error) {
|
func InitTracer(ctx context.Context, cfg Config) (trace.TracerProvider, error) {
|
||||||
if !cfg.Enabled {
|
if !cfg.Enabled {
|
||||||
// Return a no-op tracer provider
|
// Return a no-op tracer provider
|
||||||
return noop.NewTracerProvider(), nil
|
return trace.NewNoopTracerProvider(), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create resource with service information
|
// Create resource with service information
|
||||||
@@ -93,3 +91,4 @@ func ShutdownTracer(ctx context.Context, tp trace.TracerProvider) error {
|
|||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,186 +0,0 @@
|
|||||||
package observability
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"go.opentelemetry.io/otel/trace"
|
|
||||||
"go.opentelemetry.io/otel/trace/noop"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestInitTracer_Disabled(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
cfg := Config{
|
|
||||||
Enabled: false,
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx := context.Background()
|
|
||||||
tp, err := InitTracer(ctx, cfg)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("InitTracer failed: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if tp == nil {
|
|
||||||
t.Fatal("Expected tracer provider, got nil")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestInitTracer_DevelopmentMode(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
cfg := Config{
|
|
||||||
Enabled: true,
|
|
||||||
ServiceName: "test-service",
|
|
||||||
ServiceVersion: "1.0.0",
|
|
||||||
Environment: "development",
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx := context.Background()
|
|
||||||
tp, err := InitTracer(ctx, cfg)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("InitTracer failed: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if tp == nil {
|
|
||||||
t.Fatal("Expected tracer provider, got nil")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Verify it's not a no-op tracer
|
|
||||||
if _, ok := tp.(*noop.TracerProvider); ok {
|
|
||||||
t.Error("Expected real tracer provider in development mode")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Clean up
|
|
||||||
if err := ShutdownTracer(ctx, tp); err != nil {
|
|
||||||
t.Logf("Failed to shutdown tracer: %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestInitTracer_ProductionMode_WithOTLP(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
cfg := Config{
|
|
||||||
Enabled: true,
|
|
||||||
ServiceName: "test-service",
|
|
||||||
ServiceVersion: "1.0.0",
|
|
||||||
Environment: "production",
|
|
||||||
OTLPEndpoint: "http://localhost:4318",
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx := context.Background()
|
|
||||||
tp, err := InitTracer(ctx, cfg)
|
|
||||||
if err != nil {
|
|
||||||
// OTLP endpoint might not be available in tests, that's okay
|
|
||||||
t.Skipf("Skipping test - OTLP endpoint not available: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if tp == nil {
|
|
||||||
t.Fatal("Expected tracer provider, got nil")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Clean up
|
|
||||||
if err := ShutdownTracer(ctx, tp); err != nil {
|
|
||||||
t.Logf("Failed to shutdown tracer: %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestInitTracer_ProductionMode_WithoutOTLP(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
cfg := Config{
|
|
||||||
Enabled: true,
|
|
||||||
ServiceName: "test-service",
|
|
||||||
ServiceVersion: "1.0.0",
|
|
||||||
Environment: "production",
|
|
||||||
OTLPEndpoint: "",
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx := context.Background()
|
|
||||||
tp, err := InitTracer(ctx, cfg)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("InitTracer failed: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if tp == nil {
|
|
||||||
t.Fatal("Expected tracer provider, got nil")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Clean up
|
|
||||||
if err := ShutdownTracer(ctx, tp); err != nil {
|
|
||||||
t.Logf("Failed to shutdown tracer: %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestShutdownTracer(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
cfg := Config{
|
|
||||||
Enabled: true,
|
|
||||||
ServiceName: "test-service",
|
|
||||||
ServiceVersion: "1.0.0",
|
|
||||||
Environment: "development",
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx := context.Background()
|
|
||||||
tp, err := InitTracer(ctx, cfg)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("InitTracer failed: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
||||||
defer cancel()
|
|
||||||
|
|
||||||
if err := ShutdownTracer(shutdownCtx, tp); err != nil {
|
|
||||||
t.Errorf("ShutdownTracer failed: %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestShutdownTracer_NoopTracer(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
tp := noop.NewTracerProvider()
|
|
||||||
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
||||||
defer cancel()
|
|
||||||
|
|
||||||
// Should not fail for no-op tracer
|
|
||||||
if err := ShutdownTracer(ctx, tp); err != nil {
|
|
||||||
t.Errorf("ShutdownTracer should handle no-op tracer gracefully: %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestInitTracer_InvalidResource(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
// This test would require invalid resource configuration
|
|
||||||
// Since resource.New doesn't have easy ways to fail, we'll skip this
|
|
||||||
// In practice, resource.New should always succeed with valid inputs
|
|
||||||
t.Skip("Skipping - resource.New doesn't easily fail with test inputs")
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestTracerProvider_ImplementsInterface(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
cfg := Config{
|
|
||||||
Enabled: true,
|
|
||||||
ServiceName: "test-service",
|
|
||||||
ServiceVersion: "1.0.0",
|
|
||||||
Environment: "development",
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx := context.Background()
|
|
||||||
tp, err := InitTracer(ctx, cfg)
|
|
||||||
if err != nil {
|
|
||||||
t.Skipf("Skipping test - tracer init failed: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Verify it implements the interface
|
|
||||||
var _ trace.TracerProvider = tp
|
|
||||||
|
|
||||||
// Clean up
|
|
||||||
if err := ShutdownTracer(ctx, tp); err != nil {
|
|
||||||
t.Logf("Failed to shutdown tracer: %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,4 +1,3 @@
|
|||||||
// Package server provides HTTP middleware functions for request processing.
|
|
||||||
package server
|
package server
|
||||||
|
|
||||||
import (
|
import (
|
||||||
@@ -7,17 +6,15 @@ import (
|
|||||||
"runtime"
|
"runtime"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"git.dcentral.systems/toolz/goplt/pkg/errorbus"
|
|
||||||
"git.dcentral.systems/toolz/goplt/pkg/logger"
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
|
"git.dcentral.systems/toolz/goplt/pkg/errorbus"
|
||||||
|
"git.dcentral.systems/toolz/goplt/pkg/logger"
|
||||||
)
|
)
|
||||||
|
|
||||||
type contextKey string
|
|
||||||
|
|
||||||
const (
|
const (
|
||||||
requestIDKey contextKey = "request_id"
|
requestIDKey = "request_id"
|
||||||
userIDKey contextKey = "user_id"
|
userIDKey = "user_id"
|
||||||
)
|
)
|
||||||
|
|
||||||
// RequestIDMiddleware generates a unique request ID for each request.
|
// RequestIDMiddleware generates a unique request ID for each request.
|
||||||
@@ -28,7 +25,7 @@ func RequestIDMiddleware() gin.HandlerFunc {
|
|||||||
requestID = uuid.New().String()
|
requestID = uuid.New().String()
|
||||||
}
|
}
|
||||||
|
|
||||||
c.Set(string(requestIDKey), requestID)
|
c.Set(requestIDKey, requestID)
|
||||||
c.Header("X-Request-ID", requestID)
|
c.Header("X-Request-ID", requestID)
|
||||||
c.Next()
|
c.Next()
|
||||||
}
|
}
|
||||||
@@ -48,7 +45,7 @@ func LoggingMiddleware(log logger.Logger) gin.HandlerFunc {
|
|||||||
duration := time.Since(start)
|
duration := time.Since(start)
|
||||||
|
|
||||||
// Get request ID from context
|
// Get request ID from context
|
||||||
requestID, _ := c.Get(string(requestIDKey))
|
requestID, _ := c.Get(requestIDKey)
|
||||||
requestIDStr := ""
|
requestIDStr := ""
|
||||||
if id, ok := requestID.(string); ok {
|
if id, ok := requestID.(string); ok {
|
||||||
requestIDStr = id
|
requestIDStr = id
|
||||||
@@ -77,8 +74,8 @@ func PanicRecoveryMiddleware(errorBus errorbus.ErrorPublisher) gin.HandlerFunc {
|
|||||||
stack = stack[:n]
|
stack = stack[:n]
|
||||||
|
|
||||||
// Get request ID from context
|
// Get request ID from context
|
||||||
requestID, _ := c.Get(string(requestIDKey))
|
requestID, _ := c.Get(requestIDKey)
|
||||||
ctx := context.WithValue(context.Background(), requestIDKey, requestID)
|
ctx := context.WithValue(context.Background(), "request_id", requestID)
|
||||||
|
|
||||||
// Create error
|
// Create error
|
||||||
var panicErr error
|
var panicErr error
|
||||||
@@ -141,3 +138,4 @@ func TimeoutMiddleware(timeout time.Duration) gin.HandlerFunc {
|
|||||||
c.Next()
|
c.Next()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,259 +0,0 @@
|
|||||||
package server
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"errors"
|
|
||||||
"net/http"
|
|
||||||
"net/http/httptest"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"git.dcentral.systems/toolz/goplt/pkg/logger"
|
|
||||||
"github.com/gin-gonic/gin"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestRequestIDMiddleware(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
gin.SetMode(gin.TestMode)
|
|
||||||
|
|
||||||
router := gin.New()
|
|
||||||
router.Use(RequestIDMiddleware())
|
|
||||||
|
|
||||||
router.GET("/test", func(c *gin.Context) {
|
|
||||||
requestID, exists := c.Get(string(requestIDKey))
|
|
||||||
if !exists {
|
|
||||||
t.Error("Expected request ID in context")
|
|
||||||
}
|
|
||||||
if requestID == nil || requestID == "" {
|
|
||||||
t.Error("Expected non-empty request ID")
|
|
||||||
}
|
|
||||||
c.JSON(http.StatusOK, gin.H{"request_id": requestID})
|
|
||||||
})
|
|
||||||
|
|
||||||
req := httptest.NewRequest(http.MethodGet, "/test", nil)
|
|
||||||
w := httptest.NewRecorder()
|
|
||||||
|
|
||||||
router.ServeHTTP(w, req)
|
|
||||||
|
|
||||||
if w.Code != http.StatusOK {
|
|
||||||
t.Errorf("Expected status 200, got %d", w.Code)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Verify X-Request-ID header is set
|
|
||||||
if w.Header().Get("X-Request-ID") == "" {
|
|
||||||
t.Error("Expected X-Request-ID header")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestRequestIDMiddleware_ExistingHeader(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
gin.SetMode(gin.TestMode)
|
|
||||||
|
|
||||||
router := gin.New()
|
|
||||||
router.Use(RequestIDMiddleware())
|
|
||||||
|
|
||||||
router.GET("/test", func(c *gin.Context) {
|
|
||||||
c.JSON(http.StatusOK, gin.H{"ok": true})
|
|
||||||
})
|
|
||||||
|
|
||||||
req := httptest.NewRequest(http.MethodGet, "/test", nil)
|
|
||||||
req.Header.Set("X-Request-ID", "existing-id")
|
|
||||||
w := httptest.NewRecorder()
|
|
||||||
|
|
||||||
router.ServeHTTP(w, req)
|
|
||||||
|
|
||||||
if w.Header().Get("X-Request-ID") != "existing-id" {
|
|
||||||
t.Errorf("Expected existing request ID, got %s", w.Header().Get("X-Request-ID"))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestLoggingMiddleware(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
gin.SetMode(gin.TestMode)
|
|
||||||
|
|
||||||
mockLogger := &mockLogger{}
|
|
||||||
router := gin.New()
|
|
||||||
router.Use(RequestIDMiddleware())
|
|
||||||
router.Use(LoggingMiddleware(mockLogger))
|
|
||||||
|
|
||||||
router.GET("/test", func(c *gin.Context) {
|
|
||||||
c.JSON(http.StatusOK, gin.H{"message": "test"})
|
|
||||||
})
|
|
||||||
|
|
||||||
req := httptest.NewRequest(http.MethodGet, "/test", nil)
|
|
||||||
w := httptest.NewRecorder()
|
|
||||||
|
|
||||||
router.ServeHTTP(w, req)
|
|
||||||
|
|
||||||
if w.Code != http.StatusOK {
|
|
||||||
t.Errorf("Expected status 200, got %d", w.Code)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Verify logging was called
|
|
||||||
if len(mockLogger.infoLogs) == 0 {
|
|
||||||
t.Error("Expected info log to be called")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestPanicRecoveryMiddleware(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
gin.SetMode(gin.TestMode)
|
|
||||||
|
|
||||||
mockErrorBus := &mockErrorBusMiddleware{}
|
|
||||||
|
|
||||||
router := gin.New()
|
|
||||||
router.Use(PanicRecoveryMiddleware(mockErrorBus))
|
|
||||||
|
|
||||||
router.GET("/panic", func(c *gin.Context) {
|
|
||||||
panic("test panic")
|
|
||||||
})
|
|
||||||
|
|
||||||
req := httptest.NewRequest(http.MethodGet, "/panic", nil)
|
|
||||||
w := httptest.NewRecorder()
|
|
||||||
|
|
||||||
router.ServeHTTP(w, req)
|
|
||||||
|
|
||||||
if w.Code != http.StatusInternalServerError {
|
|
||||||
t.Errorf("Expected status 500, got %d", w.Code)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Verify error was published to error bus
|
|
||||||
if len(mockErrorBus.errors) == 0 {
|
|
||||||
t.Error("Expected error to be published to error bus")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestPanicRecoveryMiddleware_ErrorPanic(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
gin.SetMode(gin.TestMode)
|
|
||||||
|
|
||||||
mockErrorBus := &mockErrorBusMiddleware{}
|
|
||||||
|
|
||||||
router := gin.New()
|
|
||||||
router.Use(PanicRecoveryMiddleware(mockErrorBus))
|
|
||||||
|
|
||||||
router.GET("/panic-error", func(c *gin.Context) {
|
|
||||||
panic(errors.New("test error"))
|
|
||||||
})
|
|
||||||
|
|
||||||
req := httptest.NewRequest(http.MethodGet, "/panic-error", nil)
|
|
||||||
w := httptest.NewRecorder()
|
|
||||||
|
|
||||||
router.ServeHTTP(w, req)
|
|
||||||
|
|
||||||
if w.Code != http.StatusInternalServerError {
|
|
||||||
t.Errorf("Expected status 500, got %d", w.Code)
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(mockErrorBus.errors) == 0 {
|
|
||||||
t.Error("Expected error to be published to error bus")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestCORSMiddleware(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
gin.SetMode(gin.TestMode)
|
|
||||||
|
|
||||||
router := gin.New()
|
|
||||||
router.Use(CORSMiddleware())
|
|
||||||
|
|
||||||
router.GET("/test", func(c *gin.Context) {
|
|
||||||
c.JSON(http.StatusOK, gin.H{"message": "test"})
|
|
||||||
})
|
|
||||||
|
|
||||||
req := httptest.NewRequest(http.MethodGet, "/test", nil)
|
|
||||||
w := httptest.NewRecorder()
|
|
||||||
|
|
||||||
router.ServeHTTP(w, req)
|
|
||||||
|
|
||||||
// Verify CORS headers
|
|
||||||
if w.Header().Get("Access-Control-Allow-Origin") != "*" {
|
|
||||||
t.Error("Expected CORS header Access-Control-Allow-Origin")
|
|
||||||
}
|
|
||||||
|
|
||||||
if w.Header().Get("Access-Control-Allow-Credentials") != "true" {
|
|
||||||
t.Error("Expected CORS header Access-Control-Allow-Credentials")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestCORSMiddleware_OPTIONS(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
gin.SetMode(gin.TestMode)
|
|
||||||
|
|
||||||
router := gin.New()
|
|
||||||
router.Use(CORSMiddleware())
|
|
||||||
|
|
||||||
router.GET("/test", func(c *gin.Context) {
|
|
||||||
c.JSON(http.StatusOK, gin.H{"message": "test"})
|
|
||||||
})
|
|
||||||
|
|
||||||
req := httptest.NewRequest(http.MethodOptions, "/test", nil)
|
|
||||||
w := httptest.NewRecorder()
|
|
||||||
|
|
||||||
router.ServeHTTP(w, req)
|
|
||||||
|
|
||||||
if w.Code != http.StatusNoContent {
|
|
||||||
t.Errorf("Expected status 204 for OPTIONS, got %d", w.Code)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestTimeoutMiddleware(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
gin.SetMode(gin.TestMode)
|
|
||||||
|
|
||||||
router := gin.New()
|
|
||||||
router.Use(TimeoutMiddleware(100 * time.Millisecond))
|
|
||||||
|
|
||||||
router.GET("/test", func(c *gin.Context) {
|
|
||||||
c.JSON(http.StatusOK, gin.H{"message": "test"})
|
|
||||||
})
|
|
||||||
|
|
||||||
req := httptest.NewRequest(http.MethodGet, "/test", nil)
|
|
||||||
w := httptest.NewRecorder()
|
|
||||||
|
|
||||||
router.ServeHTTP(w, req)
|
|
||||||
|
|
||||||
if w.Code != http.StatusOK {
|
|
||||||
t.Errorf("Expected status 200, got %d", w.Code)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// mockLogger implements logger.Logger for testing.
|
|
||||||
type mockLogger struct {
|
|
||||||
infoLogs []string
|
|
||||||
errors []string
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *mockLogger) Debug(msg string, fields ...logger.Field) {}
|
|
||||||
func (m *mockLogger) Info(msg string, fields ...logger.Field) {
|
|
||||||
m.infoLogs = append(m.infoLogs, msg)
|
|
||||||
}
|
|
||||||
func (m *mockLogger) Warn(msg string, fields ...logger.Field) {}
|
|
||||||
func (m *mockLogger) Error(msg string, fields ...logger.Field) {
|
|
||||||
m.errors = append(m.errors, msg)
|
|
||||||
}
|
|
||||||
func (m *mockLogger) With(fields ...logger.Field) logger.Logger {
|
|
||||||
return m
|
|
||||||
}
|
|
||||||
func (m *mockLogger) WithContext(ctx context.Context) logger.Logger {
|
|
||||||
return m
|
|
||||||
}
|
|
||||||
|
|
||||||
// mockErrorBusMiddleware implements errorbus.ErrorPublisher for testing middleware.
|
|
||||||
type mockErrorBusMiddleware struct {
|
|
||||||
errors []error
|
|
||||||
ctxs []context.Context
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *mockErrorBusMiddleware) Publish(ctx context.Context, err error) {
|
|
||||||
m.errors = append(m.errors, err)
|
|
||||||
m.ctxs = append(m.ctxs, ctx)
|
|
||||||
}
|
|
||||||
@@ -1,290 +0,0 @@
|
|||||||
package server
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"net/http"
|
|
||||||
"net/http/httptest"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"git.dcentral.systems/toolz/goplt/internal/health"
|
|
||||||
"git.dcentral.systems/toolz/goplt/internal/metrics"
|
|
||||||
"github.com/gin-gonic/gin"
|
|
||||||
"go.opentelemetry.io/otel/trace/noop"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestNewServer(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
mockConfig := &mockConfigProvider{
|
|
||||||
values: map[string]any{
|
|
||||||
"environment": "test",
|
|
||||||
"server.port": 8080,
|
|
||||||
"server.host": "127.0.0.1",
|
|
||||||
"server.read_timeout": "30s",
|
|
||||||
"server.write_timeout": "30s",
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
mockLogger := &mockLogger{}
|
|
||||||
healthRegistry := health.NewRegistry()
|
|
||||||
metricsRegistry := metrics.NewMetrics()
|
|
||||||
mockErrorBus := &mockErrorBusServer{}
|
|
||||||
tracer := noop.NewTracerProvider()
|
|
||||||
|
|
||||||
srv, err := NewServer(mockConfig, mockLogger, healthRegistry, metricsRegistry, mockErrorBus, tracer)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("Failed to create server: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if srv == nil {
|
|
||||||
t.Fatal("Expected server, got nil")
|
|
||||||
}
|
|
||||||
|
|
||||||
if srv.httpServer == nil {
|
|
||||||
t.Error("Expected http server, got nil")
|
|
||||||
}
|
|
||||||
|
|
||||||
if srv.router == nil {
|
|
||||||
t.Error("Expected router, got nil")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestNewServer_DefaultValues(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
mockConfig := &mockConfigProvider{
|
|
||||||
values: map[string]any{
|
|
||||||
"environment": "test",
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
mockLogger := &mockLogger{}
|
|
||||||
healthRegistry := health.NewRegistry()
|
|
||||||
metricsRegistry := metrics.NewMetrics()
|
|
||||||
mockErrorBus := &mockErrorBusServer{}
|
|
||||||
tracer := noop.NewTracerProvider()
|
|
||||||
|
|
||||||
srv, err := NewServer(mockConfig, mockLogger, healthRegistry, metricsRegistry, mockErrorBus, tracer)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("Failed to create server: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if srv.httpServer.Addr != "0.0.0.0:8080" {
|
|
||||||
t.Errorf("Expected default address 0.0.0.0:8080, got %s", srv.httpServer.Addr)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestServer_Router(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
mockConfig := &mockConfigProvider{
|
|
||||||
values: map[string]any{
|
|
||||||
"environment": "test",
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
mockLogger := &mockLogger{}
|
|
||||||
healthRegistry := health.NewRegistry()
|
|
||||||
metricsRegistry := metrics.NewMetrics()
|
|
||||||
mockErrorBus := &mockErrorBusServer{}
|
|
||||||
tracer := noop.NewTracerProvider()
|
|
||||||
|
|
||||||
srv, err := NewServer(mockConfig, mockLogger, healthRegistry, metricsRegistry, mockErrorBus, tracer)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("Failed to create server: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
router := srv.Router()
|
|
||||||
if router == nil {
|
|
||||||
t.Error("Expected router, got nil")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestServer_Shutdown(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
mockConfig := &mockConfigProvider{
|
|
||||||
values: map[string]any{
|
|
||||||
"environment": "test",
|
|
||||||
"server.port": 0, // Use random port
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
mockLogger := &mockLogger{}
|
|
||||||
healthRegistry := health.NewRegistry()
|
|
||||||
metricsRegistry := metrics.NewMetrics()
|
|
||||||
mockErrorBus := &mockErrorBusServer{}
|
|
||||||
tracer := noop.NewTracerProvider()
|
|
||||||
|
|
||||||
srv, err := NewServer(mockConfig, mockLogger, healthRegistry, metricsRegistry, mockErrorBus, tracer)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("Failed to create server: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Start server in background
|
|
||||||
go func() {
|
|
||||||
_ = srv.Start()
|
|
||||||
}()
|
|
||||||
|
|
||||||
// Wait a bit for server to start
|
|
||||||
time.Sleep(100 * time.Millisecond)
|
|
||||||
|
|
||||||
// Shutdown
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
||||||
defer cancel()
|
|
||||||
|
|
||||||
if err := srv.Shutdown(ctx); err != nil {
|
|
||||||
t.Errorf("Shutdown failed: %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestServer_HealthEndpoints(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
gin.SetMode(gin.TestMode)
|
|
||||||
|
|
||||||
mockConfig := &mockConfigProvider{
|
|
||||||
values: map[string]any{
|
|
||||||
"environment": "test",
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
mockLogger := &mockLogger{}
|
|
||||||
healthRegistry := health.NewRegistry()
|
|
||||||
metricsRegistry := metrics.NewMetrics()
|
|
||||||
mockErrorBus := &mockErrorBusServer{}
|
|
||||||
tracer := noop.NewTracerProvider()
|
|
||||||
|
|
||||||
srv, err := NewServer(mockConfig, mockLogger, healthRegistry, metricsRegistry, mockErrorBus, tracer)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("Failed to create server: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Test /healthz endpoint
|
|
||||||
req := httptest.NewRequest(http.MethodGet, "/healthz", nil)
|
|
||||||
w := httptest.NewRecorder()
|
|
||||||
srv.router.ServeHTTP(w, req)
|
|
||||||
|
|
||||||
if w.Code != http.StatusOK {
|
|
||||||
t.Errorf("Expected status 200 for /healthz, got %d", w.Code)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Test /ready endpoint
|
|
||||||
req = httptest.NewRequest(http.MethodGet, "/ready", nil)
|
|
||||||
w = httptest.NewRecorder()
|
|
||||||
srv.router.ServeHTTP(w, req)
|
|
||||||
|
|
||||||
if w.Code != http.StatusOK {
|
|
||||||
t.Errorf("Expected status 200 for /ready, got %d", w.Code)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestServer_MetricsEndpoint(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
gin.SetMode(gin.TestMode)
|
|
||||||
|
|
||||||
mockConfig := &mockConfigProvider{
|
|
||||||
values: map[string]any{
|
|
||||||
"environment": "test",
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
mockLogger := &mockLogger{}
|
|
||||||
healthRegistry := health.NewRegistry()
|
|
||||||
metricsRegistry := metrics.NewMetrics()
|
|
||||||
mockErrorBus := &mockErrorBusServer{}
|
|
||||||
tracer := noop.NewTracerProvider()
|
|
||||||
|
|
||||||
srv, err := NewServer(mockConfig, mockLogger, healthRegistry, metricsRegistry, mockErrorBus, tracer)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("Failed to create server: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
req := httptest.NewRequest(http.MethodGet, "/metrics", nil)
|
|
||||||
w := httptest.NewRecorder()
|
|
||||||
srv.router.ServeHTTP(w, req)
|
|
||||||
|
|
||||||
if w.Code != http.StatusOK {
|
|
||||||
t.Errorf("Expected status 200 for /metrics, got %d", w.Code)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Prometheus handler may return empty body if no metrics are recorded yet
|
|
||||||
// This is acceptable - we just verify the endpoint works
|
|
||||||
_ = w.Body.String()
|
|
||||||
}
|
|
||||||
|
|
||||||
// mockConfigProvider implements config.ConfigProvider for testing.
|
|
||||||
type mockConfigProvider struct {
|
|
||||||
values map[string]any
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *mockConfigProvider) Get(key string) any {
|
|
||||||
return m.values[key]
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *mockConfigProvider) GetString(key string) string {
|
|
||||||
if val, ok := m.values[key].(string); ok {
|
|
||||||
return val
|
|
||||||
}
|
|
||||||
if val, ok := m.values[key]; ok {
|
|
||||||
return val.(string)
|
|
||||||
}
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *mockConfigProvider) GetInt(key string) int {
|
|
||||||
if val, ok := m.values[key].(int); ok {
|
|
||||||
return val
|
|
||||||
}
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *mockConfigProvider) GetBool(key string) bool {
|
|
||||||
if val, ok := m.values[key].(bool); ok {
|
|
||||||
return val
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *mockConfigProvider) GetDuration(key string) time.Duration {
|
|
||||||
if val, ok := m.values[key].(string); ok {
|
|
||||||
dur, err := time.ParseDuration(val)
|
|
||||||
if err == nil {
|
|
||||||
return dur
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if val, ok := m.values[key].(time.Duration); ok {
|
|
||||||
return val
|
|
||||||
}
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *mockConfigProvider) GetStringSlice(key string) []string {
|
|
||||||
if val, ok := m.values[key].([]string); ok {
|
|
||||||
return val
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *mockConfigProvider) IsSet(key string) bool {
|
|
||||||
_, ok := m.values[key]
|
|
||||||
return ok
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *mockConfigProvider) Unmarshal(v any) error {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Note: mockLogger and mockErrorBusMiddleware are defined in middleware_test.go
|
|
||||||
// We use mockErrorBusServer here to avoid conflicts
|
|
||||||
type mockErrorBusServer struct {
|
|
||||||
errors []error
|
|
||||||
ctxs []context.Context
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *mockErrorBusServer) Publish(ctx context.Context, err error) {
|
|
||||||
m.errors = append(m.errors, err)
|
|
||||||
m.ctxs = append(m.ctxs, ctx)
|
|
||||||
}
|
|
||||||
@@ -1,4 +1,3 @@
|
|||||||
// Package errorbus provides interfaces for error publishing and handling.
|
|
||||||
package errorbus
|
package errorbus
|
||||||
|
|
||||||
import (
|
import (
|
||||||
@@ -19,3 +18,4 @@ type ErrorContext struct {
|
|||||||
Component string
|
Component string
|
||||||
Metadata map[string]interface{}
|
Metadata map[string]interface{}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
// Package health provides interfaces and types for health checking.
|
|
||||||
package health
|
package health
|
||||||
|
|
||||||
import "context"
|
import "context"
|
||||||
@@ -32,3 +31,4 @@ type HealthStatus struct {
|
|||||||
Status Status `json:"status"`
|
Status Status `json:"status"`
|
||||||
Components []ComponentStatus `json:"components,omitempty"`
|
Components []ComponentStatus `json:"components,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user