{"id":29878272,"url":"https://github.com/sinashahoveisi/featureflags","last_synced_at":"2025-07-31T07:03:42.507Z","repository":{"id":306495060,"uuid":"1026377678","full_name":"sinashahoveisi/featureflags","owner":"sinashahoveisi","description":"A robust backend service for managing feature flags with dependency support, audit logging, and circular dependency detection.","archived":false,"fork":false,"pushed_at":"2025-07-25T22:41:52.000Z","size":67,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-07-26T03:25:31.569Z","etag":null,"topics":["feature-flag","feature-flagging","go","golang"],"latest_commit_sha":null,"homepage":"","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/sinashahoveisi.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2025-07-25T19:28:36.000Z","updated_at":"2025-07-25T22:41:56.000Z","dependencies_parsed_at":"2025-07-26T03:25:57.888Z","dependency_job_id":"e49165f3-e82a-41e6-af52-4fe9df1fb260","html_url":"https://github.com/sinashahoveisi/featureflags","commit_stats":null,"previous_names":["sinashahoveisi/featureflags"],"tags_count":null,"template":false,"template_full_name":null,"purl":"pkg:github/sinashahoveisi/featureflags","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sinashahoveisi%2Ffeatureflags","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sinashahoveisi%2Ffeatureflags/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sinashahoveisi%2Ffeatureflags/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sinashahoveisi%2Ffeatureflags/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/sinashahoveisi","download_url":"https://codeload.github.com/sinashahoveisi/featureflags/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sinashahoveisi%2Ffeatureflags/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":268003449,"owners_count":24179290,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-07-31T02:00:08.723Z","response_time":66,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["feature-flag","feature-flagging","go","golang"],"created_at":"2025-07-31T07:01:42.104Z","updated_at":"2025-07-31T07:03:42.490Z","avatar_url":"https://github.com/sinashahoveisi.png","language":"Go","funding_links":[],"categories":[],"sub_categories":[],"readme":"# FeatureFlags Service\n\nA robust backend service for managing feature flags with dependency support, audit logging, and circular dependency detection.\n\n## Features\n\n- ✅ **Feature Flag Management**: Create, enable, disable, and list feature flags\n- ✅ **Dependency Support**: Flags can depend on other flags; dependent flags can only be enabled if all dependencies are active\n- ✅ **Circular Dependency Detection**: Prevents creation of circular dependencies\n- ✅ **Cascading Disables**: When a flag is disabled, all dependent flags are automatically disabled\n- ✅ **Comprehensive Audit Logging**: Track all operations with timestamps, actors, and reasons\n- ✅ **Graceful Shutdown**: Clean shutdown with configurable timeout\n- ✅ **Structured Logging**: JSON-structured logs with configurable levels\n- ✅ **Input Validation**: Comprehensive request validation with detailed error messages\n- ✅ **Database Migrations**: Automated database schema management\n- ✅ **Docker Support**: Fully containerized with Docker Compose\n- ✅ **Comprehensive Tests**: Unit and integration tests with coverage reporting\n- ✅ **Swagger Documentation**: Interactive API documentation with configurable enable/disable\n\n## Architecture\n\nThe project follows a clean architecture pattern with clear separation of concerns:\n\n```\nfeatureflags/\n├── cmd/                    # Application entry point\n├── config/                 # Configuration management\n├── entity/                 # Domain models\n├── repository/             # Data access layer\n├── service/                # Business logic layer\n├── controller/             # HTTP handlers\n├── handler/                # Route registration\n├── validator/              # Input validation\n├── test/                   # Test helpers\n├── migrations/             # Database migrations\n├── pkg/\n│   └── logger/            # Structured logging\n├── scripts/               # Utility scripts\n└── docker-compose.yml     # Container orchestration\n```\n\n## API Endpoints\n\n### Health Check\n- `GET /health` - Service health status\n\n### Documentation\n- `GET /swagger/index.html` - Interactive Swagger API documentation (if enabled)\n\n### Flag Management\n- `POST /api/v1/flags` - Create a new flag\n- `GET /api/v1/flags` - List all flags\n- `GET /api/v1/flags/:id` - Get a specific flag\n- `POST /api/v1/flags/:id/toggle` - Enable/disable a flag\n- `GET /api/v1/flags/:id/audit` - Get audit logs for a flag\n\n## Example API Usage\n\n### Create a Flag\n```bash\ncurl -X POST http://localhost:8080/api/v1/flags \\\n  -H \"Content-Type: application/json\" \\\n  -H \"X-Actor: user123\" \\\n  -d '{\n    \"name\": \"checkout_v2\",\n    \"dependencies\": [1, 2]\n  }'\n```\n\n### Enable a Flag\n```bash\ncurl -X POST http://localhost:8080/api/v1/flags/1/toggle \\\n  -H \"Content-Type: application/json\" \\\n  -H \"X-Actor: user123\" \\\n  -d '{\n    \"enable\": true,\n    \"reason\": \"Ready for production\"\n  }'\n```\n\n### Error Response for Missing Dependencies\n```json\n{\n  \"error\": \"Missing active dependencies\",\n  \"missing_dependencies\": [\"auth_v2\", \"user_profile_v2\"]\n}\n```\n\n## Configuration\n\nThe service supports configuration via environment variables:\n\n| Variable | Default | Description |\n|----------|---------|-------------|\n| `HTTP_SERVER_PORT` | `8080` | HTTP server port |\n| `DATABASE_HOST` | `db` | PostgreSQL host |\n| `DATABASE_PORT` | `5432` | PostgreSQL port |\n| `DATABASE_USER` | `featureflags` | Database user |\n| `DATABASE_PASSWORD` | `featureflags` | Database password |\n| `DATABASE_NAME` | `featureflags` | Database name |\n| `LOGGER_LEVEL` | `info` | Log level (debug, info, warn, error) |\n| `LOGGER_MODE` | `production` | Log mode (development, production) |\n| `APPLICATION_GRACEFUL_SHUTDOWN_TIMEOUT` | `30s` | Graceful shutdown timeout |\n| `SWAGGER_ENABLED` | `true` | Enable/disable Swagger documentation |\n\n## Running the Service\n\n### Using Docker Compose (Recommended)\n\n1. **Start the service:**\n   ```bash\n   docker-compose up --build\n   ```\n\n2. **Run tests:**\n   ```bash\n   docker-compose run --rm test\n   ```\n\n3. **Stop the service:**\n   ```bash\n   docker-compose down\n   ```\n\n### Development with Hot Reload\n\nFor the best development experience, use the development environment with hot reload:\n\n```bash\n# Start development environment (recommended)\nmake dev\n# or\n./scripts/dev.sh\n\n# The service will be available at:\n# - API: http://localhost:8080\n# - Swagger: http://localhost:8080/swagger/index.html\n```\n\n**Development Features:**\n- 🔥 **Hot Reload**: Automatic restart on code changes using [Air](https://github.com/cosmtrek/air)\n- 🐛 **Debug Logging**: Enhanced logging for development\n- 📚 **Swagger Enabled**: Interactive API documentation\n- 🗄️ **PostgreSQL Included**: Database automatically configured\n- 📁 **Live Code Mounting**: Edit code directly, see changes instantly\n\n**Development Commands:**\n```bash\nmake dev          # Start development environment\nmake dev-bg       # Start in background\nmake dev-logs     # View logs\nmake dev-stop     # Stop development environment\nmake dev-test     # Run tests in dev environment\n```\n\n### Local Development (Alternative)\n\nIf you prefer to run without Docker:\n\n1. **Prerequisites:**\n   - Go 1.23+\n   - PostgreSQL 15+\n   - Air (for hot reload): `make install-air`\n\n2. **Setup database:**\n   ```bash\n   createdb featureflags\n   ```\n\n3. **Run with hot reload:**\n   ```bash\n   make air-local\n   ```\n\n4. **Or run normally:**\n   ```bash\n   make run\n   ```\n\n## Testing\n\nThe project includes comprehensive automated tests covering all core functionality and example scenarios from the requirements:\n\n### Running Tests\n\n```bash\n# Run all tests with Docker Compose\ndocker-compose run --rm test\n\n# Run example scenario tests\ndocker-compose run --rm scenario-test\n\n# Run tests locally (requires PostgreSQL)\n./scripts/test.sh\n\n# Run scenario tests locally\n./scripts/run-scenario-tests.sh\n\n# Run specific test suites\ngo test -v ./service/...                    # Service layer unit tests\ngo test -v ./test/...                       # Integration tests\ngo test -v -run \"TestExampleScenario\" ./test/  # Example scenarios only\n```\n\n### Example Scenarios Tested\n\nThe test suite validates all example scenarios from the requirements:\n\n1. **Scenario 1: Dependency Validation**\n   - `checkout_v2` depends on `auth_v2` and `user_profile_v2`\n   - Can only be enabled after both dependencies are active\n\n2. **Scenario 2: Missing Dependency Error Format**\n   - Returns exact error format: `{\"error\": \"Missing active dependencies\", \"missing_dependencies\": [\"auth_v2\"]}`\n\n3. **Scenario 3: Cascading Disable**\n   - When `auth_v2` is disabled, automatically disables `checkout_v2` and dependent flags\n   - Logs cascading changes with `system` actor and `cascade_disable` action\n\n4. **Scenario 4: Circular Dependency Detection**\n   - Prevents creation of flags with circular dependencies\n   - Returns clear error messages for circular dependency attempts\n\n5. **Complex Integration Scenario**\n   - Multi-service dependency tree with 7+ flags\n   - Tests realistic microservice dependency patterns\n   - Validates cascading behavior across complex dependency chains\n\n### Test Coverage\n\nTests cover the following functionality:\n- ✅ Flag creation with and without dependencies\n- ✅ Dependency validation and missing dependency errors\n- ✅ Cascading disable functionality with audit logging\n- ✅ Circular dependency detection and prevention\n- ✅ Flag toggling and status management\n- ✅ Audit log creation and retrieval\n- ✅ Input validation and error handling\n- ✅ Database operations and transactions\n- ✅ HTTP API endpoints and error responses\n- ✅ Integration testing with full application stack\n\n### CI/CD Testing\n\nThe project includes automated testing in both GitLab CI and GitHub Actions:\n- **Unit Tests**: Run on every commit and pull request\n- **Integration Tests**: Full application testing with PostgreSQL\n- **Scenario Tests**: Validate all requirement examples\n- **Security Scanning**: Vulnerability detection with Trivy\n- **Coverage Reports**: Generate and upload test coverage\n- **Docker Image Testing**: Test built images before deployment\n\n## Database Schema\n\nThe service uses PostgreSQL with the following tables:\n\n- **flags**: Store flag information (id, name, status, timestamps)\n- **flag_dependencies**: Store flag dependency relationships\n- **audit_logs**: Store audit trail of all operations\n- **schema_migrations**: Track applied database migrations\n\n## Graceful Shutdown\n\nThe service implements graceful shutdown:\n- Listens for SIGTERM/SIGINT signals\n- Stops accepting new requests\n- Completes existing requests within timeout\n- Closes database connections cleanly\n\n## Logging\n\nStructured JSON logging with configurable levels:\n- **Development mode**: Human-readable format with colors\n- **Production mode**: JSON format optimized for log aggregation\n- **Request logging**: Automatic HTTP request/response logging\n- **Error tracking**: Detailed error context and stack traces\n\n## Example Scenarios\n\n### Scenario 1: Basic Flag Management\n```bash\n# Create a simple flag\ncurl -X POST localhost:8080/api/v1/flags \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"name\": \"simple_feature\"}'\n\n# Enable the flag\ncurl -X POST localhost:8080/api/v1/flags/1/toggle \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"enable\": true, \"reason\": \"Feature is ready\"}'\n```\n\n### Scenario 2: Dependency Management\n```bash\n# Create base flags\ncurl -X POST localhost:8080/api/v1/flags \\\n  -d '{\"name\": \"auth_v2\"}'\ncurl -X POST localhost:8080/api/v1/flags \\\n  -d '{\"name\": \"user_profile_v2\"}'\n\n# Create dependent flag\ncurl -X POST localhost:8080/api/v1/flags \\\n  -d '{\"name\": \"checkout_v2\", \"dependencies\": [1, 2]}'\n\n# Try to enable checkout_v2 (will fail - dependencies not enabled)\ncurl -X POST localhost:8080/api/v1/flags/3/toggle \\\n  -d '{\"enable\": true, \"reason\": \"Launch checkout v2\"}'\n# Response: {\"error\": \"Missing active dependencies\", \"missing_dependencies\": [\"auth_v2\", \"user_profile_v2\"]}\n\n# Enable dependencies first\ncurl -X POST localhost:8080/api/v1/flags/1/toggle \\\n  -d '{\"enable\": true, \"reason\": \"Auth v2 ready\"}'\ncurl -X POST localhost:8080/api/v1/flags/2/toggle \\\n  -d '{\"enable\": true, \"reason\": \"User profile ready\"}'\n\n# Now enable checkout_v2 (will succeed)\ncurl -X POST localhost:8080/api/v1/flags/3/toggle \\\n  -d '{\"enable\": true, \"reason\": \"All dependencies ready\"}'\n```\n\n### Scenario 3: Cascade Disable\n```bash\n# Disable auth_v2 (will cascade disable checkout_v2)\ncurl -X POST localhost:8080/api/v1/flags/1/toggle \\\n  -d '{\"enable\": false, \"reason\": \"Auth issues detected\"}'\n\n# Check audit logs to see cascade actions\ncurl localhost:8080/api/v1/flags/3/audit\n```\n\n## Development\n\n### Adding New Features\n\n1. **Add entity models** in `entity/`\n2. **Implement repository methods** in `repository/`\n3. **Add business logic** in `service/`\n4. **Create HTTP handlers** in `controller/`\n5. **Add validation** in `validator/`\n6. **Write tests** in `*_test.go` files\n7. **Update migrations** in `migrations/`\n\n### Code Quality\n\n- Follow Go best practices and idioms\n- Maintain test coverage above 80%\n- Use structured logging for observability\n- Implement proper error handling\n- Document public APIs\n\n## Contributing\n\n1. Fork the repository\n2. Create a feature branch\n3. Add tests for new functionality\n4. Ensure all tests pass\n5. Submit a pull request\n\n## Swagger Documentation\n\nThe service includes interactive Swagger/OpenAPI documentation that can be enabled or disabled via configuration.\n\n### Accessing Swagger UI\n\nWhen enabled (default), you can access the interactive API documentation at:\n- **Local Development**: http://localhost:8080/swagger/index.html\n- **Docker**: http://localhost:8080/swagger/index.html\n\n### Configuration\n\nControl Swagger documentation via environment variables:\n\n```bash\n# Enable/disable Swagger (default: true)\nSWAGGER_ENABLED=true\n```\n\n### Disabling Swagger in Production\n\nFor production environments, you may want to disable Swagger:\n\n```bash\n# In your .env or environment\nSWAGGER_ENABLED=false\n```\n\nThe Swagger documentation includes:\n- **Interactive API Testing**: Test endpoints directly from the browser\n- **Request/Response Examples**: See example payloads and responses\n- **Schema Documentation**: Detailed information about data models\n- **Error Response Examples**: Including dependency error formats\n\n## CI/CD Pipeline\n\nThe project includes comprehensive CI/CD pipelines for both GitLab CI and GitHub Actions.\n\n### Pipeline Features\n\n- ✅ **Automated Testing**: Unit, integration, and scenario tests\n- ✅ **Security Scanning**: Vulnerability detection with Trivy\n- ✅ **Docker Image Building**: Multi-platform (amd64/arm64) builds\n- ✅ **Container Registry**: Automatic image publishing with git commit hash\n- ✅ **Coverage Reports**: Test coverage analysis and reporting\n- ✅ **Integration Testing**: Full application testing with Docker Compose\n- ✅ **Deployment Automation**: Staging and production deployment workflows\n\n### GitLab CI Pipeline\n\nThe `.gitlab-ci.yml` includes:\n\n```yaml\nstages:\n  - test          # Run tests with PostgreSQL\n  - build         # Build Docker images\n  - publish       # Push to GitLab Container Registry\n```\n\n**Image Tags:**\n- `registry.gitlab.com/project/featureflags:latest` (main branch)\n- `registry.gitlab.com/project/featureflags:${CI_COMMIT_SHA}` (commit hash)\n- `registry.gitlab.com/project/featureflags:${CI_COMMIT_REF_SLUG}` (branch name)\n\n### GitHub Actions Pipeline\n\nThe `.github/workflows/ci.yml` includes:\n\n```yaml\njobs:\n  - test              # Unit and integration tests\n  - build             # Docker image building\n  - publish           # Push to GitHub Container Registry\n  - security-scan     # Trivy vulnerability scanning\n  - integration-test  # Full application testing\n  - deploy-staging    # Staging deployment\n  - deploy-production # Production deployment\n```\n\n**Image Tags:**\n- `ghcr.io/username/featureflags:latest` (main branch)\n- `ghcr.io/username/featureflags:${GITHUB_SHA}` (commit hash)\n- `ghcr.io/username/featureflags:main-${GITHUB_SHA}` (branch-commit)\n\n### Database Configuration for Testing\n\nBoth pipelines support the `POSTGRES_DB_test` naming convention:\n\n```bash\n# Environment variables\nPOSTGRES_DB=featureflags          # Base database name\nTEST_DB_NAME=featureflags_test    # Test database name (auto-generated)\n```\n\n### Running CI/CD Locally\n\n```bash\n# Test the full CI pipeline locally\ndocker-compose run --rm scenario-test\n\n# Test image building\ndocker build -t featureflags:test .\n\n# Test with specific commit hash\ndocker build -t featureflags:$(git rev-parse --short HEAD) .\n```\n\n## License\n\nThis project is licensed under the MIT License. ","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsinashahoveisi%2Ffeatureflags","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsinashahoveisi%2Ffeatureflags","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsinashahoveisi%2Ffeatureflags/lists"}