Commit 08415506 by Percy Quispe Huarcaya

feat: agregar sync balotarios

parent e760316c
...@@ -28,7 +28,7 @@ No Makefile/linter config present, no test suite — use plain `go` toolchain co ...@@ -28,7 +28,7 @@ No Makefile/linter config present, no test suite — use plain `go` toolchain co
1. `sync_state` table is auto-bootstrapped at startup (`Pool.BootstrapSchema`, seeds `id=1` students row) — no manual migration step required, though the SQL files under `migrations/` are kept for reference/manual runs. 1. `sync_state` table is auto-bootstrapped at startup (`Pool.BootstrapSchema`, seeds `id=1` students row) — no manual migration step required, though the SQL files under `migrations/` are kept for reference/manual runs.
2. Mongo `students` collection must exist with a `$jsonSchema` validator requiring `student_id` int and `enrollment_id` int. A `deleted_students` collection archives students removed at the source — no schema setup needed for it. 2. Mongo `students` collection must exist with a `$jsonSchema` validator requiring `student_id` int and `enrollment_id` int. A `deleted_students` collection archives students removed at the source — no schema setup needed for it.
3. Required env vars: `PG_DSN`, `MONGO_URI`, `MONGO_DB`. Optional: `SYNC_INTERVAL` (default `5m`), `PORT` (default `8080`). Per-pipeline PG function name (or raw `PGQuery`) / Mongo collection / deleted-collection / id field / `sync_state` id are **not** env vars — they're declared in `internal/infrastructure/config/pipelines.go` (`Pipelines []PipelineDef`). Add a new sync pipeline by adding an entry there; `internal/infrastructure/pipeline.Build` loops over `config.Pipelines` to wire reader/upserter/mover/state/service/scheduler for each. 3. Required env vars: `PG_DSN`, `MONGO_URI`, `MONGO_DB`. Optional: `SYNC_INTERVAL` (default `5m`), `PORT` (default `8080`), `SCHEDULERS_ENABLED` (default `true`; `false` apaga todos los schedulers y deja solo los triggers HTTP) y `SYNC_<NAME>_ENABLED` (default `true`; `false` apaga el scheduler solo de ese módulo, que igual queda accesible por HTTP) y la configuración explícita de pools: `PG_POOL_MAX_CONNS`/`PG_POOL_MIN_CONNS`/`PG_POOL_MAX_CONN_LIFETIME`/`PG_POOL_MAX_CONN_IDLE_TIME` (pgxpool) y `MONGO_POOL_MAX_SIZE`/`MONGO_POOL_MIN_SIZE`/`MONGO_POOL_MAX_IDLE_TIME` (driver de Mongo); vacío o `0` deja el valor por defecto del driver. Per-pipeline PG function name (or raw `PGQuery`) / Mongo collection / deleted-collection / id field / `sync_state` id are **not** env vars — they're declared in `internal/infrastructure/config/pipelines.go` (`Pipelines []PipelineDef`). Add a new sync pipeline by adding an entry there; `internal/infrastructure/pipeline.Build` loops over `config.Pipelines` to wire reader/upserter/mover/state/service/scheduler for each.
4. Per-pipeline schedule (interval vs. fixed daily time) IS configurable via env vars, unlike the other pipeline settings above: `SYNC_<NAME>_MODE` (`interval` default, or `daily`), `SYNC_<NAME>_INTERVAL` (falls back to `SYNC_INTERVAL`), `SYNC_<NAME>_TIME` (`HH:MM`, required when `MODE=daily`). `<NAME>` is the pipeline name uppercased (`SYNC_STUDENTS_MODE`, `SYNC_PAYMENT_PLANS_MODE`, `SYNC_PARENTS_MODE`). Built by `config.ScheduleFor` into an `internal/usecase.Schedule` (`IntervalSchedule` or `DailySchedule`), consumed by `usecase.NewScheduler`. Example — run every pipeline once a day at 1am (current `.env`): 4. Per-pipeline schedule (interval vs. fixed daily time) IS configurable via env vars, unlike the other pipeline settings above: `SYNC_<NAME>_MODE` (`interval` default, or `daily`), `SYNC_<NAME>_INTERVAL` (falls back to `SYNC_INTERVAL`), `SYNC_<NAME>_TIME` (`HH:MM`, required when `MODE=daily`). `<NAME>` is the pipeline name uppercased (`SYNC_STUDENTS_MODE`, `SYNC_PAYMENT_PLANS_MODE`, `SYNC_PARENTS_MODE`). Built by `config.ScheduleFor` into an `internal/usecase.Schedule` (`IntervalSchedule` or `DailySchedule`), consumed by `usecase.NewScheduler`. Example — run every pipeline once a day at 1am (current `.env`):
``` ```
SYNC_STUDENTS_MODE=daily SYNC_STUDENTS_MODE=daily
......
...@@ -71,3 +71,58 @@ Cada ciclo tiene dos fases: ...@@ -71,3 +71,58 @@ Cada ciclo tiene dos fases:
- **Registro eliminado**: id presente en Mongo pero ya no devuelto por el origen Postgres → el documento se mueve (no solo se elimina) a la colección de archivo (`deleted_students`) con una marca `deleted_at`, contado como `Deleted`. - **Registro eliminado**: id presente en Mongo pero ya no devuelto por el origen Postgres → el documento se mueve (no solo se elimina) a la colección de archivo (`deleted_students`) con una marca `deleted_at`, contado como `Deleted`.
El estado persistido (`sync_state`) solo avanza si el ciclo completo (hash/upsert + reconciliación de borrados) tiene éxito; cualquier fallo se corta y se reporta vía `/api/v1/sync/<módulo>/status`. El estado persistido (`sync_state`) solo avanza si el ciclo completo (hash/upsert + reconciliación de borrados) tiene éxito; cualquier fallo se corta y se reporta vía `/api/v1/sync/<módulo>/status`.
## ENV Configuration
Crea un archivo `.env` en la raíz del proyecto basado en el siguiente ejemplo:
```env
PG_DSN=postgres://user:pass@host:port/database
MONGO_URI=mongodb://user:pass@host:port/?authSource=admin
MONGO_DB=database_name
SYNC_INTERVAL=5m
PORT=8080
SYNC_STUDENTS_MODE=daily
SYNC_STUDENTS_TIME=01:00
SYNC_PAYMENT_PLANS_MODE=daily
SYNC_PAYMENT_PLANS_TIME=01:00
SYNC_PARENTS_MODE=daily
SYNC_PARENTS_TIME=01:00
SYNC_USERS_MODE=daily
SYNC_USERS_TIME=01:00
SYNC_PROFESSORS_MODE=daily
SYNC_PROFESSORS_TIME=01:00
SYNC_ATTENDANCE_MODE=daily
SYNC_ATTENDANCE_TIME=01:00
SCHEDULERS_ENABLED=false
# Habilitación de schedulers por módulo (true/false). El global SCHEDULERS_ENABLED apaga todos.
SYNC_STUDENTS_ENABLED=true
SYNC_PAYMENT_PLANS_ENABLED=true
SYNC_PARENTS_ENABLED=true
SYNC_USERS_ENABLED=true
SYNC_PROFESSORS_ENABLED=true
SYNC_BALOTARIOS_ENABLED=false
SYNC_BALOTARIOS_INCREMENTAL_ENABLED=true
SYNC_ATTENDANCE_ENABLED=true
SYNC_HORARIO_ENABLED=true
SYNC_MENSAJES_ENABLED=true
SYNC_COMUNICADOS_ENABLED=true
# Pool de conexiones Postgres (pgxpool). 0 = usar el valor por defecto del driver.
PG_POOL_MAX_CONNS=10
PG_POOL_MIN_CONNS=0
PG_POOL_MAX_CONN_LIFETIME=1h
PG_POOL_MAX_CONN_IDLE_TIME=30m
# Pool de conexiones Mongo. 0 = usar el valor por defecto del driver.
MONGO_POOL_MAX_SIZE=100
MONGO_POOL_MIN_SIZE=0
MONGO_POOL_MAX_IDLE_TIME=10m
```
...@@ -29,18 +29,35 @@ func main() { ...@@ -29,18 +29,35 @@ func main() {
log.Fatalf("config error: %v", err) log.Fatalf("config error: %v", err)
} }
pool, err := postgres.NewPool(bootCtx, cfg.PGDSN) pool, err := postgres.NewPool(bootCtx, cfg.PGDSN, postgres.PoolOptions{
MaxConns: cfg.PGPoolMaxConns,
MinConns: cfg.PGPoolMinConns,
MaxConnLifetime: cfg.PGPoolMaxConnLifetime,
MaxConnIdleTime: cfg.PGPoolMaxConnIdleTime,
})
if err != nil { if err != nil {
log.Fatalf("postgres connect error: %v", err) log.Fatalf("postgres connect error: %v", err)
} }
defer pool.Close()
if err := pool.BootstrapSchema(bootCtx); err != nil { if err := pool.BootstrapSchema(bootCtx); err != nil {
log.Fatalf("schema bootstrap error: %v", err) log.Fatalf("schema bootstrap error: %v", err)
} }
mongoClient, err := mongo.NewClient(bootCtx, cfg.MongoURI) mongoClient, err := mongo.NewClient(bootCtx, cfg.MongoURI, mongo.ClientOptions{
MaxPoolSize: cfg.MongoPoolMaxSize,
MinPoolSize: cfg.MongoPoolMinSize,
MaxConnIdleTime: cfg.MongoPoolMaxIdleTime,
})
if err != nil { if err != nil {
log.Fatalf("mongo connect error: %v", err) log.Fatalf("mongo connect error: %v", err)
} }
defer func() {
disconnectCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := mongoClient.Disconnect(disconnectCtx); err != nil {
log.Printf("mongo disconnect error: %v", err)
}
}()
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop() defer stop()
...@@ -49,8 +66,13 @@ func main() { ...@@ -49,8 +66,13 @@ func main() {
if err != nil { if err != nil {
log.Fatalf("pipeline wiring error: %v", err) log.Fatalf("pipeline wiring error: %v", err)
} }
for _, s := range schedulers { if cfg.SchedulersEnabled {
go s.Start(ctx) for _, s := range schedulers {
go s.Start(ctx)
}
log.Printf("schedulers enabled: %d pipeline(s)", len(schedulers))
} else {
log.Println("schedulers disabled: solo se ejecutan los triggers manuales")
} }
r := router.New(router.Config{ r := router.New(router.Config{
......
...@@ -45,3 +45,18 @@ func (r *Balotario) SetRowHash(h string) { ...@@ -45,3 +45,18 @@ func (r *Balotario) SetRowHash(h string) {
func (r *Balotario) SetCreatedAt(t time.Time) { func (r *Balotario) SetCreatedAt(t time.Time) {
r.CreatedAt = t r.CreatedAt = t
} }
type BalotarioRef struct {
MatriculaID int
BalotarioID int
}
func (r *Balotario) Refs() []BalotarioRef {
refs := make([]BalotarioRef, 0)
for _, periodo := range r.Periodos {
for _, curso := range periodo.Cursos {
refs = append(refs, BalotarioRef{MatriculaID: r.MatriculaID, BalotarioID: curso.BalotarioID})
}
}
return refs
}
...@@ -37,3 +37,14 @@ type SyncStateRepository interface { ...@@ -37,3 +37,14 @@ type SyncStateRepository interface {
Get(ctx context.Context) (time.Time, error) Get(ctx context.Context) (time.Time, error)
Set(ctx context.Context, t time.Time) error Set(ctx context.Context, t time.Time) error
} }
// ProcessedMarker marca en el origen los registros que ya quedaron reflejados en Mongo,
// para que una carga incremental no vuelva a leerlos en el siguiente ciclo.
type ProcessedMarker interface {
MarkProcessed(ctx context.Context, rows []entities.SyncRow) error
}
// PeriodosCleaner elimina el array periodos de los documentos indicados antes de reescribirlo.
type PeriodosCleaner interface {
ClearPeriodos(ctx context.Context, ids []int) error
}
...@@ -11,11 +11,21 @@ import ( ...@@ -11,11 +11,21 @@ import (
) )
type Config struct { type Config struct {
PGDSN string PGDSN string
MongoURI string MongoURI string
MongoDB string MongoDB string
SyncInterval time.Duration SyncInterval time.Duration
Port string Port string
SchedulersEnabled bool
PGPoolMaxConns int32
PGPoolMinConns int32
PGPoolMaxConnLifetime time.Duration
PGPoolMaxConnIdleTime time.Duration
MongoPoolMaxSize uint64
MongoPoolMinSize uint64
MongoPoolMaxIdleTime time.Duration
} }
func Load() (Config, error) { func Load() (Config, error) {
...@@ -51,9 +61,83 @@ func Load() (Config, error) { ...@@ -51,9 +61,83 @@ func Load() (Config, error) {
} }
cfg.SyncInterval = d cfg.SyncInterval = d
cfg.SchedulersEnabled = true
if raw := os.Getenv("SCHEDULERS_ENABLED"); raw != "" {
enabled, err := strconv.ParseBool(raw)
if err != nil {
return Config{}, fmt.Errorf("invalid SCHEDULERS_ENABLED %q: %w", raw, err)
}
cfg.SchedulersEnabled = enabled
}
if cfg.PGPoolMaxConns, err = parseInt32Env("PG_POOL_MAX_CONNS"); err != nil {
return Config{}, err
}
if cfg.PGPoolMinConns, err = parseInt32Env("PG_POOL_MIN_CONNS"); err != nil {
return Config{}, err
}
if cfg.PGPoolMaxConnLifetime, err = parseDurationEnv("PG_POOL_MAX_CONN_LIFETIME"); err != nil {
return Config{}, err
}
if cfg.PGPoolMaxConnIdleTime, err = parseDurationEnv("PG_POOL_MAX_CONN_IDLE_TIME"); err != nil {
return Config{}, err
}
if cfg.PGPoolMaxConns > 0 && cfg.PGPoolMinConns > cfg.PGPoolMaxConns {
return Config{}, fmt.Errorf("PG_POOL_MIN_CONNS no puede ser mayor que PG_POOL_MAX_CONNS")
}
if cfg.MongoPoolMaxSize, err = parseUint64Env("MONGO_POOL_MAX_SIZE"); err != nil {
return Config{}, err
}
if cfg.MongoPoolMinSize, err = parseUint64Env("MONGO_POOL_MIN_SIZE"); err != nil {
return Config{}, err
}
if cfg.MongoPoolMaxIdleTime, err = parseDurationEnv("MONGO_POOL_MAX_IDLE_TIME"); err != nil {
return Config{}, err
}
if cfg.MongoPoolMaxSize > 0 && cfg.MongoPoolMinSize > cfg.MongoPoolMaxSize {
return Config{}, fmt.Errorf("MONGO_POOL_MIN_SIZE no puede ser mayor que MONGO_POOL_MAX_SIZE")
}
return cfg, nil return cfg, nil
} }
func parseInt32Env(name string) (int32, error) {
raw := os.Getenv(name)
if raw == "" {
return 0, nil
}
v, err := strconv.ParseInt(raw, 10, 32)
if err != nil || v < 0 {
return 0, fmt.Errorf("invalid %s %q: debe ser un entero >= 0", name, raw)
}
return int32(v), nil
}
func parseUint64Env(name string) (uint64, error) {
raw := os.Getenv(name)
if raw == "" {
return 0, nil
}
v, err := strconv.ParseUint(raw, 10, 64)
if err != nil {
return 0, fmt.Errorf("invalid %s %q: debe ser un entero >= 0", name, raw)
}
return v, nil
}
func parseDurationEnv(name string) (time.Duration, error) {
raw := os.Getenv(name)
if raw == "" {
return 0, nil
}
d, err := time.ParseDuration(raw)
if err != nil {
return 0, fmt.Errorf("invalid %s %q: %w", name, raw, err)
}
return d, nil
}
func ScheduleFor(pipelineName string, defaultInterval time.Duration) (usecase.Schedule, error) { func ScheduleFor(pipelineName string, defaultInterval time.Duration) (usecase.Schedule, error) {
prefix := "SYNC_" + strings.ToUpper(pipelineName) prefix := "SYNC_" + strings.ToUpper(pipelineName)
...@@ -90,6 +174,20 @@ func ScheduleFor(pipelineName string, defaultInterval time.Duration) (usecase.Sc ...@@ -90,6 +174,20 @@ func ScheduleFor(pipelineName string, defaultInterval time.Duration) (usecase.Sc
} }
} }
func SchedulerEnabledFor(pipelineName string) (bool, error) {
prefix := "SYNC_" + strings.ToUpper(pipelineName)
raw := os.Getenv(prefix + "_ENABLED")
if raw == "" {
return true, nil
}
enabled, err := strconv.ParseBool(raw)
if err != nil {
return false, fmt.Errorf("invalid %s_ENABLED %q: %w", prefix, raw, err)
}
return enabled, nil
}
func parseHHMM(raw string) (hour, minute int, err error) { func parseHHMM(raw string) (hour, minute int, err error) {
parts := strings.SplitN(raw, ":", 2) parts := strings.SplitN(raw, ":", 2)
if len(parts) != 2 { if len(parts) != 2 {
......
package config package config
import "intranet-synchronizer/internal/infrastructure/database/postgres" import (
"time"
"intranet-synchronizer/internal/infrastructure/database/postgres"
)
type PipelineDef struct { type PipelineDef struct {
Name string Name string
...@@ -9,6 +13,8 @@ type PipelineDef struct { ...@@ -9,6 +13,8 @@ type PipelineDef struct {
MongoDeletedCollection string MongoDeletedCollection string
IDField string IDField string
StateID int StateID int
Incremental bool
DefaultInterval time.Duration
} }
var Pipelines = []PipelineDef{ var Pipelines = []PipelineDef{
...@@ -61,6 +67,16 @@ var Pipelines = []PipelineDef{ ...@@ -61,6 +67,16 @@ var Pipelines = []PipelineDef{
StateID: 6, StateID: 6,
}, },
{ {
Name: "balotarios_incremental",
PGQuery: postgres.LoadDataBalotario,
MongoCollection: "c_balotario",
MongoDeletedCollection: "deleted_c_balotario",
IDField: "matricula_id",
StateID: 12,
Incremental: true,
DefaultInterval: 90 * time.Minute,
},
{
Name: "attendance", Name: "attendance",
PGQuery: postgres.AttendanceQuery, PGQuery: postgres.AttendanceQuery,
MongoCollection: "c_attendance", MongoCollection: "c_attendance",
......
...@@ -2,17 +2,36 @@ package mongo ...@@ -2,17 +2,36 @@ package mongo
import ( import (
"context" "context"
"time"
"go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options" "go.mongodb.org/mongo-driver/mongo/options"
) )
func NewClient(ctx context.Context, uri string) (*mongo.Client, error) { type ClientOptions struct {
client, err := mongo.Connect(ctx, options.Client().ApplyURI(uri)) MaxPoolSize uint64
MinPoolSize uint64
MaxConnIdleTime time.Duration
}
func NewClient(ctx context.Context, uri string, opts ClientOptions) (*mongo.Client, error) {
clientOpts := options.Client().ApplyURI(uri)
if opts.MaxPoolSize > 0 {
clientOpts.SetMaxPoolSize(opts.MaxPoolSize)
}
if opts.MinPoolSize > 0 {
clientOpts.SetMinPoolSize(opts.MinPoolSize)
}
if opts.MaxConnIdleTime > 0 {
clientOpts.SetMaxConnIdleTime(opts.MaxConnIdleTime)
}
client, err := mongo.Connect(ctx, clientOpts)
if err != nil { if err != nil {
return nil, err return nil, err
} }
if err := client.Ping(ctx, nil); err != nil { if err := client.Ping(ctx, nil); err != nil {
_ = client.Disconnect(ctx)
return nil, err return nil, err
} }
return client, nil return client, nil
......
...@@ -58,6 +58,20 @@ func (c *DocumentRepository) BulkUpsert(ctx context.Context, rows []entities.Syn ...@@ -58,6 +58,20 @@ func (c *DocumentRepository) BulkUpsert(ctx context.Context, rows []entities.Syn
return created, updated, nil return created, updated, nil
} }
func (c *DocumentRepository) ClearPeriodos(ctx context.Context, ids []int) error {
if len(ids) == 0 {
return nil
}
_, err := c.coll.UpdateMany(ctx,
bson.M{c.idField: bson.M{"$in": ids}},
bson.M{"$unset": bson.M{"periodos": ""}})
if err != nil {
return fmt.Errorf("clear periodos: %w", err)
}
return nil
}
func (c *DocumentRepository) ListIDsAndHashes(ctx context.Context) (map[int]string, error) { func (c *DocumentRepository) ListIDsAndHashes(ctx context.Context) (map[int]string, error) {
cur, err := c.coll.Find(ctx, bson.M{}, options.Find().SetProjection(bson.M{c.idField: 1, "row_hash": 1})) cur, err := c.coll.Find(ctx, bson.M{}, options.Find().SetProjection(bson.M{c.idField: 1, "row_hash": 1}))
if err != nil { if err != nil {
......
package postgres
import (
"context"
"fmt"
"log"
"sort"
"intranet-synchronizer/internal/domain/entities"
"intranet-synchronizer/internal/domain/repositories"
)
type BalotarioMarker struct {
pool *Pool
}
func NewBalotarioMarker(pool *Pool) repositories.ProcessedMarker {
return &BalotarioMarker{pool: pool}
}
const resetBalotarioToUpdateSQL = `
UPDATE academico.ac_balotario
SET to_update = false, sync_last_update = now()
WHERE balotario_id = ANY($1)
AND coalesce(to_update, false)`
func (m *BalotarioMarker) MarkProcessed(ctx context.Context, rows []entities.SyncRow) error {
refs := balotarioRefs(rows)
if len(refs) == 0 {
return nil
}
if _, err := m.pool.Pool.Exec(ctx, resetBalotarioToUpdateSQL, distinctBalotarioIDs(refs)); err != nil {
return fmt.Errorf("reset balotario to_update: %w", err)
}
for _, ref := range refs {
log.Printf("[balotarios_incremental] Paso 3: actualizar balotario en Postgres to_update=false con matricula_id: %d y balotario_id: %d", ref.MatriculaID, ref.BalotarioID)
}
return nil
}
func balotarioRefs(rows []entities.SyncRow) []entities.BalotarioRef {
refs := make([]entities.BalotarioRef, 0)
for _, row := range rows {
doc, ok := row.Doc.(*entities.Balotario)
if !ok {
continue
}
refs = append(refs, doc.Refs()...)
}
return refs
}
func distinctBalotarioIDs(refs []entities.BalotarioRef) []int {
seen := make(map[int]struct{}, len(refs))
ids := make([]int, 0, len(refs))
for _, ref := range refs {
if _, exists := seen[ref.BalotarioID]; exists {
continue
}
seen[ref.BalotarioID] = struct{}{}
ids = append(ids, ref.BalotarioID)
}
sort.Ints(ids)
return ids
}
...@@ -136,12 +136,35 @@ FROM alumnos a ...@@ -136,12 +136,35 @@ FROM alumnos a
GROUP BY a.matricula_id, a.estudiante_id GROUP BY a.matricula_id, a.estudiante_id
` `
// LoadDataBalotario es la lectura incremental: devuelve solo los alumnos afectados por algún
// balotario marcado con to_update, pero con su documento completo (todos sus cursos). Así el
// upsert no reemplaza periodos[].cursos con una lista parcial y no borra cursos no marcados.
const LoadDataBalotario = ` const LoadDataBalotario = `
WITH periodos (periodo_id, periodo_orden) AS ( WITH periodos (periodo_id, periodo_orden) AS (
VALUES (3170, 1), (3174, 2), (3171, 3), (3175, 4), (3172, 5), (3176, 6), (3173, 7), (3177, 8) VALUES (3170, 1), (3174, 2), (3171, 3), (3175, 4), (3172, 5), (3176, 6), (3173, 7), (3177, 8)
), balotarios_update AS (
SELECT balotario_id
FROM academico.ac_balotario
WHERE periodo_academico_id = 14
AND to_update
), matriculas_afectadas AS (
SELECT m.matricula_id
FROM balotarios_update bu
INNER JOIN academico.ac_balotario_aula ba ON ba.balotario_id = bu.balotario_id
INNER JOIN matricula.ma_matricula m ON m.aula_id_asiste = ba.aula_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
UNION
SELECT r.matricula_id
FROM balotarios_update bu
INNER JOIN academico.ac_balotario_respuesta r ON r.balotario_id = bu.balotario_id
), alumnos AS ( ), alumnos AS (
SELECT m.matricula_id, m.estudiante_id, m.aula_id_asiste AS aula_id SELECT m.matricula_id, m.estudiante_id, m.aula_id_asiste AS aula_id
FROM matricula.ma_matricula m FROM matriculas_afectadas ma
INNER JOIN matricula.ma_matricula m ON m.matricula_id = ma.matricula_id
INNER JOIN academico.ac_aula au ON au.aula_id = m.aula_id_asiste INNER JOIN academico.ac_aula au ON au.aula_id = m.aula_id_asiste
WHERE NOT m.matricula_retirado WHERE NOT m.matricula_retirado
AND NOT m.matricula_anulada AND NOT m.matricula_anulada
...@@ -152,13 +175,11 @@ WITH periodos (periodo_id, periodo_orden) AS ( ...@@ -152,13 +175,11 @@ WITH periodos (periodo_id, periodo_orden) AS (
FROM alumnos a FROM alumnos a
INNER JOIN academico.ac_balotario_aula ba ON ba.aula_id = a.aula_id INNER JOIN academico.ac_balotario_aula ba ON ba.aula_id = a.aula_id
INNER JOIN academico.ac_balotario b ON b.balotario_id = ba.balotario_id AND b.periodo_academico_id = 14 INNER JOIN academico.ac_balotario b ON b.balotario_id = ba.balotario_id AND b.periodo_academico_id = 14
where coalesce(b.to_update, false)
UNION UNION
SELECT a.matricula_id, b.balotario_id, b.periodo_id, b.curso_id, b.formulario_url SELECT a.matricula_id, b.balotario_id, b.periodo_id, b.curso_id, b.formulario_url
FROM alumnos a FROM alumnos a
INNER JOIN academico.ac_balotario_respuesta r ON r.matricula_id = a.matricula_id INNER JOIN academico.ac_balotario_respuesta r ON r.matricula_id = a.matricula_id
INNER JOIN academico.ac_balotario b ON b.balotario_id = r.balotario_id AND b.periodo_academico_id = 14 INNER JOIN academico.ac_balotario b ON b.balotario_id = r.balotario_id AND b.periodo_academico_id = 14
where coalesce(b.to_update, false)
), cursos AS ( ), cursos AS (
SELECT DISTINCT ON (s.matricula_id, s.periodo_id, s.curso_id) SELECT DISTINCT ON (s.matricula_id, s.periodo_id, s.curso_id)
s.matricula_id, s.matricula_id,
......
...@@ -3,6 +3,7 @@ package postgres ...@@ -3,6 +3,7 @@ package postgres
import ( import (
"context" "context"
"fmt" "fmt"
"time"
"github.com/jackc/pgx/v5/pgxpool" "github.com/jackc/pgx/v5/pgxpool"
) )
...@@ -11,12 +12,37 @@ type Pool struct { ...@@ -11,12 +12,37 @@ type Pool struct {
*pgxpool.Pool *pgxpool.Pool
} }
func NewPool(ctx context.Context, dsn string) (*Pool, error) { type PoolOptions struct {
pool, err := pgxpool.New(ctx, dsn) MaxConns int32
MinConns int32
MaxConnLifetime time.Duration
MaxConnIdleTime time.Duration
}
func NewPool(ctx context.Context, dsn string, opts PoolOptions) (*Pool, error) {
cfg, err := pgxpool.ParseConfig(dsn)
if err != nil {
return nil, err
}
if opts.MaxConns > 0 {
cfg.MaxConns = opts.MaxConns
}
if opts.MinConns > 0 {
cfg.MinConns = opts.MinConns
}
if opts.MaxConnLifetime > 0 {
cfg.MaxConnLifetime = opts.MaxConnLifetime
}
if opts.MaxConnIdleTime > 0 {
cfg.MaxConnIdleTime = opts.MaxConnIdleTime
}
pool, err := pgxpool.NewWithConfig(ctx, cfg)
if err != nil { if err != nil {
return nil, err return nil, err
} }
if err := pool.Ping(ctx); err != nil { if err := pool.Ping(ctx); err != nil {
pool.Close()
return nil, err return nil, err
} }
return &Pool{pool}, nil return &Pool{pool}, nil
...@@ -29,7 +55,7 @@ CREATE TABLE IF NOT EXISTS sync_state ( ...@@ -29,7 +55,7 @@ CREATE TABLE IF NOT EXISTS sync_state (
); );
INSERT INTO sync_state (id, last_synced_at) 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'), (6, '1970-01-01T00:00:00Z'), (7, '1970-01-01T00:00:00Z'), (8, '1970-01-01T00:00:00Z'), (9, '1970-01-01T00:00:00Z'), (11, '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'), (7, '1970-01-01T00:00:00Z'), (8, '1970-01-01T00:00:00Z'), (9, '1970-01-01T00:00:00Z'), (11, '1970-01-01T00:00:00Z'), (12, '1970-01-01T00:00:00Z')
ON CONFLICT (id) DO NOTHING; ON CONFLICT (id) DO NOTHING;
` `
......
...@@ -26,7 +26,7 @@ func readerFor(name string, pool *postgres.Pool, query string) (repositories.Sou ...@@ -26,7 +26,7 @@ func readerFor(name string, pool *postgres.Pool, query string) (repositories.Sou
return postgres.NewUserReader(pool, query), nil return postgres.NewUserReader(pool, query), nil
case "professors": case "professors":
return postgres.NewProfessorReader(pool, query), nil return postgres.NewProfessorReader(pool, query), nil
case "balotarios": case "balotarios", "balotarios_incremental":
return postgres.NewBalotarioReader(pool, query), nil return postgres.NewBalotarioReader(pool, query), nil
case "attendance": case "attendance":
return postgres.NewAttendanceReader(pool, query), nil return postgres.NewAttendanceReader(pool, query), nil
...@@ -71,6 +71,17 @@ func groupReaderFor(name string, pool *postgres.Pool) repositories.SourceGroupRe ...@@ -71,6 +71,17 @@ func groupReaderFor(name string, pool *postgres.Pool) repositories.SourceGroupRe
} }
} }
// markerFor devuelve el marcador en el origen de los módulos incrementales, que resetea el
// flag to_update de los registros ya reflejados en Mongo. Los módulos sin marcador no lo usan.
func markerFor(name string, pool *postgres.Pool) repositories.ProcessedMarker {
switch name {
case "balotarios_incremental":
return postgres.NewBalotarioMarker(pool)
default:
return nil
}
}
// BuildGroupUpserters arma un caso de uso de upsert por grupo para cada pipeline que lo soporte. // BuildGroupUpserters arma un caso de uso de upsert por grupo para cada pipeline que lo soporte.
func BuildGroupUpserters( func BuildGroupUpserters(
cfg config.Config, cfg config.Config,
...@@ -143,7 +154,12 @@ func Build( ...@@ -143,7 +154,12 @@ func Build(
// omite el fetch de documentos previos y no escribe en /opt/logs. // omite el fetch de documentos previos y no escribe en /opt/logs.
var changeLog usecase.ChangeLogger var changeLog usecase.ChangeLogger
uc := usecase.NewRunSyncPipelineUseCase(p.Name, reader, docRepo, docRepo, archiver, state, docRepo, changeLog, time.Now) var uc usecase.RunSyncPipelineUseCase
if p.Incremental {
uc = usecase.NewRunIncrementalSyncUseCase(p.Name, reader, docRepo, docRepo, state, markerFor(p.Name, pool), docRepo, time.Now)
} else {
uc = usecase.NewRunSyncPipelineUseCase(p.Name, reader, docRepo, docRepo, archiver, state, docRepo, changeLog, time.Now)
}
if lastSynced, err := state.Get(ctx); err != nil { if lastSynced, err := state.Get(ctx); err != nil {
return nil, nil, fmt.Errorf("load persisted %s sync state: %w", p.Name, err) return nil, nil, fmt.Errorf("load persisted %s sync state: %w", p.Name, err)
...@@ -151,12 +167,26 @@ func Build( ...@@ -151,12 +167,26 @@ func Build(
uc.SeedLastResult(lastSynced) uc.SeedLastResult(lastSynced)
} }
schedule, err := config.ScheduleFor(p.Name, cfg.SyncInterval) defaultInterval := cfg.SyncInterval
if p.DefaultInterval > 0 {
defaultInterval = p.DefaultInterval
}
useCases[p.Name] = uc
enabled, err := config.SchedulerEnabledFor(p.Name)
if err != nil {
return nil, nil, err
}
if !enabled {
continue
}
schedule, err := config.ScheduleFor(p.Name, defaultInterval)
if err != nil { if err != nil {
return nil, nil, fmt.Errorf("schedule config error for pipeline %s: %w", p.Name, err) return nil, nil, fmt.Errorf("schedule config error for pipeline %s: %w", p.Name, err)
} }
useCases[p.Name] = uc
schedulers = append(schedulers, usecase.NewScheduler(uc, schedule)) schedulers = append(schedulers, usecase.NewScheduler(uc, schedule))
} }
......
package usecase
import (
"context"
"fmt"
"log"
"sync"
"time"
"intranet-synchronizer/internal/domain/entities"
"intranet-synchronizer/internal/domain/repositories"
)
// runIncrementalSync ejecuta una carga parcial: el lector devuelve solo el subconjunto de
// documentos marcados para actualizar en el origen. No reconcilia borrados, porque los ids
// ausentes en esa lectura parcial no significan que hayan desaparecido del origen.
type runIncrementalSync struct {
name string
reader repositories.SourceReader
upserter repositories.DocumentUpserter
fetcher repositories.DocumentFetcher
state repositories.SyncStateRepository
marker repositories.ProcessedMarker
cleaner repositories.PeriodosCleaner
now func() time.Time
mu sync.Mutex
lastResult entities.SyncResult
}
func NewRunIncrementalSyncUseCase(
name string,
reader repositories.SourceReader,
upserter repositories.DocumentUpserter,
fetcher repositories.DocumentFetcher,
state repositories.SyncStateRepository,
marker repositories.ProcessedMarker,
cleaner repositories.PeriodosCleaner,
now func() time.Time,
) RunSyncPipelineUseCase {
return &runIncrementalSync{
name: name,
reader: reader,
upserter: upserter,
fetcher: fetcher,
state: state,
marker: marker,
cleaner: cleaner,
now: now,
}
}
func (s *runIncrementalSync) Run(ctx context.Context) error {
log.Printf("[%s] Paso 0: Start incremental sync", s.name)
s.mu.Lock()
defer s.mu.Unlock()
runAt := s.now().UTC()
result := entities.SyncResult{RanAt: runAt}
rows, err := s.reader.FetchAll(ctx)
if err != nil {
result.Err = fmt.Errorf("fetch incremental rows: %w", err)
s.lastResult = result
return result.Err
}
ids := make([]int, len(rows))
for i, row := range rows {
ids[i] = row.ID
}
log.Printf("[%s] Paso 1: obtener matrículas de Postgres con to_update=true -> %d matrícula(s): %v", s.name, len(ids), ids)
var currentDocs map[int]map[string]interface{}
if s.fetcher != nil && len(ids) > 0 {
currentDocs, err = s.fetcher.FindByIDs(ctx, ids)
if err != nil {
result.Err = fmt.Errorf("fetch current docs: %w", err)
s.lastResult = result
return result.Err
}
}
changed := make([]entities.SyncRow, 0, len(rows))
for _, row := range rows {
hash, err := computeRowHash(row.Doc)
if err != nil {
result.Err = fmt.Errorf("hash row %d: %w", row.ID, err)
s.lastResult = result
return result.Err
}
if current, ok := currentDocs[row.ID]; ok {
if storedHash, _ := current["row_hash"].(string); storedHash == hash {
result.Unchanged++
continue
}
}
stampUpdatedAt(row.Doc, runAt)
stampRowHash(row.Doc, hash)
stampCreatedAt(row.Doc, runAt)
changed = append(changed, row)
}
if s.cleaner != nil && len(changed) > 0 {
changedIDs := make([]int, len(changed))
for i, row := range changed {
changedIDs[i] = row.ID
}
if err := s.cleaner.ClearPeriodos(ctx, changedIDs); err != nil {
result.Err = fmt.Errorf("clear periodos: %w", err)
s.lastResult = result
return result.Err
}
}
created, updated, err := s.upserter.BulkUpsert(ctx, changed)
if err != nil {
result.Err = fmt.Errorf("bulk upsert: %w", err)
s.lastResult = result
return result.Err
}
for _, row := range changed {
doc, ok := row.Doc.(*entities.Balotario)
if !ok {
continue
}
verbo, estado := "insertar", "nueva"
if _, existed := currentDocs[row.ID]; existed {
verbo, estado = "actualizar", "existente"
}
for _, ref := range doc.Refs() {
log.Printf("[%s] Paso 2: %s matrícula %s en Mongo con matricula_id: %d y balotario_id: %d", s.name, verbo, estado, ref.MatriculaID, ref.BalotarioID)
}
}
log.Printf("[%s] Paso 2: fin -> nuevas=%d existentes=%d", s.name, created, updated)
if s.marker != nil {
if err := s.marker.MarkProcessed(ctx, rows); err != nil {
result.Err = fmt.Errorf("mark processed in source: %w", err)
s.lastResult = result
return result.Err
}
}
result.Created = created
result.Updated = updated
result.RowsSynced = len(rows)
if err := s.state.Set(ctx, runAt); err != nil {
result.Err = fmt.Errorf("advance sync state: %w", err)
s.lastResult = result
return result.Err
}
s.lastResult = result
return nil
}
func (s *runIncrementalSync) SeedLastResult(t time.Time) {
s.mu.Lock()
defer s.mu.Unlock()
s.lastResult = entities.SyncResult{RanAt: t}
}
func (s *runIncrementalSync) LastResult() entities.SyncResult {
s.mu.Lock()
defer s.mu.Unlock()
return s.lastResult
}
-- Índices que necesita la sincronización de balotarios (full e incremental).
-- Ejecutar contra cada ambiente. CONCURRENTLY evita bloquear la tabla mientras se construye,
-- por eso el archivo no va dentro de una transacción.
-- Acelera todos los joins por alumno sobre la tabla de respuestas (3.2M filas en desarrollo,
-- sin ningún índice que empiece por matricula_id). Las columnas INCLUDE permiten index-only
-- scan al reconstruir el documento completo (cursos con responde/puntuacion).
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_ac_balotario_respuesta_matricula
ON academico.ac_balotario_respuesta (matricula_id, balotario_id)
INCLUDE (balotario_respuesta_id, balotario_nota);
-- El único existente es (balotario_id, aula_id), que no sirve para buscar por aula.
-- Este índice permite ir de un aula a sus balotarios.
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_ac_balotario_aula_aula
ON academico.ac_balotario_aula (aula_id, balotario_id);
-- Permite ir de las aulas afectadas a sus matrículas sin recorrer toda la tabla.
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_ma_matricula_aula_asiste
ON matricula.ma_matricula (aula_id_asiste);
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