Skip to content

Commit

Permalink
fix: db issues beforesave and afterfind
Browse files Browse the repository at this point in the history
  • Loading branch information
im-adithya committed Feb 22, 2024
1 parent 92c981a commit 995924a
Show file tree
Hide file tree
Showing 4 changed files with 133 additions and 45 deletions.
109 changes: 95 additions & 14 deletions internal/nostr/models.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
package nostr

import (
"encoding/json"
"time"

"github.com/nbd-wtf/go-nostr"
"gorm.io/gorm"
)

const (
Expand All @@ -21,20 +23,99 @@ const (
)

type Subscription struct {
ID uint
RelayUrl string `validate:"required"`
WebhookUrl string
Open bool // "open" / "closed"
Ids *[]string `gorm:"type:jsonb"`
Kinds *[]int `gorm:"type:jsonb"`
Authors *[]string `gorm:"type:jsonb"` // WalletPubkey is included in this
Tags *nostr.TagMap `gorm:"type:jsonb"` // RequestEvent ID goes in the "e" tag
Since time.Time
Until time.Time
Limit int
Search string
CreatedAt time.Time
UpdatedAt time.Time
ID uint
RelayUrl string `validate:"required"`
WebhookUrl string
Open bool // "open" / "closed"
Ids *[]string `gorm:"-"`
Kinds *[]int `gorm:"-"`
Authors *[]string `gorm:"-"` // WalletPubkey is included in this
Tags *nostr.TagMap `gorm:"-"` // RequestEvent ID goes in the "e" tag
Since time.Time
Until time.Time
Limit int
Search string
CreatedAt time.Time
UpdatedAt time.Time

IdsString string
KindsString string
AuthorsString string
TagsString string
}

func (s *Subscription) BeforeSave(tx *gorm.DB) error {
var err error
if s.Ids != nil {
var idsJson []byte
idsJson, err = json.Marshal(s.Ids)
if err != nil {
return err
}
s.IdsString = string(idsJson)
}

if s.Kinds != nil {
var kindsJson []byte
kindsJson, err = json.Marshal(s.Kinds)
if err != nil {
return err
}
s.KindsString = string(kindsJson)
}

if s.Authors != nil {
var authorsJson []byte
authorsJson, err = json.Marshal(s.Authors)
if err != nil {
return err
}
s.AuthorsString = string(authorsJson)
}

if s.Tags != nil {
var tagsJson []byte
tagsJson, err = json.Marshal(s.Tags)
if err != nil {
return err
}
s.TagsString = string(tagsJson)
}

return nil
}

func (s *Subscription) AfterFind(tx *gorm.DB) error {
var err error
if s.IdsString != "" {
err = json.Unmarshal([]byte(s.IdsString), &s.Ids)
if err != nil {
return err
}
}

if s.KindsString != "" {
err = json.Unmarshal([]byte(s.KindsString), &s.Kinds)
if err != nil {
return err
}
}

if s.AuthorsString != "" {
err = json.Unmarshal([]byte(s.AuthorsString), &s.Authors)
if err != nil {
return err
}
}

if s.TagsString != "" {
err = json.Unmarshal([]byte(s.TagsString), &s.Tags)
if err != nil {
return err
}
}

return nil
}

type RequestEvent struct {
Expand Down
59 changes: 33 additions & 26 deletions internal/nostr/nostr.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ func NewService(ctx context.Context) (*Service, error) {
logger.Fatalf("Failed to migrate: %v", err)
return nil, err
}
logger.Println("Any pending migrations ran successfully")
logger.Info("Any pending migrations ran successfully")

ctx, _ = signal.NotifyContext(ctx, os.Interrupt)

Expand Down Expand Up @@ -187,33 +187,41 @@ func (svc *Service) NIP47Handler(c echo.Context) error {
})
}

// TODO: check if the RequestEvent already exists in our db

requestEvent := RequestEvent{
NostrId: requestData.SignedEvent.ID,
Content: requestData.SignedEvent.Content,
}
subscription := Subscription{}
requestEvent := RequestEvent{}
findRequestResult := svc.db.Where("nostr_id = ?", requestData.SignedEvent.ID).Find(&requestEvent)
if findRequestResult.RowsAffected != 0 {
svc.Logger.Info("request event is already processed")
return c.JSON(http.StatusBadRequest, ErrorResponse{
Message: "request event is already processed",
})
} else {
subscription = Subscription{
RelayUrl: requestData.RelayUrl,
WebhookUrl: requestData.WebhookUrl,
Open: true,
Ids: &[]string{},
Authors: &[]string{requestData.WalletPubkey},
Kinds: &[]int{NIP_47_RESPONSE_KIND},
Tags: &nostr.TagMap{"e": []string{requestEvent.NostrId}},
Since: time.Now(),
Limit: 1,
}
svc.db.Create(&subscription)

subscription := Subscription{
RelayUrl: requestData.RelayUrl,
WebhookUrl: requestData.WebhookUrl,
Open: true,
Ids: &[]string{},
Authors: &[]string{requestData.WalletPubkey},
Kinds: &[]int{NIP_47_RESPONSE_KIND},
Tags: &nostr.TagMap{"e": []string{requestEvent.NostrId}},
Since: time.Now(),
Limit: 1,
requestEvent = RequestEvent{
NostrId: requestData.SignedEvent.ID,
Content: requestData.SignedEvent.Content,
SubscriptionId: subscription.ID,
}
svc.db.Create(&requestEvent)
}

svc.db.Create(&subscription)

requestEvent.SubscriptionId = subscription.ID
svc.db.Create(&requestEvent)

if subscription.WebhookUrl != "" {
go func() {
event, publishState, _, err := svc.processRequest(context.Background(), &subscription, &requestEvent, requestData.SignedEvent)
ctx, cancel := context.WithTimeout(context.Background(), 120*time.Second)
defer cancel()
event, publishState, _, err := svc.processRequest(ctx, &subscription, &requestEvent, requestData.SignedEvent)
subscription.Open = false
requestEvent.State = publishState
svc.db.Save(&subscription)
Expand All @@ -228,7 +236,7 @@ func (svc *Service) NIP47Handler(c echo.Context) error {
RequestId: requestEvent.ID,
NostrId: event.ID,
Content: event.Content,
RepliedAt: time.Now(),
RepliedAt: event.CreatedAt.Time(),
}
svc.db.Save(&responseEvent)
svc.postEventToWebhook(event, requestData.WebhookUrl)
Expand All @@ -252,7 +260,7 @@ func (svc *Service) NIP47Handler(c echo.Context) error {
RequestId: requestEvent.ID,
NostrId: event.ID,
Content: event.Content,
RepliedAt: time.Now(),
RepliedAt: event.CreatedAt.Time(),
}
svc.db.Save(&responseEvent)
return c.JSON(http.StatusOK, event)
Expand Down Expand Up @@ -301,7 +309,6 @@ func (svc *Service) processRequest(ctx context.Context, subscription *Subscripti
Since: &since,
Limit: subscription.Limit,
}
fmt.Println(filter.Kinds[0], filter.Authors[0], filter.Tags["e"])

sub, err := relay.Subscribe(ctx, []nostr.Filter{filter})
if err != nil {
Expand Down
8 changes: 4 additions & 4 deletions migrations/initial_migration_postgres.sql
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@ CREATE TABLE subscriptions (
id bigint NOT NULL,
relay_url text,
webhook_url text,
ids jsonb,
kinds jsonb,
authors jsonb,
tags jsonb,
ids_string text,
kinds_string text,
authors_string text,
tags_string text,
since timestamp with time zone,
until timestamp with time zone,
"limit" integer,
Expand Down
2 changes: 1 addition & 1 deletion migrations/initial_migration_sqlite.sql
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
CREATE TABLE "subscriptions" (`id` integer,`relay_url` text,`webhook_url` text,`ids` json,`kinds` json,`authors` json,`tags` json,`since` datetime,`until` datetime,`limit` integer,`search` text,`open` boolean,`created_at` datetime,`updated_at` datetime,PRIMARY KEY (`id`));
CREATE TABLE "subscriptions" (`id` integer,`relay_url` text,`webhook_url` text,`ids_string` text,`kinds_string` text,`authors_string` text,`tags_string` text,`since` datetime,`until` datetime,`limit` integer,`search` text,`open` boolean,`created_at` datetime,`updated_at` datetime,PRIMARY KEY (`id`));
CREATE TABLE "request_events" (`id` integer,`subscription_id` integer,`nostr_id` text UNIQUE,`content` text,`state` text,`created_at` datetime,`updated_at` datetime,PRIMARY KEY (`id`),CONSTRAINT `fk_request_events_subscription` FOREIGN KEY (`subscription_id`) REFERENCES `subscriptions`(`id`) ON DELETE CASCADE);
CREATE TABLE "response_events" (`id` integer,`subscription_id` integer,`request_id` integer,`nostr_id` text UNIQUE,`content` text,`replied_at` datetime,`created_at` datetime,`updated_at` datetime,PRIMARY KEY (`id`),CONSTRAINT `fk_response_events_subscription` FOREIGN KEY (`subscription_id`) REFERENCES `subscriptions`(`id`) ON DELETE CASCADE,CONSTRAINT `fk_response_events_request_event` FOREIGN KEY (`request_id`) REFERENCES `request_events`(`id`) ON DELETE CASCADE);

0 comments on commit 995924a

Please sign in to comment.