diff --git a/src/github.com/matrix-org/go-neb/database/db.go b/src/github.com/matrix-org/go-neb/database/db.go index 79c83bc..bb3fdc2 100644 --- a/src/github.com/matrix-org/go-neb/database/db.go +++ b/src/github.com/matrix-org/go-neb/database/db.go @@ -104,6 +104,14 @@ func (d *ServiceDB) LoadService(serviceID string) (service types.Service, err er return } +// DeleteService deletes the given service from the database. +func (d *ServiceDB) DeleteService(serviceID string) (err error) { + err = runTransaction(d.db, func(txn *sql.Tx) error { + return deleteServiceTxn(txn, serviceID) + }) + return +} + // LoadServicesForUser loads all the bot services configured for a given user. // Returns an empty list if there aren't any services configured. func (d *ServiceDB) LoadServicesForUser(serviceUserID string) (services []types.Service, err error) { diff --git a/src/github.com/matrix-org/go-neb/database/schema.go b/src/github.com/matrix-org/go-neb/database/schema.go index e60e23a..0a56857 100644 --- a/src/github.com/matrix-org/go-neb/database/schema.go +++ b/src/github.com/matrix-org/go-neb/database/schema.go @@ -231,6 +231,15 @@ func selectServicesForUserTxn(txn *sql.Tx, userID string) (srvs []types.Service, return } +const deleteServiceSQL = ` +DELETE FROM services WHERE service_id = $1 +` + +func deleteServiceTxn(txn *sql.Tx, serviceID string) error { + _, err := txn.Exec(deleteServiceSQL, serviceID) + return err +} + const insertRealmSQL = ` INSERT INTO auth_realms( realm_id, realm_type, realm_json, time_added_ms, time_updated_ms diff --git a/src/github.com/matrix-org/go-neb/services/github/github_webhook.go b/src/github.com/matrix-org/go-neb/services/github/github_webhook.go index 4feeac2..6f6daf3 100644 --- a/src/github.com/matrix-org/go-neb/services/github/github_webhook.go +++ b/src/github.com/matrix-org/go-neb/services/github/github_webhook.go @@ -192,6 +192,20 @@ func (s *githubWebhookService) PostRegister(oldService types.Service) { }).Warn("Failed to remove webhook") } } + + // If we are not tracking any repos any more then we are back to square 1 and not doing anything + // so remove ourselves from the database. This is safe because this is still within the critical + // section for this service. + if len(newRepos) == 0 { + logger := log.WithFields(log.Fields{ + "service_type": s.ServiceType(), + "service_id": s.ServiceID(), + }) + logger.Info("Removing service as no webhooks are registered.") + if err := database.GetServiceDB().DeleteService(s.ServiceID()); err != nil { + logger.WithError(err).Error("Failed to delete service") + } + } } func (s *githubWebhookService) joinWebhookRooms(client *matrix.Client) error {