# AUDIT-NG KNOWLEDGE BASE

## OVERVIEW
`audit-ng` is a timer-driven log rotation/upload service with two operating modes:
- `tidb` (default): TiDB/Kong-specific behavior such as format-switch detection and built-in `tidb-` / `kong-` path handling.
- `agent`: generic log shipping mode that uses `subPath` plus size/lifetime-based rotation triggers.

## STRUCTURE
- `main.go`, `cmd/root.go`, and `cmd/audit_server.go`: CLI bootstrap and `server` command entrypoint.
- `server/server.go`: main loop (`checkLogTick`, `cleanLogTick`, shutdown flush).
- `server/handler.go`: `LogHandler` abstraction.
- `server/*_handler.go`: storage backend implementations (S3/GCS/Azure/OSS).
- `server/rotation.go`: rename/copytruncate rotation logic.
- `server/config.go`: config schema, mode semantics, and validation.

## WHERE TO LOOK
| Task | Location | Notes |
|------|----------|-------|
| Main runtime behavior | `server/server.go` | Push loop, cleanup loop, graceful stop |
| Mode-specific behavior | `server/server.go` and `server/config.go` | `tidb` format/prefix logic vs `agent` maxSize/maxLifetime rotation |
| Rotation correctness | `server/rotation.go` | Copy-truncate safety and boundaries |
| Backend upload behavior | `server/s3_handler.go`, `server/gcs_handler.go`, `server/azblob_handler.go`, `server/oss_handler.go` | Cloud-specific upload paths |
| Config semantics | `server/config.go` | Mode, trigger, limits, auth options |
| Metrics | `server/metrics.go` | `auditlog_*` series |

## COMMANDS
```bash
make build
make test
make lint
make lint-fix
make run
```

## CONVENTIONS (LOCAL)
- Service behavior is timer-driven; most changes belong in `server/server.go` and should preserve shutdown flush semantics.
- Keep the two runtime modes aligned: `tidb` mode owns format-switch detection and TiDB/Kong path conventions, while `agent` mode owns `subPath` and size/lifetime-triggered rotation.
- Rotation strategy supports `rename` and `copytruncate`; test both behavior and file integrity when changing rotation paths.
- `pushTrigger.maxSize`, `pushTrigger.maxLifetime`, and `subPath` only apply in `agent` mode; `tidb` mode intentionally ignores them or uses built-in defaults.
- Config is viper-driven, but not every field supports live reload (`server/config.go` documents constraints).
- `server/gomock_handler.go` is generated (`MockGen`); regenerate instead of editing manually.
- Unit tests are concentrated in `server/*_test.go`; keep table-driven style for multi-scenario logic.

## ANTI-PATTERNS
- Treating rotation as stateless and ignoring modified-time/size edge cases.
- Changing one mode's behavior without checking the other mode's defaults, validation, and tests.
- Adding backend-specific logic directly into the generic server loop.
- Editing generated mock file directly.
- Changing push-trigger semantics without updating config validation and tests together.
