Commit 6b3057fd by Percy Quispe Huarcaya

chore: refactor code

parent dbf8aafa
File added
---
name: golang-concurrency
description: "Golang concurrency design — goroutine lifecycle and leak prevention, channels and `select`, channel ownership and direction, `sync.Mutex`/`RWMutex`/`sync.Map`/`sync.Once`/atomics, `errgroup`, `singleflight`, worker pools, and fan-out/fan-in pipelines. Use when writing or reviewing concurrent Go code, when choosing between channels and mutexes, when protecting a shared map or counter, or when a goroutine has no clear exit. Not for defensive coding unrelated to concurrency such as nil panics, slice aliasing, or numeric overflow (→ See `samber/cc-skills-golang@golang-safety` skill), and not for debugging a specific hung, crashing, or racing program after the fact (→ See `samber/cc-skills-golang@golang-troubleshooting` skill)."
user-invocable: true
license: MIT
compatibility: Designed for Claude Code, Codex or similar harness, and for projects using Golang.
metadata:
author: samber
version: "1.2.1"
openclaw:
emoji: "⚡"
homepage: https://github.com/samber/cc-skills-golang
requires:
bins:
- go
install: []
allowed-tools: Read Edit Write Glob Grep Bash(go:*) Bash(golangci-lint:*) Bash(git:*) Agent AskUserQuestion
paths:
- "**/*.go"
---
**Persona:** You are a Go concurrency engineer. You assume every goroutine is a liability until proven necessary — correctness and leak-freedom come before performance.
**Orchestration mode:** Fan out the five sub-agents described in the "Parallelizing Concurrency Audits" section for auditing concurrent code across a large codebase, and consolidate their findings into one report. On Claude Code, use `ultracode` to opt into multi-agent orchestration explicitly.
**Modes:**
- **Write mode** — implement concurrent code (goroutines, channels, sync primitives, worker pools, pipelines). Follow the sequential instructions below.
- **Review mode** — reviewing a PR's concurrent code changes. Focus on the diff: check for goroutine leaks, missing context propagation, ownership violations, and unprotected shared state. Sequential.
- **Audit mode** — auditing existing concurrent code across a codebase. Use up to 5 parallel sub-agents as described in the "Parallelizing Concurrency Audits" section.
> **Community default.** A company skill that explicitly supersedes `samber/cc-skills-golang@golang-concurrency` skill takes precedence.
# Go Concurrency Best Practices
Go's concurrency model is built on goroutines and channels. Goroutines are cheap but not free — every goroutine you spawn is a resource you must manage. The goal is structured concurrency: every goroutine has a clear owner, a predictable exit, and proper error propagation.
## Core Principles
1. **Every goroutine must have a clear exit** — without a shutdown mechanism (context, done channel, WaitGroup), they leak and accumulate until the process crashes
2. **Share memory by communicating** — channels transfer ownership explicitly; mutexes protect shared state but make ownership implicit
3. **Send copies, not pointers** on channels — sending pointers creates invisible shared memory, defeating the purpose of channels
4. **Only the sender closes a channel** — closing from the receiver side panics if the sender writes after close
5. **Specify channel direction** (`chan<-`, `<-chan`) — the compiler prevents misuse at build time
6. **Default to unbuffered channels** — larger buffers mask backpressure; use them only with measured justification
7. **Always include `ctx.Done()` in select** — without it, goroutines leak after caller cancellation
8. **Avoid repeated `time.After` in hot loops** — each call allocates a timer and creates unnecessary churn; use `time.NewTimer` + `Reset` for long-running loops
9. **Track goroutine leaks in tests** with `go.uber.org/goleak`
For detailed channel/select code examples, see [Channels and Select Patterns](references/channels-and-select.md).
## Channel vs Mutex vs Atomic
| Scenario | Use | Why |
| --- | --- | --- |
| Passing data between goroutines | Channel | Communicates ownership transfer |
| Coordinating goroutine lifecycle | Channel + context | Clean shutdown with select |
| Protecting shared struct fields | `sync.Mutex` / `sync.RWMutex` | Simple critical sections |
| Simple counters, flags | `sync/atomic` | Lock-free, lower overhead |
| Many readers, few writers on a map | `sync.Map` | Optimized for read-heavy workloads. **Concurrent map read/write causes a hard crash** |
| Caching expensive computations | `sync.Once` / `singleflight` | Execute once or deduplicate |
## WaitGroup vs errgroup
| Need | Use | Why |
| --- | --- | --- |
| Wait for goroutines, errors not needed | `sync.WaitGroup` | Fire-and-forget |
| Wait + collect first error | `errgroup.Group` | Error propagation |
| Wait + cancel siblings on first error | `errgroup.WithContext` | Context cancellation on error |
| Wait + limit concurrency | `errgroup.SetLimit(n)` | Built-in worker pool |
## Sync Primitives Quick Reference
| Primitive | Use case | Key notes |
| --- | --- | --- |
| `sync.Mutex` | Protect shared state | Keep critical sections short; never hold across I/O |
| `sync.RWMutex` | Many readers, few writers | Never upgrade RLock to Lock (deadlock) |
| `sync/atomic` | Simple counters, flags | Prefer typed atomics (Go 1.19+): `atomic.Int64`, `atomic.Bool` |
| `sync.Map` | Concurrent map, read-heavy | No explicit locking; use `RWMutex`+map when writes dominate |
| `sync.Pool` | Reuse temporary objects | Always `Reset()` before `Put()`; reduces GC pressure |
| `sync.Once` | One-time initialization | Go 1.21+: `OnceFunc`, `OnceValue`, `OnceValues` |
| `sync.WaitGroup` | Waiting for simple goroutines | Go 1.25+: prefer `wg.Go(func(){ ... })` for fire-and-wait tasks that do not panic and do not need error propagation. For Go <1.25 use `Add`/`Done`. For errors/cancellation/limits, use `errgroup` with context. |
| `x/sync/singleflight` | Deduplicate concurrent calls | Cache stampede prevention |
| `x/sync/errgroup` | Goroutine group + errors | `SetLimit(n)` replaces hand-rolled worker pools |
For detailed examples and anti-patterns, see [Sync Primitives Deep Dive](references/sync-primitives.md).
## Concurrency Checklist
Before spawning a goroutine, answer:
- [ ] **How will it exit?** — context cancellation, channel close, or explicit signal
- [ ] **Can I signal it to stop?** — pass `context.Context` or done channel
- [ ] **Can I wait for it?** — `sync.WaitGroup` or `errgroup`
- [ ] **Who owns the channels?** — creator/sender owns and closes
- [ ] **Should this be synchronous instead?** — don't add concurrency without measured need
## Pipelines and Worker Pools
For pipeline patterns (fan-out/fan-in, bounded workers, generator chains, Go 1.23+ iterators, `samber/ro`), see [Pipelines and Worker Pools](references/pipelines.md).
## Parallelizing Concurrency Audits
When auditing concurrency across a large codebase, use up to 5 parallel sub-agents:
1. Find all goroutine spawns (`go func`, `go method`) and verify shutdown mechanisms
2. Search for mutable globals and shared state without synchronization
3. Audit channel usage — ownership, direction, closure, buffer sizes
4. Find `time.After` in loops, missing `ctx.Done()` in select, unbounded spawning
5. Check mutex usage, `sync.Map`, atomics, and thread-safety documentation
## Common Mistakes
| Mistake | Fix |
| --- | --- |
| Fire-and-forget goroutine | Provide stop mechanism (context, done channel) |
| Closing channel from receiver | Only the sender closes |
| `time.After` in hot loop | Reuse `time.NewTimer` + `Reset` |
| Missing `ctx.Done()` in select | Always select on context to allow cancellation |
| Unbounded goroutine spawning | Use `errgroup.SetLimit(n)` or semaphore |
| Sharing pointer via channel | Send copies or immutable values |
| `wg.Add` inside goroutine | Call `Add` before `go` — `Wait` may return early otherwise |
| Forgetting `-race` in CI | Always run `go test -race ./...` |
| Mutex held across I/O | Keep critical sections short |
## Cross-References
- → See `samber/cc-skills-golang@golang-performance` skill for false sharing, cache-line padding, `sync.Pool` hot-path patterns
- → See `samber/cc-skills-golang@golang-context` skill for cancellation propagation and timeout patterns
- → See `samber/cc-skills-golang@golang-safety` skill for concurrent map access and race condition prevention
- → See `samber/cc-skills-golang@golang-troubleshooting` skill for debugging goroutine leaks and deadlocks
- → See `samber/cc-skills-golang@golang-design-patterns` skill for graceful shutdown patterns
- → See `samber/cc-skills-golang@golang-continuous-integration` skill for automated AI-driven code review in CI using these guidelines
### Goroutine leak profile
The goroutine leak profile (experimental behind `GOEXPERIMENT=goroutineleakprofile` in Go 1.26) is generally available in `runtime/pprof` since Go 1.27 — no build flag required. It is a useful production-oriented leak signal alongside the existing tools below.
```bash
curl http://localhost:6060/debug/pprof/goroutineleak?debug=2
go tool pprof http://localhost:6060/debug/pprof/goroutineleak
```
Keep existing tools:
- tests: `go.uber.org/goleak`
- runtime count: `runtime.NumGoroutine()`
- stack dump: `/debug/pprof/goroutine?debug=2`
- race checks: `go test -race ./...`
## References
- [Go Concurrency Patterns: Pipelines](https://go.dev/blog/pipelines)
- [Effective Go: Concurrency](https://go.dev/doc/effective_go#concurrency)
# Channels and Select Patterns
## Table of Contents
- [Goroutine Lifecycle](#goroutine-lifecycle)
- [Panic Recovery at Goroutine Boundaries](#panic-recovery-at-goroutine-boundaries)
- [Channel Direction](#channel-direction)
- [Channel Closing](#channel-closing)
- [Buffer Size](#buffer-size)
- [Select for Non-Blocking Communication](#select-for-non-blocking-communication)
- [Avoid Repeated `time.After` in Hot Loops](#avoid-repeated-timeafter-in-hot-loops)
## Goroutine Lifecycle
NEVER start a goroutine without knowing how it stops. Every goroutine MUST answer: **how will it stop?**
```go
// ✗ Bad — fire-and-forget, no way to stop or wait
func startWorker() {
go func() {
for {
doWork() // runs forever, leaks on shutdown
}
}()
}
// ✓ Good — goroutine respects context cancellation, caller can wait
func startWorker(ctx context.Context) *sync.WaitGroup {
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
for {
select {
case <-ctx.Done():
return
default:
doWork(ctx)
}
}
}()
return &wg
}
```
### Panic Recovery at Goroutine Boundaries
A panic in a goroutine crashes the entire process. Always recover at goroutine boundaries in production code:
```go
go func() {
defer func() {
if r := recover(); r != nil {
// ...
}
}()
doWork(ctx)
}()
```
## Channel Direction
Specify direction in function signatures to prevent misuse at compile time:
```go
// ✗ Bad — caller could accidentally close or send on a receive-only channel
func consume(ch chan int) { ... }
// ✓ Good — compiler enforces correct usage
func produce(ch chan<- int) { ... } // send-only
func consume(ch <-chan int) { ... } // receive-only
```
## Channel Closing
Channels MUST be closed by the sender (producer), NEVER by the receiver — it causes a panic if the sender writes after close.
```go
// ✓ Good — producer closes when done
func generate(ctx context.Context) <-chan int {
ch := make(chan int)
go func() {
defer close(ch) // sender closes
for i := 0; ; i++ {
select {
case ch <- i:
case <-ctx.Done():
return
}
}
}()
return ch
}
```
## Buffer Size
| Size | When to use |
| --- | --- |
| 0 (unbuffered) | Default. Synchronizes sender and receiver — use when you need handoff guarantees |
| 1 | Signal channels (`done := make(chan struct{}, 1)`), or when sender must not block on a single pending item |
| N > 1 | Only with measured justification — document why N was chosen and what happens when the buffer fills |
```go
// ✓ Good — unbuffered for synchronous handoff
ch := make(chan Result)
// ✓ Good — buffered 1 for signal
done := make(chan struct{}, 1)
// ✗ Suspicious — arbitrary large buffer hides backpressure problems
// Give explanation in comments.
ch := make(chan Task, 1000) // why 1000? what if it fills?
```
## Select for Non-Blocking Communication
Use `select` to multiplex channel operations and always include `ctx.Done()` to prevent goroutine leaks:
```go
func process(ctx context.Context, in <-chan Task, out chan<- Result) {
for {
select {
case <-ctx.Done():
return
case task, ok := <-in:
if !ok {
return // channel closed
}
result := handle(ctx, task)
select {
case out <- result:
case <-ctx.Done():
return
}
}
}
}
```
## Avoid Repeated `time.After` in Hot Loops
```go
// ✗ Bad — creates a new timer on every iteration
for {
select {
case msg := <-ch:
handle(msg)
case <-time.After(5 * time.Second): // repeated allocation/churn
handleTimeout()
}
}
// ✓ Good (Go 1.23+) — reuse the timer
timer := time.NewTimer(5 * time.Second)
defer timer.Stop()
for {
select {
case msg := <-ch:
timer.Stop()
timer.Reset(5 * time.Second)
handle(msg)
case <-timer.C:
handleTimeout()
timer.Reset(5 * time.Second)
}
}
```
For Go <1.23, if `timer.Stop()` returns false, drain a possible stale value before `Reset`. In Go 1.23+, receiving from `timer.C` after `Stop` returns is guaranteed to block rather than receive a stale value.
# Pipelines and Worker Pools
## Table of Contents
- [Pipeline Pattern](#pipeline-pattern)
- [Fan-Out / Fan-In](#fan-out--fan-in)
- [Worker Pool with errgroup](#worker-pool-with-errgroup)
- [Bounded Concurrency with Semaphore](#bounded-concurrency-with-semaphore)
- [Pipeline Alternatives](#pipeline-alternatives)
- [Go 1.23+ Iterators (range-over-func)](#go-123-iterators-range-over-func)
- [samber/ro](#samberro)
- [Goroutine Leak Detection](#goroutine-leak-detection)
- [Common Pipeline Mistakes](#common-pipeline-mistakes)
## Pipeline Pattern
A pipeline is a series of stages connected by channels, where each stage is a goroutine (or group of goroutines) that:
1. Receives values from an upstream channel
2. Processes each value
3. Sends results to a downstream channel
```go
// Stage 1: Generate integers
func generate(ctx context.Context, nums ...int) <-chan int {
out := make(chan int)
go func() {
defer close(out)
for _, n := range nums {
select {
case out <- n:
case <-ctx.Done():
return
}
}
}()
return out
}
// Stage 2: Square each integer
func square(ctx context.Context, in <-chan int) <-chan int {
out := make(chan int)
go func() {
defer close(out)
for n := range in {
select {
case out <- n * n:
case <-ctx.Done():
return
}
}
}()
return out
}
// Usage
func main() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
ch := generate(ctx, 2, 3, 4)
results := square(ctx, ch)
for v := range results {
fmt.Println(v) // 4, 9, 16
}
}
```
**Key rules for pipelines**:
- Pipeline stages MUST accept and respect context cancellation — every stage must select on `ctx.Done()` to avoid goroutine leaks on early cancellation
- The producer (first stage) closes its output channel; each subsequent stage closes its own output
- NEVER create unbounded goroutines in pipeline stages
- Use unbuffered channels unless you have measured throughput needs
## Fan-Out / Fan-In
**Fan-out**: multiple goroutines read from the same channel to parallelize CPU-bound work. **Fan-in**: multiple channels are merged into a single output channel.
```go
// Fan-out: N workers reading from the same input channel
func fanOut(ctx context.Context, in <-chan Task, workers int) <-chan Result {
out := make(chan Result)
var wg sync.WaitGroup
for i := 0; i < workers; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for {
select {
case task, ok := <-in:
if !ok {
return
}
select {
case out <- process(ctx, task):
case <-ctx.Done():
return
}
case <-ctx.Done():
return
}
}
}()
}
go func() {
wg.Wait()
close(out)
}()
return out
}
```
```go
// Fan-in: merge multiple channels into one
func fanIn(ctx context.Context, channels ...<-chan Result) <-chan Result {
out := make(chan Result)
var wg sync.WaitGroup
for _, ch := range channels {
wg.Add(1)
go func(c <-chan Result) {
defer wg.Done()
for v := range c {
select {
case out <- v:
case <-ctx.Done():
return
}
}
}(ch)
}
go func() {
wg.Wait()
close(out)
}()
return out
}
```
## Worker Pool with errgroup
Fan-out workers SHOULD use `errgroup.SetLimit` for bounded concurrency. For most use cases, `errgroup.SetLimit` replaces hand-rolled worker pools:
```go
func processAll(ctx context.Context, tasks []Task) error {
g, ctx := errgroup.WithContext(ctx)
g.SetLimit(10) // max 10 concurrent workers
for _, task := range tasks {
g.Go(func() error {
return process(ctx, task)
})
}
return g.Wait()
}
```
Use a hand-rolled worker pool only when you need:
- Per-worker state (connections, buffers)
- Custom backpressure or priority scheduling
- Graceful draining with in-flight task completion
## Bounded Concurrency with Semaphore
When you need fine-grained concurrency control without errgroup:
```go
func processAll(ctx context.Context, items []Item) error {
sem := make(chan struct{}, 10) // semaphore of 10
var wg sync.WaitGroup
for _, item := range items {
wg.Add(1)
sem <- struct{}{} // acquire
go func(item Item) {
defer wg.Done()
defer func() { <-sem }() // release
process(ctx, item)
}(item)
}
wg.Wait()
return nil
}
```
Prefer `errgroup.SetLimit` over this pattern when error propagation is needed.
## Pipeline Alternatives
### Go 1.23+ Iterators (range-over-func)
For in-process data transformations that do not need concurrency, iterators avoid the overhead of goroutines and channels:
```go
func Filter[T any](seq iter.Seq[T], pred func(T) bool) iter.Seq[T] {
return func(yield func(T) bool) {
for v := range seq {
if pred(v) {
if !yield(v) {
return
}
}
}
}
}
func Map[T, U any](seq iter.Seq[T], f func(T) U) iter.Seq[U] {
return func(yield func(U) bool) {
for v := range seq {
if !yield(f(v)) {
return
}
}
}
}
```
Use iterators when:
- Processing is CPU-bound and does not benefit from parallelism
- You want lazy evaluation without goroutine overhead
- The data source is already sequential (slice, database cursor)
Use goroutine+channel pipelines when:
- Stages involve I/O (network, disk) that benefits from concurrency
- You need true parallelism across CPU cores
- Stages have different throughput characteristics
### samber/ro
`samber/ro` provides a fluent, type-safe pipeline API for read-only collections:
```go
import "github.com/samber/ro"
emails, _ := ro.Collect( // ignore error
ro.Pipe(
ro.FromSlice(users),
ro.Filter(func(u User) bool { return u.Active }),
ro.Map(func(u User) string { return u.Email }),
),
)
```
Use `samber/ro` for sequential data transformations that benefit from a fluent API. It might also support parallel processing if needed.
## Goroutine Leak Detection
Goroutine leaks SHOULD be detected with goleak in tests. Use `go.uber.org/goleak` in `TestMain` to catch leaked goroutines across all tests:
```go
func TestMain(m *testing.M) {
goleak.VerifyTestMain(m)
}
```
## Common Pipeline Mistakes
| Mistake | Fix |
| --- | --- |
| Missing `ctx.Done()` in pipeline stage | Always select on context to allow cancellation |
| Not closing output channel | Producer must `defer close(out)` |
| Unbounded goroutine spawning | Use `errgroup.SetLimit` or a semaphore |
| Sending mutable data through channel | Send copies or immutable values |
| Blocking send without select | Wrap channel sends in select with `ctx.Done()` |
→ See `samber/cc-skills-golang@golang-concurrency` skill for sync primitives and channel patterns.
# Sync Primitives Deep Dive
## Table of Contents
- [sync.Mutex](#syncmutex)
- [Embedding Convention](#embedding-convention)
- [sync.RWMutex](#syncrwmutex)
- [sync/atomic](#syncatomic)
- [sync.Map](#syncmap)
- [sync.Pool](#syncpool)
- [sync.Once](#synconce)
- [sync.WaitGroup](#syncwaitgroup)
- [Go 1.25+: `wg.Go`](#go-125-wggo)
- [Go <1.25 fallback](#go-125-fallback)
- [golang.org/x/sync/singleflight](#golangorgxsyncsingleflight)
- [golang.org/x/sync/errgroup](#golangorgxsyncerrgroup)
- [Bounded Concurrency with SetLimit](#bounded-concurrency-with-setlimit)
## sync.Mutex
Protects shared state with exclusive access. MUST hold the lock for the shortest time possible — NEVER hold a mutex across I/O, network calls, or channel operations.
```go
type SafeCache struct {
mu sync.Mutex
items map[string]string
}
func (c *SafeCache) Get(key string) (string, bool) {
c.mu.Lock()
defer c.mu.Unlock()
v, ok := c.items[key]
return v, ok
}
func (c *SafeCache) Set(key, value string) {
c.mu.Lock()
defer c.mu.Unlock()
c.items[key] = value
}
```
### Embedding Convention
Embed the mutex as an unexported field, placed directly above the fields it protects:
```go
type Registry struct {
mu sync.Mutex // protects entries
entries map[string]Entry
}
```
## sync.RWMutex
SHOULD be used when reads greatly outnumber writes. Multiple goroutines can hold `RLock` simultaneously; `Lock` is exclusive.
```go
type Config struct {
mu sync.RWMutex
values map[string]string
}
func (c *Config) Get(key string) string {
c.mu.RLock()
defer c.mu.RUnlock()
return c.values[key]
}
func (c *Config) Set(key, value string) {
c.mu.Lock()
defer c.mu.Unlock()
c.values[key] = value
}
```
**Pitfall**: Do not upgrade RLock to Lock — this deadlocks. Release RLock first, then acquire Lock.
## sync/atomic
Lock-free operations for simple values. SHOULD be preferred over Mutex for simple counter operations. Faster than mutex for low-contention counters and flags.
```go
// ✓ Good — atomic for a simple counter
var requestCount atomic.Int64
func handleRequest() {
requestCount.Add(1)
}
func getCount() int64 {
return requestCount.Load()
}
```
```go
// ✓ Good — atomic.Bool for a shutdown flag
var shuttingDown atomic.Bool
func shutdown() {
shuttingDown.Store(true)
}
func isRunning() bool {
return !shuttingDown.Load()
}
```
Go 1.19+ provides typed atomics (`atomic.Int64`, `atomic.Bool`, `atomic.Pointer[T]`) — prefer these over raw `atomic.AddInt64`/`atomic.LoadInt64`.
## sync.Map
SHOULD only be used for write-once/read-many patterns. Optimized for two common patterns: (1) keys are written once and read many times, (2) multiple goroutines read/write disjoint key sets. For other patterns, a plain `map` + `sync.RWMutex` is faster.
```go
var cache sync.Map
func Get(key string) (any, bool) {
return cache.Load(key)
}
func Set(key string, value any) {
cache.Store(key, value)
}
func GetOrSet(key string, compute func() any) any {
if v, ok := cache.Load(key); ok {
return v
}
v, _ := cache.LoadOrStore(key, compute())
return v
}
```
**When NOT to use `sync.Map`**: when you need to iterate, get the length, or when writes are frequent and keys overlap heavily. Use `sync.RWMutex` + `map` instead.
## sync.Pool
Reuse temporary objects to reduce GC pressure. MUST NOT store pointers to stack-allocated objects. Objects in the pool may be reclaimed at any GC cycle — do not store persistent state.
```go
var bufPool = sync.Pool{
New: func() any {
return new(bytes.Buffer)
},
}
func process(data []byte) string {
buf := bufPool.Get().(*bytes.Buffer)
defer func() {
buf.Reset()
bufPool.Put(buf)
}()
buf.Write(data)
// ... transform ...
return buf.String()
}
```
**Rules**:
- Always `Reset()` before `Put()` — returning dirty objects causes bugs
- Do not assume an object from `Get()` is zeroed — the `New` func only runs if the pool is empty
- Best for short-lived, frequently allocated objects (buffers, encoders, temporary structs)
## sync.Once
MUST be used for one-time initialization. Execute exactly once, regardless of how many goroutines call it concurrently. Thread-safe by design.
```go
type DBClient struct {
initOnce sync.Once
closeOnce sync.Once
conn *sql.DB
}
func (c *DBClient) getConn() *sql.DB {
c.initOnce.Do(func() {
var err error
c.conn, err = sql.Open("postgres", dsn)
if err != nil {
panic(fmt.Sprintf("db init: %v", err))
}
})
return c.conn
}
func (c *DBClient) Close() error {
var err error
c.closeOnce.Do(func() {
err = c.conn.Close()
})
return err
}
```
Go 1.21+ also provides `sync.OnceFunc`, `sync.OnceValue`, and `sync.OnceValues` for simpler use cases:
```go
var loadConfig = sync.OnceValue(func() *Config {
cfg, err := parseConfig("config.yaml")
if err != nil {
panic(err)
}
return cfg
})
// Usage: cfg := loadConfig()
```
## sync.WaitGroup
Use `sync.WaitGroup` when you only need to wait for a set of goroutines to finish.
### Go 1.25+: `wg.Go`
`WaitGroup.Go` starts a goroutine, adds it to the group, and removes it from the group when the function returns.
```go
func processAll(items []Item) {
var wg sync.WaitGroup
for _, item := range items {
// Go 1.22+ loop variables are per-iteration when the module has `go 1.22+`.
// Do not add `item := item` solely for closure capture in modern modules.
wg.Go(func() {
process(item)
})
}
wg.Wait()
}
```
Rules:
- `WaitGroup.Go` is Go 1.25+, not Go 1.24.
- The function passed to `wg.Go` must not panic.
- `WaitGroup` does not propagate errors and does not cancel siblings.
- For first-error-wins, cancellation, concurrency limits, or returned values, use `golang.org/x/sync/errgroup`.
**Benefits of `wg.Go()`**:
- No manual `Add`/`Done` bookkeeping
- Lower risk of `Add`/`Wait` ordering bugs
- Cleaner API for simple fire-and-wait work
**When to use**: Go 1.25+ projects for simple goroutines that must all finish, do not return errors, do not need cancellation, and must not panic. Use `errgroup` when work returns errors, needs cancellation, limits, or first-error behavior.
### Go <1.25 fallback
```go
func processAll(ctx context.Context, items []Item) {
var wg sync.WaitGroup
for _, item := range items {
wg.Add(1) // Add BEFORE go
go func(item Item) {
defer wg.Done()
process(ctx, item)
}(item)
}
wg.Wait() // blocks until all goroutines finish
}
```
```go
// ✗ Bad — Add inside the goroutine (race: Wait may return before Add runs)
go func() {
wg.Add(1)
defer wg.Done()
process(item)
}()
```
## golang.org/x/sync/singleflight
Deduplicates concurrent calls for the same key. When multiple goroutines request the same resource simultaneously, only one executes; the rest wait and share the result.
```go
var group singleflight.Group
func GetUser(ctx context.Context, id string) (*User, error) {
v, err, _ := group.Do(id, func() (any, error) {
// Only one goroutine executes this for a given id
return db.QueryUser(ctx, id)
})
if err != nil {
return nil, err
}
return v.(*User), nil
}
```
**Use cases**: cache stampede prevention, deduplicating expensive lookups (DB, API), rate-limited external service calls.
## golang.org/x/sync/errgroup
Goroutine group with error propagation. Returns the first error from any goroutine. With `WithContext`, cancels remaining goroutines on first error.
```go
func fetchAll(ctx context.Context, urls []string) ([]Response, error) {
g, ctx := errgroup.WithContext(ctx) // cancel siblings on first error
results := make([]Response, len(urls))
for i, url := range urls {
g.Go(func() error {
resp, err := fetch(ctx, url)
if err != nil {
return fmt.Errorf("fetching %s: %w", url, err)
}
results[i] = resp // safe: each goroutine writes to its own index
return nil
})
}
if err := g.Wait(); err != nil {
return nil, err
}
return results, nil
}
```
### Bounded Concurrency with SetLimit
SHOULD use `SetLimit` to bound concurrency and avoid unbounded goroutine spawning.
```go
g, ctx := errgroup.WithContext(ctx)
g.SetLimit(10) // at most 10 goroutines run concurrently
for _, task := range tasks {
g.Go(func() error {
return process(ctx, task)
})
}
return g.Wait()
```
This replaces hand-rolled worker pools for most use cases.
→ See `samber/cc-skills-golang@golang-concurrency` skill for high-level patterns and decision trees.
# Architecture Patterns
## Table of Contents
- [Choose the Right Level of Architecture](#choose-the-right-level-of-architecture)
- [Keep Domain Pure](#keep-domain-pure)
- [Fail Fast — Validate at Boundaries](#fail-fast--validate-at-boundaries)
- [Make Illegal States Unrepresentable](#make-illegal-states-unrepresentable)
- [Detailed Architecture Guides](#detailed-architecture-guides)
- [12-Factor App Principles](#12-factor-app-principles)
- [Explicit Over Implicit](#explicit-over-implicit)
## Choose the Right Level of Architecture
Architecture complexity MUST match project scope — don't over-architect small projects. When starting a new project, ask the developer what architecture they prefer:
| Project Size | Recommended Approach |
| --- | --- |
| Script / small CLI (<500 lines) | Flat `main.go` + a few files, no layers |
| Medium service (500-5K lines) | Simple layered: `handler/`, `service/`, `repository/` |
| Large service / monolith (5K+ lines) | Clean architecture, hexagonal, or DDD — ask the team |
A 100-line CLI does not need a domain layer, ports and adapters, or dependency injection frameworks. Start simple and refactor when complexity demands it.
## Keep Domain Pure
Domain logic MUST remain pure — no framework or infrastructure dependencies. The domain layer contains business logic and types:
```go
// domain/order.go — pure business logic, no imports from infrastructure
package domain
type Order struct {
ID string
Items []Item
Status OrderStatus
}
func (o *Order) AddItem(item Item) error {
if o.Status != StatusDraft {
return ErrOrderNotEditable
}
o.Items = append(o.Items, item)
return nil
}
```
Infrastructure concerns (database queries, HTTP clients, message queues) live in separate packages that depend on the domain — never the reverse.
## Fail Fast — Validate at Boundaries
Input MUST be validated at system boundaries (HTTP handlers, CLI argument parsing, message consumers). Once data enters your domain layer, trust it:
```go
// Handler layer — validate here
func (h *Handler) CreateOrder(w http.ResponseWriter, r *http.Request) {
var req CreateOrderRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "invalid JSON", http.StatusBadRequest)
return
}
if req.UserID == "" {
http.Error(w, "user_id is required", http.StatusBadRequest)
return
}
if len(req.Items) == 0 {
http.Error(w, "at least one item required", http.StatusBadRequest)
return
}
// Domain layer trusts this data is valid
order, err := h.service.CreateOrder(r.Context(), req.UserID, req.Items)
// ...
}
```
Don't re-validate the same data at every layer — it clutters the code and violates DRY.
## Make Illegal States Unrepresentable
Use Go's type system to prevent invalid states from being expressible in code:
```go
// Bad — status is a raw string, anything goes
type Order struct {
Status string // "pending"? "PENDING"? "active"? anything?
}
// Good — typed enum constrains the values
type OrderStatus int
const (
OrderStatusUnknown OrderStatus = iota // 0 = invalid
OrderStatusDraft // 1
OrderStatusConfirmed // 2
OrderStatusShipped // 3
)
type Order struct {
Status OrderStatus
}
```
```go
// Bad — email is a raw string, could be anything
func SendEmail(to string, body string) error { ... }
// Good — validated type enforces the constraint
type Email struct {
address string // unexported: can only be created via constructor
}
func NewEmail(raw string) (Email, error) {
if !isValidEmail(raw) {
return Email{}, fmt.Errorf("invalid email: %s", raw)
}
return Email{address: raw}, nil
}
```
## Detailed Architecture Guides
For projects that warrant a formal architecture (typically 5K+ lines), see the dedicated guides:
- [Domain-Driven Design (DDD)](./ddd.md) — aggregates, value objects, bounded contexts
- [Clean Architecture](./clean-architecture.md) — use cases, dependency rule, layered adapters
- [Hexagonal Architecture](./hexagonal-architecture.md) — ports, adapters, domain core isolation
## 12-Factor App Principles
→ See `samber/cc-skills-golang@golang-project-layout` for 12-Factor App conventions.
## Explicit Over Implicit
Go favors explicitness. Code should express its intent clearly without requiring the reader to know hidden conventions:
```go
// Bad — implicit behavior hidden in struct tags and reflection
type Config struct {
Port int `default:"8080"`
}
// Good — explicit defaults visible in code
func NewConfig() Config {
return Config{Port: 8080}
}
```
```go
// Bad — implicit dependency via global
func HandleRequest(w http.ResponseWriter, r *http.Request) {
user := globalDB.FindUser(r.Context(), userID) // where does globalDB come from?
}
// Good — explicit dependency via injection
func (h *Handler) HandleRequest(w http.ResponseWriter, r *http.Request) {
user := h.db.FindUser(r.Context(), userID) // clear: db is a field on Handler
}
```
→ See `samber/cc-skills-golang@golang-project-layout` skill for directory structure and layout patterns.
# Clean Architecture in Go
## Table of Contents
- [When to Use](#when-to-use)
- [The Dependency Rule](#the-dependency-rule)
- [Project Structure](#project-structure)
- [Code Examples](#code-examples)
- [Entity — pure domain logic, zero dependencies](#entity--pure-domain-logic-zero-dependencies)
- [Use Case — orchestrates business operations](#use-case--orchestrates-business-operations)
- [Adapter — implements a port](#adapter--implements-a-port)
- [Handler — translates HTTP to use case calls](#handler--translates-http-to-use-case-calls)
- [Key Principle](#key-principle)
- [Wiring](#wiring)
## When to Use
Apply clean architecture when you need strong separation between business logic and infrastructure — typically medium-to-large services (2K+ lines) where testability, framework independence, and clear dependency direction matter. Do NOT use for small CLI tools or scripts.
## The Dependency Rule
Dependencies point inward only. Inner layers never import outer layers.
```
Frameworks & Drivers → Interface Adapters → Use Cases → Entities
(HTTP, DB, gRPC) (handlers, repos) (app logic) (domain)
```
Each layer defines interfaces for what it needs. Outer layers implement those interfaces.
## Project Structure
```
order-service/
├── cmd/
│ └── server/
│ └── main.go # Wiring only — builds the dependency graph
├── internal/
│ ├── entity/
│ │ ├── order.go # Order entity + business rules
│ │ ├── item.go # OrderItem
│ │ └── status.go # OrderStatus enum
│ ├── order/
│ │ ├── place.go # PlaceOrderUseCase
│ │ ├── cancel.go # CancelOrderUseCase
│ │ └── port.go # Interfaces this use case depends on
│ ├── adapter/
│ │ ├── handler/
│ │ │ └── order_handler.go # HTTP handler — calls use cases
│ │ ├── repository/
│ │ │ └── order_postgres.go # OrderRepository — implements port
│ │ └── gateway/
│ │ └── payment_client.go # External payment API client
│ └── infrastructure/
│ ├── router.go # HTTP router setup
│ ├── database.go # DB connection
│ └── config.go # Config loading
├── go.mod
└── go.sum
```
## Code Examples
### Entity — pure domain logic, zero dependencies
```go
// internal/entity/order.go
package entity
type Order struct {
ID string
Items []Item
Status OrderStatus
}
func (o *Order) Cancel() error {
if o.Status == StatusShipped {
return ErrCannotCancelShipped
}
o.Status = StatusCancelled
return nil
}
func (o *Order) Total() int64 {
var sum int64
for _, item := range o.Items {
sum += item.Price * int64(item.Quantity)
}
return sum
}
```
### Use Case — orchestrates business operations
```go
// internal/order/port.go
package order
// Ports — interfaces defined by the use case, implemented by adapters
type OrderRepository interface {
Save(ctx context.Context, order *entity.Order) error
FindByID(ctx context.Context, id string) (*entity.Order, error)
}
type PaymentGateway interface {
Charge(ctx context.Context, orderID string, amount int64) error
}
```
```go
// internal/order/place.go
package order
type PlaceOrderUseCase struct {
orders OrderRepository
payments PaymentGateway
}
func NewPlaceOrderUseCase(orders OrderRepository, payments PaymentGateway) *PlaceOrderUseCase {
return &PlaceOrderUseCase{orders: orders, payments: payments}
}
func (uc *PlaceOrderUseCase) Execute(ctx context.Context, orderID string) error {
order, err := uc.orders.FindByID(ctx, orderID)
if err != nil {
return fmt.Errorf("finding order: %w", err)
}
if err := uc.payments.Charge(ctx, order.ID, order.Total()); err != nil {
return fmt.Errorf("charging payment: %w", err)
}
order.Status = entity.StatusPlaced
return uc.orders.Save(ctx, order)
}
```
### Adapter — implements a port
```go
// internal/adapter/repository/order_postgres.go
package repository
type OrderPostgres struct {
db *sql.DB
}
func NewOrderPostgres(db *sql.DB) *OrderPostgres {
return &OrderPostgres{db: db}
}
func (r *OrderPostgres) FindByID(ctx context.Context, id string) (*entity.Order, error) {
// SQL query, scan into entity.Order
}
func (r *OrderPostgres) Save(ctx context.Context, order *entity.Order) error {
// SQL upsert
}
```
### Handler — translates HTTP to use case calls
```go
// internal/adapter/handler/order_handler.go
package handler
type OrderHandler struct {
placeOrder *usecase.PlaceOrderUseCase
}
func (h *OrderHandler) HandlePlaceOrder(w http.ResponseWriter, r *http.Request) {
orderID := chi.URLParam(r, "id")
if err := h.placeOrder.Execute(r.Context(), orderID); err != nil {
// Map domain errors to HTTP status codes
http.Error(w, err.Error(), mapToHTTPStatus(err))
return
}
w.WriteHeader(http.StatusOK)
}
```
## Key Principle
Interfaces live where they are consumed, not where they are implemented. The `usecase/order/port.go` file defines `OrderRepository` — the adapter in `adapter/repository/` implements it. This keeps the use case layer free from infrastructure imports.
## Wiring
All dependency construction happens in `cmd/server/main.go`. → See `samber/cc-skills-golang@golang-dependency-injection` skill for DI library alternatives.
# Data Handling Patterns
## Iterators for Large Data (Go 1.23+)
Process large datasets without allocating everything into memory:
```go
// Bad — loads all rows into memory
func AllUsers(db *sql.DB) ([]User, error) {
rows, err := db.Query("SELECT * FROM users")
// ... scan all into slice
}
// Good — iterator yields one at a time
func AllUsers(db *sql.DB) iter.Seq2[User, error] {
return func(yield func(User, error) bool) {
rows, err := db.Query("SELECT * FROM users")
if err != nil {
yield(User{}, err)
return
}
defer rows.Close()
for rows.Next() {
var u User
if err := rows.Scan(&u.ID, &u.Name, &u.Email); err != nil {
yield(User{}, err)
return
}
if !yield(u, nil) {
return
}
}
}
}
```
## Streaming Large Transfers
When transferring large data between services (e.g., 1M rows from DB, 1M rows in HTTP response), use streaming patterns with iterators or `github.com/samber/ro` to prevent OOM:
```go
// Stream JSON array to HTTP response — constant memory
func (h *Handler) ExportUsers(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Write([]byte("["))
first := true
for user, err := range h.repo.AllUsers(r.Context()) {
if err != nil {
slog.Error("streaming user", "error", err)
return
}
if !first {
w.Write([]byte(","))
}
json.NewEncoder(w).Encode(user)
first = false
}
w.Write([]byte("]"))
}
```
# Domain-Driven Design (DDD) in Go
## Table of Contents
- [When to Use](#when-to-use)
- [Building Blocks](#building-blocks)
- [Project Structure](#project-structure)
- [Code Examples](#code-examples)
- [Value Object — Money](#value-object--money)
- [Aggregate Root — Order](#aggregate-root--order)
- [Repository Interface — defined in domain](#repository-interface--defined-in-domain)
- [Application Service — orchestrates a use case](#application-service--orchestrates-a-use-case)
- [Bounded Contexts](#bounded-contexts)
- [Wiring](#wiring)
## When to Use
Apply DDD when the business domain is complex enough that the code structure should mirror the business model — typically services with 5K+ lines, multiple bounded contexts, or rich business rules. Do NOT use for simple CRUD apps or CLI tools.
## Building Blocks
| Concept | Go Mapping | Purpose |
| --- | --- | --- |
| **Entity** | Struct with identity field | Has unique ID, mutable state, lifecycle |
| **Value Object** | Immutable struct, compared by value | No identity — represents a measurement, quantity, or descriptor |
| **Aggregate** | Entity + child entities/value objects | Consistency boundary — all mutations go through the root |
| **Repository** | Interface in domain, impl in infrastructure | Persistence abstraction for aggregates |
| **Domain Service** | Function or struct in domain package | Logic that spans multiple aggregates |
| **Domain Event** | Struct describing a fact that happened | Decouples bounded contexts |
## Project Structure
Organize by **bounded context**, grouping domain, application, and adapters vertically. This scales across multiple contexts and clarifies ownership.
```
order-service/
├── cmd/
│ └── server/
│ └── main.go # Wiring only
├── internal/
│ ├── order/ # Bounded context: Order
│ │ ├── domain/
│ │ │ ├── order.go # Order aggregate root
│ │ │ ├── item.go # OrderItem entity
│ │ │ ├── status.go # OrderStatus enum
│ │ │ ├── repository.go # OrderRepository interface
│ │ │ └── events.go # OrderPlaced, OrderShipped events
│ │ ├── application/
│ │ │ ├── place_order.go # PlaceOrderHandler (command)
│ │ │ └── get_order.go # GetOrderHandler (query)
│ │ └── adapters/
│ │ ├── persistence/
│ │ │ └── postgres.go # OrderRepository implementation
│ │ └── http/
│ │ └── handler.go # HTTP transport
│ ├── billing/ # Bounded context: Billing (another example)
│ │ ├── domain/
│ │ ├── application/
│ │ └── adapters/
│ ├── shared/
│ │ └── money.go # Value object reused across contexts
│ └── events/
│ └── publisher.go # Shared event bus (infrastructure)
├── go.mod
└── go.sum
```
**Key principles:**
- Group each bounded context **vertically** (domain → application → adapters), not by technical role
- Use `adapters/` instead of `infrastructure/` to be explicit about Hexagonal Architecture
- Make cross-context boundaries explicit (see **Bounded Contexts** section below)
- Place shared infrastructure (event bus, logging) at `internal/{shared}/` or `internal/events/`
## Code Examples
### Value Object — Money
```go
// internal/domain/shared/money.go
package shared
type Money struct {
amount int64 // cents — avoids float precision issues
currency string
}
func NewMoney(amount int64, currency string) (Money, error) {
if currency == "" {
return Money{}, errors.New("currency is required")
}
return Money{amount: amount, currency: currency}, nil
}
func (m Money) Add(other Money) (Money, error) {
if m.currency != other.currency {
return Money{}, fmt.Errorf("cannot add %s to %s", other.currency, m.currency)
}
return Money{amount: m.amount + other.amount, currency: m.currency}, nil
}
```
### Aggregate Root — Order
```go
// internal/domain/order/order.go
package order
type Order struct {
id string
items []Item
status Status
total shared.Money
}
func NewOrder(id string) *Order {
return &Order{id: id, status: StatusDraft}
}
// All mutations go through the aggregate root
func (o *Order) AddItem(item Item) error {
if o.status != StatusDraft {
return ErrOrderNotEditable
}
o.items = append(o.items, item)
return o.recalculateTotal()
}
func (o *Order) Place() (OrderPlaced, error) {
if len(o.items) == 0 {
return OrderPlaced{}, ErrEmptyOrder
}
o.status = StatusPlaced
return OrderPlaced{OrderID: o.id, Total: o.total}, nil
}
```
### Repository Interface — defined in domain
```go
// internal/order/domain/repository.go
package domain
type Repository interface {
Save(ctx context.Context, order *Order) error
FindByID(ctx context.Context, id string) (*Order, error)
}
```
The implementation lives in `internal/order/adapters/persistence/postgres.go` and depends on the domain — never the reverse.
### Application Service — orchestrates a use case
```go
// internal/order/application/place_order.go
package application
import (
"context"
"fmt"
"myapp/internal/order/domain"
)
type PlaceOrderHandler struct {
orders domain.Repository
events EventPublisher
}
func (h *PlaceOrderHandler) Handle(ctx context.Context, cmd PlaceOrderCommand) error {
order, err := h.orders.FindByID(ctx, cmd.OrderID)
if err != nil {
return fmt.Errorf("finding order: %w", err)
}
evt, err := order.Place()
if err != nil {
return fmt.Errorf("placing order: %w", err)
}
if err := h.orders.Save(ctx, order); err != nil {
return fmt.Errorf("saving order: %w", err)
}
return h.events.Publish(ctx, evt)
}
```
## Bounded Contexts
Each bounded context maps to a top-level package under `internal/` with its own domain, application, and adapters. Contexts communicate through domain events or explicit anti-corruption layers — never by importing each other's internal types directly.
**Anti-corruption layer example:** If `billing/` needs to consume an `order.OrderPlaced` event, translate it to a billing-specific type:
```go
// internal/billing/adapters/events/order_events.go
package events
import (
"myapp/internal/events"
"myapp/internal/billing/domain"
)
type OrderPlacedSubscriber struct {
invoices domain.InvoiceRepository
}
// Receives order.OrderPlaced, translates to billing domain
func (s *OrderPlacedSubscriber) OnOrderPlaced(evt events.OrderPlaced) error {
// Translate and create invoice
return s.invoices.Create(evt.OrderID, evt.Total)
}
```
This prevents billing from depending on order's internal types.
For large systems, each context can be its own Go module in a workspace (`go.work`). See the `samber/cc-skills-golang@golang-project-layout` skill for workspace setup.
## Wiring
Wire dependencies in `cmd/server/main.go` using manual constructor injection. → See `samber/cc-skills-golang@golang-dependency-injection` skill for DI library alternatives.
# Hexagonal Architecture (Ports & Adapters) in Go
## Table of Contents
- [When to Use](#when-to-use)
- [Core Concepts](#core-concepts)
- [Project Structure](#project-structure)
- [Code Examples](#code-examples)
- [Domain — pure business logic](#domain--pure-business-logic)
- [Ports — interfaces defined separately from implementations](#ports--interfaces-defined-separately-from-implementations)
- [Service — implements primary port, depends on secondary ports](#service--implements-primary-port-depends-on-secondary-ports)
- [Primary Adapter — HTTP handler calls the service port](#primary-adapter--http-handler-calls-the-service-port)
- [Secondary Adapter — implements a driven port](#secondary-adapter--implements-a-driven-port)
- [Multiple Entry Points](#multiple-entry-points)
- [Wiring](#wiring)
## When to Use
Apply hexagonal architecture when a service interacts with multiple external systems (databases, APIs, message queues, caches) and you want the domain logic fully decoupled from all of them. Particularly effective when the same business logic needs multiple entry points (HTTP, gRPC, CLI, message consumer). Do NOT use for simple CRUD apps or libraries.
## Core Concepts
- **Domain** — Business logic and types. No external dependencies.
- **Ports** — Interfaces that define how the domain interacts with the outside world.
- **Primary (driving) ports**: How the outside world calls into the domain (e.g., `OrderService` interface).
- **Secondary (driven) ports**: How the domain calls out to infrastructure (e.g., `OrderRepository`, `PaymentGateway` interfaces).
- **Adapters** — Concrete implementations of ports.
- **Primary adapters**: HTTP handlers, gRPC servers, CLI commands — they call primary ports.
- **Secondary adapters**: PostgreSQL repository, Stripe client, Redis cache — they implement secondary ports.
## Project Structure
```
order-service/
├── cmd/
│ ├── server/
│ │ └── main.go # HTTP server wiring
│ └── worker/
│ └── main.go # Message consumer wiring
├── internal/
│ ├── domain/
│ │ ├── order.go # Order entity + business rules
│ │ ├── item.go # OrderItem
│ │ └── status.go # OrderStatus enum
│ ├── port/
│ │ ├── incoming.go # Primary ports (OrderService interface)
│ │ └── outgoing.go # Secondary ports (OrderRepository, PaymentGateway)
│ ├── service/
│ │ └── order_service.go # Implements primary ports — orchestrates domain + secondary ports
│ └── adapter/
│ ├── primary/
│ │ ├── http/
│ │ │ ├── router.go
│ │ │ └── order_handler.go # HTTP adapter — calls OrderService
│ │ └── grpc/
│ │ └── order_server.go # gRPC adapter — calls OrderService
│ └── secondary/
│ ├── postgres/
│ │ └── order_repo.go # Implements OrderRepository
│ └── stripe/
│ └── payment.go # Implements PaymentGateway
├── go.mod
└── go.sum
```
## Code Examples
### Domain — pure business logic
```go
// internal/domain/order.go
package domain
type Order struct {
ID string
Items []Item
Status OrderStatus
}
func (o *Order) Ship() error {
if o.Status != StatusPaid {
return ErrOrderNotPaid
}
o.Status = StatusShipped
return nil
}
```
### Ports — interfaces defined separately from implementations
```go
// internal/port/incoming.go
package port
// Primary port — how the outside world drives the application
type OrderService interface {
PlaceOrder(ctx context.Context, items []domain.Item) (string, error)
ShipOrder(ctx context.Context, orderID string) error
GetOrder(ctx context.Context, orderID string) (*domain.Order, error)
}
```
```go
// internal/port/outgoing.go
package port
// Secondary ports — how the application reaches external systems
type OrderRepository interface {
Save(ctx context.Context, order *domain.Order) error
FindByID(ctx context.Context, id string) (*domain.Order, error)
}
type PaymentGateway interface {
Charge(ctx context.Context, orderID string, amount int64) error
}
```
### Service — implements primary port, depends on secondary ports
```go
// internal/service/order_service.go
package service
type orderService struct {
orders port.OrderRepository
payments port.PaymentGateway
}
func NewOrderService(orders port.OrderRepository, payments port.PaymentGateway) port.OrderService {
return &orderService{orders: orders, payments: payments}
}
func (s *orderService) PlaceOrder(ctx context.Context, items []domain.Item) (string, error) {
order := domain.NewOrder(items)
if err := s.payments.Charge(ctx, order.ID, order.Total()); err != nil {
return "", fmt.Errorf("charging payment: %w", err)
}
if err := s.orders.Save(ctx, order); err != nil {
return "", fmt.Errorf("saving order: %w", err)
}
return order.ID, nil
}
```
### Primary Adapter — HTTP handler calls the service port
```go
// internal/adapter/primary/http/order_handler.go
package http
type OrderHandler struct {
svc port.OrderService
}
func NewOrderHandler(svc port.OrderService) *OrderHandler {
return &OrderHandler{svc: svc}
}
func (h *OrderHandler) HandlePlaceOrder(w http.ResponseWriter, r *http.Request) {
var req PlaceOrderRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "invalid request", http.StatusBadRequest)
return
}
id, err := h.svc.PlaceOrder(r.Context(), req.Items)
if err != nil {
http.Error(w, err.Error(), mapToHTTPStatus(err))
return
}
json.NewEncoder(w).Encode(map[string]string{"id": id})
}
```
### Secondary Adapter — implements a driven port
```go
// internal/adapter/secondary/postgres/order_repo.go
package postgres
type OrderRepo struct {
db *sql.DB
}
func NewOrderRepo(db *sql.DB) *OrderRepo {
return &OrderRepo{db: db}
}
func (r *OrderRepo) Save(ctx context.Context, order *domain.Order) error {
// SQL upsert
}
func (r *OrderRepo) FindByID(ctx context.Context, id string) (*domain.Order, error) {
// SQL query
}
```
## Multiple Entry Points
The hexagonal approach shines when the same `OrderService` is called from different primary adapters — HTTP for external clients, gRPC for internal services, a message consumer for async events. Each adapter is wired in its own `cmd/` entry point.
## Wiring
Construct adapters and inject them in `cmd/server/main.go`. → See `samber/cc-skills-golang@golang-dependency-injection` skill for DI library alternatives.
# Resource Management Patterns
## Table of Contents
- [Defer Close Immediately](#defer-close-immediately)
- [`runtime.AddCleanup` over `runtime.SetFinalizer`](#runtimeaddcleanup-over-runtimesetfinalizer)
- [Resource Pools](#resource-pools)
- [Graceful Shutdown](#graceful-shutdown)
## Defer Close Immediately
`defer Close()` MUST be called immediately after opening — NEVER delay. This prevents leaks when code is modified later and new return paths are added:
```go
// Good — defer is right next to open
f, err := os.Open(path)
if err != nil {
return err
}
defer f.Close()
// Bad — Close() is far from Open(), easy to forget when adding early returns
f, err := os.Open(path)
if err != nil {
return err
}
// ... 50 lines of code ...
f.Close() // might never run if a new return is added above
```
This applies to all closeable resources: files, SQL rows, HTTP response bodies, gzip readers, bufio scanners wrapping readers, etc.
```go
resp, err := http.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
rows, err := db.QueryContext(ctx, query)
if err != nil {
return err
}
defer rows.Close()
```
## `runtime.AddCleanup` over `runtime.SetFinalizer`
`runtime.AddCleanup` SHOULD be preferred over `runtime.SetFinalizer` (Go 1.24+):
```go
type Resource struct {
handle uintptr
}
func NewResource() *Resource {
r := &Resource{handle: acquireHandle()}
runtime.AddCleanup(r, func(handle uintptr) {
releaseHandle(handle)
}, r.handle)
return r
}
```
`AddCleanup` is preferred because:
- Multiple cleanups can be attached to the same object
- The cleanup function receives a copy of the value, not the object itself — no resurrection risk
- Cleanups run even if the object is part of a cycle
## Resource Pools
Resource pools SHOULD use channels with a fixed capacity for bounded allocation. Use channel-based pools or `sync.Pool` to manage limited resources between consumers. Always set a maximum size:
```go
type ConnPool struct {
conns chan *Conn
}
func NewConnPool(maxSize int, factory func() (*Conn, error)) (*ConnPool, error) {
pool := &ConnPool{
conns: make(chan *Conn, maxSize),
}
// Pre-fill with initial connections
for range maxSize {
conn, err := factory()
if err != nil {
return nil, fmt.Errorf("creating connection: %w", err)
}
pool.conns <- conn
}
return pool, nil
}
func (p *ConnPool) Get(ctx context.Context) (*Conn, error) {
select {
case conn := <-p.conns:
return conn, nil
case <-ctx.Done():
return nil, ctx.Err()
}
}
func (p *ConnPool) Put(conn *Conn) {
select {
case p.conns <- conn:
default:
conn.Close() // pool is full, discard
}
}
```
## Graceful Shutdown
Graceful shutdown MUST use `signal.NotifyContext` for clean termination. All resources (connections, files, channels) MUST be drained before process exit. Use `os/signal` and context cancellation:
```go
func main() {
ctx, stop := signal.NotifyContext(context.Background(),
syscall.SIGINT, syscall.SIGTERM,
)
defer stop()
srv := &http.Server{Addr: ":8080", Handler: router}
// Start server in background
go func() {
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
slog.Error("server error", "error", err)
}
}()
slog.Info("server started", "addr", ":8080")
// Wait for interrupt signal
<-ctx.Done()
slog.Info("shutting down...")
// Give outstanding requests time to complete
shutdownCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if err := srv.Shutdown(shutdownCtx); err != nil {
slog.Error("shutdown error", "error", err)
}
// Close other resources: database connections, message queues, etc.
db.Close()
slog.Info("shutdown complete")
}
```
This pattern applies to any long-running service — gRPC servers, message consumers, background workers. The key elements are:
1. Capture OS signals with `signal.NotifyContext`
2. Start the server in a goroutine
3. Block on context cancellation
4. Shut down with a timeout to drain in-flight requests
5. Close all remaining resources in order
For goroutine shutdown patterns, see the `samber/cc-skills-golang@golang-concurrency` skill.
......@@ -2,12 +2,85 @@
Sincroniza estudiantes (con padres y planes de pago) desde PostgreSQL hacia MongoDB mediante sondeo completo cada N minutos.
## Ejecución rápida
```bash
go run ./cmd/server
```
El proceso lee el `.env` del directorio raíz, levanta Postgres/Mongo, arranca un scheduler por pipeline y expone la API en `PORT` (8080 por defecto). Los pipelines no corren al arrancar: el primer ciclo ocurre según el horario configurado.
Disparar un pipeline a mano y consultar su estado:
```bash
curl -s -X POST localhost:8080/api/v1/sync/students/trigger
curl -s localhost:8080/api/v1/sync/students/status
```
Verificar conectividad antes de sincronizar:
```bash
curl -s localhost:8080/api/v1/health
```
### Pipelines
| Pipeline | Colección Mongo | `IDField` | Docs esperados | Ciclo medido |
|---|---|---|---|---|
| `students` | `students` | `student_id` | ~36 mil | segundos |
| `payment_plans` | `payment_plans` | `payment_plan_id` | cientos de miles | segundos |
| `parents` | `parents` | `parent_id` | decenas de miles | segundos |
| `users` | `users` | `user_id` | miles | segundos |
| `professors` | `professors` | `professor_id` | miles | segundos |
| `attendance` | `c_attendance` | `attendance_id` | **~321 mil** | **~56 min** (estimado) |
Los tiempos de los cinco pipelines chicos son de segundos; el de `attendance` es una extrapolación (lectura medida completa + upsert medido sobre 20 mil documentos), porque el ciclo completo no llega a terminar — ver la advertencia más abajo.
Cada pipeline se dispara y se consulta reemplazando el nombre en la ruta: `/api/v1/sync/<pipeline>/trigger` y `/api/v1/sync/<pipeline>/status`. Los endpoints se registran solos a partir de `config.Pipelines`.
El `trigger` es **síncrono**: la respuesta no vuelve hasta que el ciclo termina. Para pipelines grandes (>1 min) conviene dispararlo en segundo plano:
```bash
curl -s -X POST localhost:8080/api/v1/sync/attendance/trigger > /tmp/attendance.log &
curl -s localhost:8080/api/v1/sync/attendance/status
```
### Antes del primer ciclo
- Cada colección necesita **índice único** sobre su `IDField` (`student_id`, `attendance_id`, etc.); el código no lo crea. Sin él `BulkUpsert` matchea un documento arbitrario entre los duplicados, y `MoveToDeleted` archiva y borra solo uno por ciclo, así que los duplicados se acumulan en la colección viva.
- La tabla `sync_state` se crea sola al arrancar, con una fila por `StateID` (1–6). Si agregás un pipeline con un `StateID` nuevo, agregá también el `VALUES (...)` del seed en `internal/infrastructure/database/postgres/client.go`, o el arranque falla al leer el estado.
- `attendance` exige además un índice sobre `ac_asistencia(matricula_id, asistencia_fecha)`.
### ⚠️ `attendance` no entra en el timeout del scheduler
`internal/usecase/scheduler.go` impone un timeout duro de **4 minutos por ciclo**. Medido contra el entorno real, el ciclo de `attendance` tarda **~56 minutos**:
| fase | tiempo |
|---|---|
| lectura de Postgres a memoria | 2m05s (1.5 GB de heap, 321 mil documentos) |
| hashing `row_hash` | ~4s |
| `BulkUpsert` a Mongo remoto | **~54 min** (~100 docs/s) |
Con el contexto cancelado a los 4 min el `BulkWrite` se aborta a medias y `sync_state` nunca avanza, así que el ciclo **nunca completa**. Mientras tanto el `/status` va a mostrar el `last_error`.
Opciones, de menor a mayor effort:
1. Subir `cycleTimeout` en `internal/usecase/scheduler.go` (afecta a todos los pipelines) o hacerlo configurable por pipeline vía env.
2. Procesar en lotes de N matrículas por ciclo en vez de los 321 mil de una vez.
3. Reducir el alcance del documento a un solo mes en vez de todo el año.
No pongas `attendance` en `MODE=daily` hasta resolver esto.
### Horarios
Cada pipeline tiene su propio horario vía `SYNC_<NOMBRE>_{MODE,TIME,INTERVAL}` (ver Configuración más abajo). El scheduler corre un ciclo por pipeline en paralelo, no en serie: los cinco pipelines chicos conviven sin problema, pero `attendance` monopoliza la conexión de Mongo durante toda su hora de escritura.
## Configuración
1. La tabla `sync_state` se crea/inicializa automáticamente al arrancar (fila `id=1` estudiantes) — no se requiere paso de migración manual (`migrations/0001_create_sync_state.sql` se conserva como referencia).
1. La tabla `sync_state` se crea/inicializa automáticamente al arrancar, con una fila por pipeline (`id` 1 a 6: students, payment_plans, parents, users, professors, attendance) — no se requiere paso de migración manual (`migrations/0001_create_sync_state.sql` se conserva como referencia). El seed está en `internal/infrastructure/database/postgres/client.go`: si agregás un pipeline con `StateID` nuevo, agregá el `VALUES (...)` ahí o el arranque falla con `no rows in result set`.
2. Asegúrate de que la colección `students` exista en Mongo con el validador `$jsonSchema` provisto (requeridos: `student_id` int, `enrollment_id` int). La colección `deleted_students` archiva los estudiantes eliminados en el origen — no requiere configuración de esquema.
3. Define las variables de entorno: `PG_DSN`, `MONGO_URI`, `MONGO_DB=intranet` (o tu base de datos), `SYNC_INTERVAL` (por defecto `5m`), `PORT` (por defecto `8080`). Los nombres de función PG / colección Mongo por pipeline ya no son variables de entorno — se definen en `internal/infrastructure/config/pipelines.go`. Agrega un nuevo pipeline añadiendo una entrada ahí, no variables de entorno.
4. Horario por pipeline (opcional, `SYNC_<NOMBRE>_...` en mayúsculas, ej. `SYNC_STUDENTS_MODE`, `SYNC_PAYMENT_PLANS_MODE`, `SYNC_PARENTS_MODE`):
4. Horario por pipeline (opcional, `SYNC_<NOMBRE>_...` en mayúsculas, ej. `SYNC_STUDENTS_MODE`, `SYNC_PAYMENT_PLANS_MODE`, `SYNC_PARENTS_MODE`, `SYNC_USERS_MODE`, `SYNC_PROFESSORS_MODE`, `SYNC_ATTENDANCE_MODE`):
- `SYNC_<NOMBRE>_MODE`: `interval` (por defecto) o `daily`.
- `SYNC_<NOMBRE>_INTERVAL`: duración tipo `5m`/`1h` (modo `interval`; si falta, usa `SYNC_INTERVAL`).
- `SYNC_<NOMBRE>_TIME`: hora `HH:MM` (modo `daily`, obligatoria en ese modo). Ej: `SYNC_STUDENTS_MODE=daily` + `SYNC_STUDENTS_TIME=03:00` corre estudiantes una vez al día a las 3am.
......@@ -22,6 +95,8 @@ Todos los endpoints llevan el prefijo `/api/v1`.
- `POST /api/v1/sync/payment_plans/trigger` / `GET /api/v1/sync/payment_plans/status` — pipeline de planes de pago (misma forma).
- `POST /api/v1/sync/parents/trigger` / `GET /api/v1/sync/parents/status` — pipeline de padres/apoderados (misma forma).
- `POST /api/v1/sync/users/trigger` / `GET /api/v1/sync/users/status` — pipeline de usuarios (misma forma).
- `POST /api/v1/sync/professors/trigger` / `GET /api/v1/sync/professors/status` — pipeline de profesores (misma forma).
- `POST /api/v1/sync/attendance/trigger` / `GET /api/v1/sync/attendance/status` — pipeline de asistencia (misma forma, pero ver la advertencia de timeout arriba).
## Estructura del proyecto (arquitectura limpia)
......@@ -58,6 +133,27 @@ Padres/apoderados: une `persona.pe_persona` con una subconsulta agregada sobre `
Usuarios: una fila por login (`user_id`, `user_login`, `user_password`, `user_creation_date`, `parent_id`, `user_status`). Upsert por `user_id`.
Asistencia: `configuracion.co_calendario` cruzado con los alumnos del ciclo 28 / periodo 14 (`ac_aula`), con `LEFT JOIN` a `academico.ac_asistencia` por `(matricula_id, asistencia_fecha)`. El origen devuelve **una fila por alumno y día**; el reader las agrupa en **un documento por alumno y mes** (`registros` con un item por día del calendario). Upsert por `attendance_id`.
Dos detalles que no son obvios en el origen:
- `ac_asistencia` tiene más de una fila para el mismo `(matricula_id, asistencia_fecha)` (189 pares solo en el ciclo 28). El CTE `asistencia_dia` deduplica con `DISTINCT ON` quedándose con la fila de `fecha_hora_registro` más reciente; sin eso `registros` repetiría días y el `row_hash` nunca convergería.
- El origen **no trae `attendance_id`**. Se compone en el reader como `matricula_id * 100 + mes` (`postgres.BuildAttendanceID`), porque un alumno tiene un documento por mes.
El query está acotado a `calendario_fecha <= CURRENT_DATE` sobre el año en curso, así que el mes en curso queda parcial y, el 1 de enero, la reconciliación de borrados archiva los documentos del año anterior a `deleted_c_attendance`.
Semántica de `resumen_mes` (`postgres.summarize`):
| campo | significado |
|---|---|
| `dias_calendario` | días del mes presentes en `co_calendario` |
| `feriados` | de esos, los marcados como feriado |
| `dias_habiles` | días **con registro** de asistencia |
| `presentes` / `tardanzas` / `faltas` | días con registro de ese tipo |
| `faltas_justificadas` | faltas con `justifico = true` |
Un día hábil sin registro no cuenta como falta, porque el origen no lo reporta.
## Comportamiento de sincronización
Cada ciclo tiene dos fases:
......
package entities
import "time"
// AttendanceRecord es un día suelto del calendario del alumno. Los días sin registro de
// asistencia llegan igual, con Type vacío y AttendanceID nil.
type AttendanceRecord struct {
AttendanceID *int `bson:"asistencia_id" json:"asistencia_id"`
Date string `bson:"fecha" json:"fecha"`
Holiday bool `bson:"es_feriado" json:"es_feriado"`
EntryTime *string `bson:"hora_ingreso" json:"hora_ingreso"`
Type string `bson:"tipo" json:"tipo"`
Justified bool `bson:"justificado" json:"justificado"`
JustificationCause *string `bson:"motivo_justificacion" json:"motivo_justificacion"`
}
// AttendanceSummary agrega los contadores del mes del alumno.
type AttendanceSummary struct {
CalendarDays int `bson:"dias_calendario" json:"dias_calendario"`
WorkingDays int `bson:"dias_habiles" json:"dias_habiles"`
Holidays int `bson:"feriados" json:"feriados"`
Present int `bson:"presentes" json:"presentes"`
Late int `bson:"tardanzas" json:"tardanzas"`
Absences int `bson:"faltas" json:"faltas"`
JustifiedAbsences int `bson:"faltas_justificadas" json:"faltas_justificadas"`
}
// Attendance es un documento por alumno por mes: el id de negocio se compone de la
// matrícula y el mes (attendance_id), no de una columna del origen.
type Attendance struct {
AttendanceID int `bson:"attendance_id" json:"attendance_id"`
StudentID int `bson:"estudiante_id" json:"estudiante_id"`
EnrollmentID int `bson:"matricula_id" json:"matricula_id"`
CycleID int `bson:"ciclo_id" json:"ciclo_id"`
AcademicPeriodID int `bson:"periodo_academico_id" json:"periodo_academico_id"`
Month int `bson:"mes" json:"mes"`
MonthDescription string `bson:"mes_descripcion" json:"mes_descripcion"`
Records []AttendanceRecord `bson:"registros" json:"registros"`
MonthSummary AttendanceSummary `bson:"resumen_mes" json:"resumen_mes"`
CreatedAt time.Time `bson:"created_at" json:"created_at"`
UpdatedAt time.Time `bson:"updated_at" json:"updated_at"`
RowHash string `bson:"row_hash,omitempty" json:"-"`
}
func (r *Attendance) SetUpdatedAt(t time.Time) {
r.UpdatedAt = t
}
func (r *Attendance) SetRowHash(h string) {
r.RowHash = h
}
func (r *Attendance) SetCreatedAt(t time.Time) {
r.CreatedAt = t
}
......@@ -54,4 +54,12 @@ var Pipelines = []PipelineDef{
IDField: "professor_id",
StateID: 5,
},
{
Name: "attendance",
PGQuery: sql.AttendanceQuery,
MongoCollection: "c_attendance",
MongoDeletedCollection: "deleted_c_attendance",
IDField: "attendance_id",
StateID: 6,
},
}
package postgres
import (
"context"
"fmt"
"sort"
"time"
"intranet-synchronizer/internal/domain/entities"
"intranet-synchronizer/internal/domain/repositories"
)
const dateLayout = "2006-01-02"
var monthDescriptions = [...]string{
"Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio",
"Julio", "Agosto", "Setiembre", "Octubre", "Noviembre", "Diciembre",
}
// BuildAttendanceID compone el id de negocio del documento: matrícula * 100 + mes.
// El origen no trae esta columna, se deriva acá porque un alumno tiene un documento por mes.
func BuildAttendanceID(enrollmentID, month int) int {
return enrollmentID*100 + month
}
func monthDescription(month int) string {
if month < 1 || month > len(monthDescriptions) {
return ""
}
return monthDescriptions[month-1]
}
type AttendanceReader struct {
pool *Pool
query string
}
func NewAttendanceReader(pool *Pool, query string) repositories.SourceReader {
return &AttendanceReader{pool: pool, query: query}
}
func (r *AttendanceReader) FetchAll(ctx context.Context) ([]entities.SyncRow, error) {
rows, err := r.pool.Pool.Query(ctx, r.query)
if err != nil {
return nil, fmt.Errorf("query attendance: %w", err)
}
defer rows.Close()
docs := make(map[int]*entities.Attendance)
for rows.Next() {
var (
enrollmentID int
studentID int
cycleID int
academicPeriodID int
month int
date time.Time
isHoliday bool
recordID *int
entryTime *string
attendanceType string
justified bool
justificationText *string
)
if err := rows.Scan(
&enrollmentID,
&studentID,
&cycleID,
&academicPeriodID,
&month,
&date,
&isHoliday,
&recordID,
&entryTime,
&attendanceType,
&justified,
&justificationText,
); err != nil {
return nil, fmt.Errorf("scan attendance row: %w", err)
}
attendanceID := BuildAttendanceID(enrollmentID, month)
doc, ok := docs[attendanceID]
if !ok {
doc = &entities.Attendance{
AttendanceID: attendanceID,
StudentID: studentID,
EnrollmentID: enrollmentID,
CycleID: cycleID,
AcademicPeriodID: academicPeriodID,
Month: month,
MonthDescription: monthDescription(month),
Records: make([]entities.AttendanceRecord, 0, daysInMonth(date)),
}
docs[attendanceID] = doc
}
doc.Records = append(doc.Records, entities.AttendanceRecord{
AttendanceID: recordID,
Date: date.Format(dateLayout),
Holiday: isHoliday,
EntryTime: entryTime,
Type: attendanceType,
Justified: justified,
JustificationCause: justificationText,
})
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("iterate attendance rows: %w", err)
}
attendanceIDs := make([]int, 0, len(docs))
for id := range docs {
attendanceIDs = append(attendanceIDs, id)
}
sort.Ints(attendanceIDs)
result := make([]entities.SyncRow, 0, len(docs))
for _, id := range attendanceIDs {
doc := docs[id]
sort.SliceStable(doc.Records, func(i, j int) bool {
return doc.Records[i].Date < doc.Records[j].Date
})
doc.MonthSummary = summarize(doc.Records)
result = append(result, entities.SyncRow{ID: id, Doc: doc})
}
return result, nil
}
// summarize cuenta sobre los días del mes: dias_calendario son todos los del calendario,
// feriados los marcados como tal, y dias_habiles los que tienen registro de asistencia.
// Un día hábil sin registro no cuenta como falta, porque el origen no lo reporta.
func summarize(records []entities.AttendanceRecord) entities.AttendanceSummary {
summary := entities.AttendanceSummary{CalendarDays: len(records)}
for _, rec := range records {
if rec.Holiday {
summary.Holidays++
}
if rec.AttendanceID == nil {
continue
}
summary.WorkingDays++
switch rec.Type {
case "asistencia":
summary.Present++
case "tardanza":
summary.Late++
case "falta":
summary.Absences++
if rec.Justified {
summary.JustifiedAbsences++
}
}
}
return summary
}
func daysInMonth(date time.Time) int {
return time.Date(date.Year(), date.Month(), 1, 0, 0, 0, 0, date.Location()).AddDate(0, 1, -1).Day()
}
......@@ -29,7 +29,7 @@ CREATE TABLE IF NOT EXISTS sync_state (
);
INSERT INTO sync_state (id, last_synced_at)
VALUES (1, '1970-01-01T00:00:00Z'), (2, '1970-01-01T00:00:00Z'), (3, '1970-01-01T00:00:00Z'), (4, '1970-01-01T00:00:00Z'), (5, '1970-01-01T00:00:00Z')
VALUES (1, '1970-01-01T00:00:00Z'), (2, '1970-01-01T00:00:00Z'), (3, '1970-01-01T00:00:00Z'), (4, '1970-01-01T00:00:00Z'), (5, '1970-01-01T00:00:00Z'), (6, '1970-01-01T00:00:00Z')
ON CONFLICT (id) DO NOTHING;
`
......
package sql
// AttendanceQuery devuelve una fila por alumno y por día del calendario del año en curso
// (hasta hoy), con la asistencia del día si existe. El lector agrupa esas filas en un
// documento por alumno y mes (attendance_id = matricula_id * 100 + mes).
//
// ac_asistencia tiene más de una fila para el mismo (matricula_id, asistencia_fecha), así que
// asistencia_dia se deduplica con DISTINCT ON quedándose con la fila más reciente; sin eso el
// cross join devolvería días repetidos y el array registros dejaría de tener un item por día.
const AttendanceQuery = `
WITH asistencia_dia AS (SELECT DISTINCT ON (a.matricula_id, a.asistencia_fecha)
a.matricula_id,
a.asistencia_fecha,
a.asistencia_id,
a.hora_ingreso,
a.tipo_asistencia_id,
COALESCE(a.justifico, false) as justifico,
a.justifico_observacion
FROM academico.ac_asistencia a
INNER JOIN matricula.ma_matricula m ON m.matricula_id = a.matricula_id
INNER JOIN academico.ac_aula au ON au.aula_id = m.aula_id_asiste
WHERE NOT m.matricula_retirado
AND NOT m.matricula_anulada
AND au.periodo_academico_id = 14
AND au.ciclo_id = 28
AND EXTRACT('YEAR' FROM a.asistencia_fecha) = EXTRACT('YEAR' FROM CURRENT_DATE)
AND a.asistencia_fecha <= CURRENT_DATE
ORDER BY a.matricula_id, a.asistencia_fecha,
a.fecha_hora_registro DESC NULLS LAST, a.asistencia_id DESC
), calendario AS (SELECT C.calendario_fecha as fecha,
C.calendario_es_feriado as es_feriado
FROM configuracion.co_calendario C
WHERE EXTRACT('YEAR' FROM C.calendario_fecha) = EXTRACT('YEAR' FROM CURRENT_DATE)
AND C.calendario_fecha <= CURRENT_DATE
), alumno AS (SELECT M.matricula_id,
e.estudiante_id,
au.ciclo_id,
au.periodo_academico_id
FROM matricula.ma_matricula M
INNER JOIN matricula.ma_estudiante e ON e.estudiante_id = M.estudiante_id
INNER JOIN persona.pe_persona P ON P.persona_id = e.persona_id
INNER JOIN academico.ac_aula au ON au.aula_id = M.aula_id_asiste
WHERE NOT M.matricula_retirado
AND NOT M.matricula_anulada
AND au.periodo_academico_id = 14
AND au.ciclo_id = 28
)
SELECT alumno.matricula_id as enrollment_id,
alumno.estudiante_id as student_id,
alumno.ciclo_id as cycle_id,
alumno.periodo_academico_id as academic_period_id,
EXTRACT('MONTH' FROM calendario.fecha) as attendance_month,
calendario.fecha as attendance_date,
calendario.es_feriado as is_holiday,
A.asistencia_id as attendance_row_id,
A.hora_ingreso as entry_time,
CASE A.tipo_asistencia_id
WHEN 1 THEN 'asistencia'
WHEN 2 THEN 'tardanza'
WHEN 3 THEN 'falta'
WHEN 4 THEN 'no_corresponde'
ELSE ''
END as attendance_type,
COALESCE(A.justifico, false) as justified,
A.justifico_observacion as justification_cause
FROM alumno
CROSS JOIN calendario
LEFT JOIN asistencia_dia A
ON A.matricula_id = alumno.matricula_id
AND A.asistencia_fecha = calendario.fecha
ORDER BY alumno.matricula_id, EXTRACT('MONTH' FROM calendario.fecha), calendario.fecha;
`
......@@ -26,6 +26,8 @@ func readerFor(name string, pool *postgres.Pool, query string) (repositories.Sou
return postgres.NewUserReader(pool, query), nil
case "professors":
return postgres.NewProfessorReader(pool, query), nil
case "attendance":
return postgres.NewAttendanceReader(pool, query), nil
default:
return nil, fmt.Errorf("no reader wired for pipeline %q", name)
}
......
{
"version": 1,
"skills": {
"golang-concurrency": {
"source": "samber/cc-skills-golang",
"sourceType": "github",
"skillPath": "skills/golang-concurrency/SKILL.md",
"computedHash": "f76a7af92805c94c91b7aea0f743e20c4613ca346203cbd7f0e9d296a7970385"
}
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment