Skip to content

Commit

Permalink
chore: use api.Context instead of duty.DBContext
Browse files Browse the repository at this point in the history
  • Loading branch information
adityathebe committed Sep 20, 2023
1 parent 1d46a8d commit 44ad1da
Show file tree
Hide file tree
Showing 10 changed files with 37 additions and 40 deletions.
4 changes: 2 additions & 2 deletions auth/kratos_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import (
"context"
"os"

"github.com/flanksource/duty"
"github.com/flanksource/incident-commander/api"
client "github.com/ory/client-go"
)

Expand Down Expand Up @@ -101,7 +101,7 @@ func (k *KratosHandler) createAdminIdentity(ctx context.Context) (string, error)
return createdIdentity.Id, nil
}

func (k *KratosHandler) CreateAdminUser(ctx duty.DBContext) (string, error) {
func (k *KratosHandler) CreateAdminUser(ctx api.Context) (string, error) {
var id string
tx := ctx.DB().Raw(`SELECT id FROM identities WHERE traits->>'email' = ?`, AdminEmail).Scan(&id)
if tx.Error != nil {
Expand Down
12 changes: 6 additions & 6 deletions db/agents.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@ import (
"fmt"

"github.com/flanksource/commons/collections"
"github.com/flanksource/duty"
"github.com/flanksource/duty/models"
"github.com/flanksource/incident-commander/api"
"github.com/google/uuid"
"gorm.io/gorm"
)

func FindAgent(ctx duty.DBContext, name string) (*models.Agent, error) {
func FindAgent(ctx api.Context, name string) (*models.Agent, error) {
var agent models.Agent
err := ctx.DB().Where("name = ?", name).First(&agent).Error
if err != nil {
Expand All @@ -25,19 +25,19 @@ func FindAgent(ctx duty.DBContext, name string) (*models.Agent, error) {
return &agent, nil
}

func getAgent(ctx duty.DBContext, name string) (*models.Agent, error) {
func getAgent(ctx api.Context, name string) (*models.Agent, error) {
var t models.Agent
tx := ctx.DB().Where("name = ?", name).First(&t)
return &t, tx.Error
}

func createAgent(ctx duty.DBContext, name string) (*models.Agent, error) {
func createAgent(ctx api.Context, name string) (*models.Agent, error) {
a := models.Agent{Name: name}
tx := ctx.DB().Create(&a)
return &a, tx.Error
}

func GetOrCreateAgent(ctx duty.DBContext, name string) (*models.Agent, error) {
func GetOrCreateAgent(ctx api.Context, name string) (*models.Agent, error) {
a, err := getAgent(ctx, name)
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
Expand All @@ -53,7 +53,7 @@ func GetOrCreateAgent(ctx duty.DBContext, name string) (*models.Agent, error) {
return a, nil
}

func CreateAgent(ctx duty.DBContext, name string, personID *uuid.UUID, properties map[string]string) error {
func CreateAgent(ctx api.Context, name string, personID *uuid.UUID, properties map[string]string) error {
properties = collections.MergeMap(properties, map[string]string{"type": "agent"})

a := models.Agent{
Expand Down
3 changes: 1 addition & 2 deletions db/canaries.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,11 @@ package db
import (
"time"

"github.com/flanksource/duty"
"github.com/flanksource/incident-commander/api"
"github.com/google/uuid"
)

func GetCanariesOfAgent(ctx duty.DBContext, agentID uuid.UUID, since time.Time) (*api.CanaryPullResponse, error) {
func GetCanariesOfAgent(ctx api.Context, agentID uuid.UUID, since time.Time) (*api.CanaryPullResponse, error) {
var now time.Time
if err := ctx.DB().Raw("SELECT NOW()").Scan(&now).Error; err != nil {
return nil, err
Expand Down
6 changes: 3 additions & 3 deletions db/job_history.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
package db

import (
"github.com/flanksource/duty"
"github.com/flanksource/duty/models"
"github.com/flanksource/incident-commander/api"
"github.com/google/uuid"
)

func PersistJobHistory(ctx duty.DBContext, h *models.JobHistory) error {
func PersistJobHistory(ctx api.Context, h *models.JobHistory) error {
// Delete jobs which did not process anything
if h.ID != uuid.Nil && (h.SuccessCount+h.ErrorCount) == 0 {
return ctx.DB().Table("job_history").Delete(h).Error
Expand All @@ -15,7 +15,7 @@ func PersistJobHistory(ctx duty.DBContext, h *models.JobHistory) error {
return ctx.DB().Table("job_history").Save(h).Error
}

func DeleteOldJobHistoryRows(ctx duty.DBContext, keepLatest int) error {
func DeleteOldJobHistoryRows(ctx api.Context, keepLatest int) error {
return ctx.DB().Exec(`
WITH ordered_history AS (
SELECT
Expand Down
17 changes: 8 additions & 9 deletions db/people.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,14 @@ import (
"time"

"github.com/flanksource/commons/collections"
"github.com/flanksource/duty"
"github.com/flanksource/duty/models"
"github.com/flanksource/incident-commander/api"
"github.com/google/uuid"
"golang.org/x/crypto/argon2"
"gorm.io/gorm/clause"
)

func UpdateUserProperties(ctx duty.DBContext, userID string, newProps api.PersonProperties) error {
func UpdateUserProperties(ctx api.Context, userID string, newProps api.PersonProperties) error {
var current api.Person
if err := ctx.DB().Table("people").Where("id = ?", userID).First(&current).Error; err != nil {
return err
Expand All @@ -29,30 +28,30 @@ func UpdateUserProperties(ctx duty.DBContext, userID string, newProps api.Person
return ctx.DB().Table("people").Where("id = ?", userID).Update("properties", props).Error
}

func UpdateIdentityState(ctx duty.DBContext, id, state string) error {
func UpdateIdentityState(ctx api.Context, id, state string) error {
return ctx.DB().Table("identities").Where("id = ?", id).Update("state", state).Error
}

func GetUserByID(ctx duty.DBContext, id string) (api.Person, error) {
func GetUserByID(ctx api.Context, id string) (api.Person, error) {
var user api.Person
err := ctx.DB().Table("people").Where("id = ?", id).First(&user).Error
return user, err
}

func GetTeamsForUser(ctx duty.DBContext, id string) ([]models.Team, error) {
func GetTeamsForUser(ctx api.Context, id string) ([]models.Team, error) {
var teams []models.Team
err := ctx.DB().Raw("SELECT teams.* FROM teams LEFT JOIN team_members ON teams.id = team_members.team_id WHERE team_members.person_id = ?", id).Scan(&teams).Error
return teams, err
}

func GetUserByExternalID(ctx duty.DBContext, id string) (api.Person, error) {
func GetUserByExternalID(ctx api.Context, id string) (api.Person, error) {
var user api.Person
err := ctx.DB().Table("people").Where("external_id = ?", id).First(&user).Error
return user, err
}

// CreateUser creates a new user and returns a copy
func CreateUser(ctx duty.DBContext, user api.Person) (api.Person, error) {
func CreateUser(ctx api.Context, user api.Person) (api.Person, error) {
err := ctx.DB().Table("people").Create(&user).Error
return user, err
}
Expand All @@ -63,7 +62,7 @@ type CreateUserRequest struct {
Properties models.PersonProperties
}

func CreatePerson(ctx duty.DBContext, name, email, personType string) (*models.Person, error) {
func CreatePerson(ctx api.Context, name, email, personType string) (*models.Person, error) {
person := models.Person{Name: name, Email: email, Type: personType}
if err := ctx.DB().Clauses(clause.Returning{}).Create(&person).Error; err != nil {
return nil, err
Expand All @@ -82,7 +81,7 @@ const (
saltLength = 12
)

func CreateAccessToken(ctx duty.DBContext, personID uuid.UUID, name, password string, expiry time.Duration) (string, error) {
func CreateAccessToken(ctx api.Context, personID uuid.UUID, name, password string, expiry time.Duration) (string, error) {
saltRaw := make([]byte, saltLength)
if _, err := crand.Read(saltRaw); err != nil {
return "", err
Expand Down
19 changes: 9 additions & 10 deletions db/playbooks.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (
"errors"
"fmt"

"github.com/flanksource/duty"
"github.com/flanksource/duty/models"
"github.com/flanksource/duty/types"
"github.com/flanksource/incident-commander/api"
Expand All @@ -14,7 +13,7 @@ import (
"gorm.io/gorm"
)

func FindPlaybooksForEvent(ctx duty.DBContext, eventClass, event string) ([]models.Playbook, error) {
func FindPlaybooksForEvent(ctx api.Context, eventClass, event string) ([]models.Playbook, error) {
var playbooks []models.Playbook
query := fmt.Sprintf(`SELECT * FROM playbooks WHERE spec->'on'->'%s' @> '[{"event": "%s"}]'`, eventClass, event)
if err := ctx.DB().Raw(query).Scan(&playbooks).Error; err != nil {
Expand All @@ -24,7 +23,7 @@ func FindPlaybooksForEvent(ctx duty.DBContext, eventClass, event string) ([]mode
return playbooks, nil
}

func FindPlaybook(ctx duty.DBContext, id uuid.UUID) (*models.Playbook, error) {
func FindPlaybook(ctx api.Context, id uuid.UUID) (*models.Playbook, error) {
var p models.Playbook
if err := ctx.DB().Where("id = ?", id).First(&p).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
Expand All @@ -38,7 +37,7 @@ func FindPlaybook(ctx duty.DBContext, id uuid.UUID) (*models.Playbook, error) {
}

// CanApprove returns true if the given person can approve runs of the given playbook.
func CanApprove(ctx duty.DBContext, personID, playbookID string) (bool, error) {
func CanApprove(ctx api.Context, personID, playbookID string) (bool, error) {
query := `
WITH playbook_approvers AS (
SELECT id,
Expand Down Expand Up @@ -66,7 +65,7 @@ func CanApprove(ctx duty.DBContext, personID, playbookID string) (bool, error) {
return count > 0, nil
}

func GetPlaybookRun(ctx duty.DBContext, id string) (*models.PlaybookRun, error) {
func GetPlaybookRun(ctx api.Context, id string) (*models.PlaybookRun, error) {
var p models.PlaybookRun
if err := ctx.DB().Where("id = ?", id).First(&p).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
Expand All @@ -80,7 +79,7 @@ func GetPlaybookRun(ctx duty.DBContext, id string) (*models.PlaybookRun, error)
}

// FindPlaybooksForCheck returns all the playbooks that match the given check type and tags.
func FindPlaybooksForCheck(ctx duty.DBContext, configType string, tags map[string]string) ([]models.Playbook, error) {
func FindPlaybooksForCheck(ctx api.Context, configType string, tags map[string]string) ([]models.Playbook, error) {
joinQuery := `JOIN LATERAL jsonb_array_elements(playbooks."spec"->'checks') AS checks(ch) ON 1=1`
var joinArgs []any
if len(tags) != 0 {
Expand All @@ -102,7 +101,7 @@ func FindPlaybooksForCheck(ctx duty.DBContext, configType string, tags map[strin
}

// FindPlaybooksForConfig returns all the playbooks that match the given config type and tags.
func FindPlaybooksForConfig(ctx duty.DBContext, configType string, tags map[string]string) ([]models.Playbook, error) {
func FindPlaybooksForConfig(ctx api.Context, configType string, tags map[string]string) ([]models.Playbook, error) {
joinQuery := `JOIN LATERAL jsonb_array_elements(playbooks."spec"->'configs') AS configs(config) ON 1=1`
var joinArgs []any

Expand All @@ -125,7 +124,7 @@ func FindPlaybooksForConfig(ctx duty.DBContext, configType string, tags map[stri
}

// FindPlaybooksForComponent returns all the playbooks that match the given component type and tags.
func FindPlaybooksForComponent(ctx duty.DBContext, configType string, tags map[string]string) ([]models.Playbook, error) {
func FindPlaybooksForComponent(ctx api.Context, configType string, tags map[string]string) ([]models.Playbook, error) {
joinQuery := `JOIN LATERAL jsonb_array_elements(playbooks."spec"->'components') AS components(component) ON 1=1`
var joinArgs []any

Expand Down Expand Up @@ -170,7 +169,7 @@ func DeletePlaybook(id string) error {

// UpdatePlaybookRunStatusIfApproved updates the status of the playbook run to "pending"
// if all the approvers have approved it.
func UpdatePlaybookRunStatusIfApproved(ctx duty.DBContext, playbookID string, approval v1.PlaybookApproval) error {
func UpdatePlaybookRunStatusIfApproved(ctx api.Context, playbookID string, approval v1.PlaybookApproval) error {
if approval.Approvers.Empty() {
return nil
}
Expand Down Expand Up @@ -201,6 +200,6 @@ func UpdatePlaybookRunStatusIfApproved(ctx duty.DBContext, playbookID string, ap
return ctx.DB().Exec(query, approval.Approvers.Teams, approval.Approvers.People, models.PlaybookRunStatusScheduled, models.PlaybookRunStatusPending, playbookID).Error
}

func SavePlaybookRunApproval(ctx duty.DBContext, approval models.PlaybookApproval) error {
func SavePlaybookRunApproval(ctx api.Context, approval models.PlaybookApproval) error {
return ctx.DB().Create(&approval).Error
}
6 changes: 3 additions & 3 deletions db/upstream.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@ import (
"strings"

"github.com/flanksource/commons/logger"
"github.com/flanksource/duty"
"github.com/flanksource/duty/upstream"
"github.com/flanksource/incident-commander/api"
"github.com/google/uuid"
"gorm.io/gorm/clause"
)

func GetAllResourceIDsOfAgent(ctx duty.DBContext, req upstream.PaginateRequest, agentID uuid.UUID) ([]string, error) {
func GetAllResourceIDsOfAgent(ctx api.Context, req upstream.PaginateRequest, agentID uuid.UUID) ([]string, error) {
var response []string
var err error

Expand All @@ -38,7 +38,7 @@ func GetAllResourceIDsOfAgent(ctx duty.DBContext, req upstream.PaginateRequest,
return response, err
}

func InsertUpstreamMsg(ctx duty.DBContext, req *upstream.PushData) error {
func InsertUpstreamMsg(ctx api.Context, req *upstream.PushData) error {
if len(req.Topologies) > 0 {
if err := ctx.DB().Clauses(clause.OnConflict{UpdateAll: true}).Create(req.Topologies).Error; err != nil {
return fmt.Errorf("error upserting topologies: %w", err)
Expand Down
4 changes: 2 additions & 2 deletions events/pg_notify_router.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ package events

import (
"github.com/flanksource/commons/logger"
"github.com/flanksource/duty"
"github.com/flanksource/duty/duty/pg"
"github.com/flanksource/incident-commander/api"
)

// pgNotifyRouter distributes the pgNotify event to multiple channels
Expand All @@ -27,7 +27,7 @@ func (t *pgNotifyRouter) RegisterRoutes(routes []string) <-chan string {
return pgNotifyChannel
}

func (t *pgNotifyRouter) Run(ctx duty.DBContext, channel string) {
func (t *pgNotifyRouter) Run(ctx api.Context, channel string) {
eventQueueNotifyChannel := make(chan string)
go pg.Listen(ctx, channel, eventQueueNotifyChannel)

Expand Down
2 changes: 1 addition & 1 deletion jobs/jobs.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ func ScheduleFunc(schedule string, fn func()) (any, error) {
return FuncScheduler.AddFunc(schedule, fn)
}

func Start(ctx duty.DBContext) {
func Start(ctx api.Context) {
// Running first at startup and then with the schedule
TeamComponentOwnershipRun()
EvaluateEvidenceScripts()
Expand Down
4 changes: 2 additions & 2 deletions playbook/pg_listeners.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
package playbook

import (
"github.com/flanksource/duty"
"github.com/flanksource/duty/duty/pg"
"github.com/flanksource/incident-commander/api"
)

func ListenPlaybookPGNotify(ctx duty.DBContext) {
func ListenPlaybookPGNotify(ctx api.Context) {
pgNotifyPlaybookSpecUpdated := make(chan string)
go pg.Listen(ctx, "playbook_spec_updated", pgNotifyPlaybookSpecUpdated)

Expand Down

0 comments on commit 44ad1da

Please sign in to comment.