Skip to content

Commit

Permalink
Implement clean up routine
Browse files Browse the repository at this point in the history
  • Loading branch information
Mewbi committed May 6, 2024
1 parent ca3b8d0 commit 0fc8f1b
Show file tree
Hide file tree
Showing 13 changed files with 118 additions and 10 deletions.
6 changes: 6 additions & 0 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,12 @@ type Config struct {
Development bool `yaml:"development"`
Database Database
Server Server
Schedule Schedule
}

type Schedule struct {
CleanUpDays int `yaml:"clean_up_days"`
IntervalMinutes int `yaml:"interval_minutes"`
}

type Server struct {
Expand Down
4 changes: 4 additions & 0 deletions config/config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,7 @@ database:
cache: "shared"
max_conn: 20
schema: "database/schema.sql"

schedule:
clean_up_days: 1
interval_minutes: 1
4 changes: 4 additions & 0 deletions config/config_prod.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,7 @@ database:
cache: "shared"
max_conn: 20
schema: "database/schema.sql"

schedule:
clean_up_days: 7
interval_minutes: 60
4 changes: 4 additions & 0 deletions config/config_test.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,7 @@ database:
cache: "shared"
max_conn: 20
schema: "../../database/schema.sql"

schedule:
clean_up_days: 1
interval_minutes: 1
3 changes: 2 additions & 1 deletion database/schema.sql
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
CREATE TABLE IF NOT EXISTS retrospectives (
id TEXT PRIMARY KEY,
name TEXT,
description TEXT
description TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);

-- Table for Question
Expand Down
2 changes: 2 additions & 0 deletions internal/repository/repository.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,13 @@ import (
"api/types"
"context"
"net/http"
"time"

"github.com/google/uuid"
)

type Repository interface {
GetOldRetrospectives(ctx context.Context, date time.Time) ([]uuid.UUID, error)
GetAllRetrospectives(ctx context.Context) ([]uuid.UUID, error)
GetRetrospective(ctx context.Context, id uuid.UUID) (*types.Retrospective, error)
CreateRetrospective(ctx context.Context, retro *types.Retrospective) error
Expand Down
27 changes: 25 additions & 2 deletions internal/repository/sqlite.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"database/sql"
"fmt"
"os"
"time"

"github.com/google/uuid"
_ "github.com/mattn/go-sqlite3"
Expand Down Expand Up @@ -64,11 +65,12 @@ func (s *SQLite) migrate(filepath string) error {
}

func (s *SQLite) CreateRetrospective(ctx context.Context, retro *types.Retrospective) error {
sql := `INSERT INTO retrospectives (id, name, description) VALUES ($1, $2, $3)`
sql := `INSERT INTO retrospectives (id, name, description, created_at) VALUES ($1, $2, $3, $4)`
_, err := s.conn.Exec(sql,
retro.ID,
retro.Name,
retro.Description,
retro.CreatedAt,
)
return err
}
Expand Down Expand Up @@ -152,6 +154,26 @@ func (s *SQLite) DeleteRetrospective(ctx context.Context, id uuid.UUID) (*types.
return retro, nil
}

func (s *SQLite) GetOldRetrospectives(ctx context.Context, date time.Time) ([]uuid.UUID, error) {
sqlQuery := `SELECT id FROM retrospectives WHERE created_at < $1`
rows, err := s.conn.Query(sqlQuery, date)
if err != nil {
return nil, err
}

IDs := make([]uuid.UUID, 0)

for rows.Next() {
var ID uuid.UUID
err := rows.Scan(&ID)
if err != nil {
return nil, err
}
IDs = append(IDs, ID)
}
return IDs, nil
}

func (s *SQLite) GetAllRetrospectives(ctx context.Context) ([]uuid.UUID, error) {
sqlQuery := `SELECT id FROM retrospectives`
rows, err := s.conn.Query(sqlQuery)
Expand All @@ -178,10 +200,11 @@ func (s *SQLite) GetRetrospective(ctx context.Context, id uuid.UUID) (*types.Ret
Questions: []types.Question{},
}

sqlQuery := `SELECT name, description FROM retrospectives WHERE id = $1`
sqlQuery := `SELECT name, description, created_at FROM retrospectives WHERE id = $1`
err := s.conn.QueryRow(sqlQuery, id).Scan(
&retro.Name,
&retro.Description,
&retro.CreatedAt,
)
if err != nil {
return nil, err
Expand Down
5 changes: 4 additions & 1 deletion internal/repository/sqlite_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"context"
"database/sql"
"testing"
"time"

"github.com/google/uuid"
_ "github.com/mattn/go-sqlite3"
Expand Down Expand Up @@ -160,6 +161,7 @@ func TestGetRetrospective(t *testing.T) {
ID: id,
Name: "mtg",
Description: "df/dx = 0",
CreatedAt: time.Now().UTC(),
Questions: []types.Question{
{
ID: questionID,
Expand All @@ -176,12 +178,13 @@ func TestGetRetrospective(t *testing.T) {
},
}

sqlQuery := `INSERT INTO retrospectives (id, name, description) VALUES ($1, $2, $3)`
sqlQuery := `INSERT INTO retrospectives (id, name, description, created_at) VALUES ($1, $2, $3, $4)`
_, err = db.conn.Exec(
sqlQuery,
&retro.ID,
&retro.Name,
&retro.Description,
&retro.CreatedAt,
)
assert.Nilf(t, err, "error creating retrospective")

Expand Down
10 changes: 7 additions & 3 deletions internal/repository/websocket.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package repository

import (
"api/types"
"context"
"errors"
"fmt"
Expand All @@ -10,8 +11,6 @@ import (
"net/http"
"time"

"api/types"

"github.com/google/uuid"
"github.com/gorilla/websocket"
)
Expand Down Expand Up @@ -67,7 +66,8 @@ func (ws *WebSocket) AddConnection(ctx context.Context, w http.ResponseWriter, r
continue
}

if netErr, ok := err.(net.Error); (ok && netErr.Timeout()) || websocket.IsUnexpectedCloseError(err) || errors.Is(err, io.EOF) {
if netErr, ok := err.(net.Error); (ok && netErr.Timeout()) || websocket.IsUnexpectedCloseError(err) ||
errors.Is(err, io.EOF) {
break
}

Expand Down Expand Up @@ -162,6 +162,10 @@ func (w *WebSocket) DeleteQuestion(ctx context.Context, id uuid.UUID) (*types.Qu
return nil, w.sendMessageToRetro(ctx, message, nil)
}

func (s *WebSocket) GetOldRetrospectives(ctx context.Context, date time.Time) ([]uuid.UUID, error) {
panic("unimplemented")
}

func (s *WebSocket) GetAllRetrospectives(ctx context.Context) ([]uuid.UUID, error) {
panic("unimplemented")
}
Expand Down
30 changes: 30 additions & 0 deletions internal/server/schedule.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package server

import (
"api/config"
"context"
"log"
"time"
)

func (c *controller) StartSchedule() {
config := config.Get()
go func() {
ticker := time.NewTicker(time.Duration(config.Schedule.IntervalMinutes) * time.Minute)

for {
select {
case <-ticker.C:
c.CleanUp()
}
}
}()
}

func (c *controller) CleanUp() {
log.Println("starting clean up routine")
ctx := context.Background()
if err := c.service.CleanUpRetros(ctx); err != nil {
log.Printf("error running clean up routine: %s", err.Error())
}
}
29 changes: 26 additions & 3 deletions internal/service/service.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
package service

import (
"api/config"
"api/internal/repository"
"api/types"
"context"
"log"
"net/http"
"time"

"github.com/google/uuid"
)
Expand All @@ -28,6 +31,7 @@ func (s *Service) CreateRetrospective(ctx context.Context, retro *types.Retrospe
}

retro.ID = id
retro.CreatedAt = time.Now().UTC()
err = s.repository.CreateRetrospective(ctx, retro)
if err != nil {
return err
Expand Down Expand Up @@ -119,13 +123,13 @@ func (s *Service) SubscribeChanges(ctx context.Context, w http.ResponseWriter, r
}

func (s *Service) LoadAllRetrospectives(ctx context.Context) error {
IDs, err := s.repository.GetAllRetrospectives(ctx)
ids, err := s.repository.GetAllRetrospectives(ctx)
if err != nil {
return err
}

for _, ID := range IDs {
err := s.webSocketRepository.CreateRetrospective(ctx, &types.Retrospective{ID: ID})
for _, id := range ids {
err := s.webSocketRepository.CreateRetrospective(ctx, &types.Retrospective{ID: id})
if err != nil {
return err
}
Expand All @@ -137,3 +141,22 @@ func (s *Service) LoadAllRetrospectives(ctx context.Context) error {
func (s *Service) GetLimits(ctx context.Context) *types.ApiLimits {
return types.GetApiLimits()
}

func (s *Service) CleanUpRetros(ctx context.Context) error {
config := config.Get()
cleanUpDays := time.Duration(config.Schedule.CleanUpDays)
date := time.Now().Add(-(cleanUpDays * 24 * time.Hour))
ids, err := s.repository.GetOldRetrospectives(ctx, date)
if err != nil {
return err
}

for _, id := range ids {
if _, err := s.repository.DeleteRetrospective(ctx, id); err != nil {
return err
}
}

log.Printf("deleted %d retrospectives older than %s", len(ids), date.String())
return nil
}
1 change: 1 addition & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,5 +32,6 @@ func main() {
service.LoadAllRetrospectives(context.Background())

log.Printf("initing service: %s", config.Name)
controller.StartSchedule()
controller.Start()
}
3 changes: 3 additions & 0 deletions types/retrospective.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package types

import (
"time"

"github.com/google/uuid"
)

Expand All @@ -9,6 +11,7 @@ type Retrospective struct {
Name string `json:"name"`
Description string `json:"description"`
Questions []Question `json:"questions"`
CreatedAt time.Time `json:"created_at"`
}

type Question struct {
Expand Down

0 comments on commit 0fc8f1b

Please sign in to comment.