Skip to content

Commit d4f8479

Browse files
committed
all: start to switch to slog
1 parent 07b4c3a commit d4f8479

File tree

10 files changed

+94
-74
lines changed

10 files changed

+94
-74
lines changed

Diff for: activitypub/activitypub.go

+7
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,18 @@ import (
1414
"github.com/go-chi/chi/v5"
1515
"github.com/go-json-experiment/json"
1616
"gorm.io/gorm"
17+
18+
"golang.org/x/exp/slog"
1719
)
1820

1921
type Env struct {
2022
*gorm.DB
2123
*streaming.Mux
24+
Logger *slog.Logger
25+
}
26+
27+
func (e *Env) Log() *slog.Logger {
28+
return e.Logger
2229
}
2330

2431
func Followers(env *Env, w http.ResponseWriter, r *http.Request) error {

Diff for: activitypub/inbox.go

+24-31
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import (
1515
"github.com/davecheney/pub/models"
1616
"github.com/go-fed/httpsig"
1717
"github.com/go-json-experiment/json"
18+
"golang.org/x/exp/slog"
1819
"gorm.io/gorm"
1920
"gorm.io/gorm/clause"
2021
)
@@ -43,6 +44,7 @@ func (i *InboxController) Create(env *Env, w http.ResponseWriter, r *http.Reques
4344
// if we need to make an activity pub request, we need to sign it with the
4445
// instance's admin account.
4546
processor := &inboxProcessor{
47+
logger: env.Logger.With("instance", instance.Domain),
4648
req: r,
4749
db: i.db,
4850
signAs: instance.Admin,
@@ -85,6 +87,7 @@ func (i *InboxController) fetchActor(uri string) (*models.Actor, error) {
8587
}
8688

8789
type inboxProcessor struct {
90+
logger *slog.Logger
8891
req *http.Request
8992
db *gorm.DB
9093
signAs *models.Account
@@ -95,7 +98,8 @@ type inboxProcessor struct {
9598
// blocking, it is handled immediately. If the activity requires blocking, it is
9699
// queued for later processing.
97100
func (i *inboxProcessor) processActivity(act *Activity) error {
98-
fmt.Println("processActivity: type:", act.Type, "id:", act.ID)
101+
i.logger = i.logger.With("id", act.ID, "type", act.Type)
102+
i.logger.Info("processActivity")
99103
switch act.Type {
100104
case "":
101105
return httpx.Error(http.StatusBadRequest, errors.New("missing type"))
@@ -194,28 +198,16 @@ func (i *inboxProcessor) processAnnounce(act *Activity) error {
194198
updatedAt = publishedAt
195199
}
196200

197-
conv := models.Conversation{
198-
Visibility: "public",
199-
}
200-
if err := i.db.Create(&conv).Error; err != nil {
201-
return err
202-
}
203-
204201
status := &models.Status{
205-
ID: snowflake.TimeToID(publishedAt),
206-
UpdatedAt: updatedAt,
207-
ActorID: actor.ID,
208-
Actor: actor,
209-
ConversationID: conv.ID,
210-
URI: act.ID,
211-
InReplyToID: nil,
212-
InReplyToActorID: nil,
213-
Sensitive: false,
214-
SpoilerText: "",
215-
Visibility: "public",
216-
Language: "",
217-
Note: "",
218-
ReblogID: &original.ID,
202+
ID: snowflake.TimeToID(publishedAt),
203+
UpdatedAt: updatedAt,
204+
Actor: actor,
205+
Conversation: &models.Conversation{
206+
Visibility: "public",
207+
},
208+
URI: act.ID,
209+
Visibility: "public",
210+
ReblogID: &original.ID,
219211
}
220212

221213
return i.db.Create(status).Error
@@ -410,7 +402,6 @@ func inReplyToActorID(inReplyTo *models.Status) *snowflake.ID {
410402
}
411403

412404
func objToStatusAttachment(obj map[string]any) *models.StatusAttachment {
413-
fmt.Println("objToStatusAttachment:", obj)
414405
return &models.StatusAttachment{
415406
Attachment: models.Attachment{
416407
ID: snowflake.Now(),
@@ -591,19 +582,21 @@ func (i *inboxProcessor) processDeleteStatus(uri string) error {
591582
}
592583

593584
func (i *inboxProcessor) processDeleteActor(uri string) error {
594-
// load actor to delete it so we can fire the delete hooks.
595-
actor, err := models.NewActors(i.db).FindByURI(uri)
596-
if err != nil {
597-
if errors.Is(err, gorm.ErrRecordNotFound) {
598-
// already deleted
599-
return nil
600-
}
585+
// use this form to avoid firing gorm's ErrNotFound mechanism;
586+
// most deletes we don't know about, and that's fine.
587+
var actors []*models.Actor
588+
if err := i.db.Limit(1).Where("uri = ?", uri).Find(&actors).Error; err != nil {
601589
return err
602590
}
591+
if len(actors) == 0 {
592+
// already deleted
593+
return nil
594+
}
595+
actor := actors[0]
603596
if err := i.validateSignature(); err != nil {
604597
return httpx.Error(http.StatusUnauthorized, err)
605598
}
606-
return i.db.Delete(&actor).Error
599+
return i.db.Delete(actor).Error
607600
}
608601

609602
func (i *inboxProcessor) validateSignature() error {

Diff for: go.mod

+1-1
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ require (
1414
github.com/pkg/group v1.0.0
1515
github.com/stretchr/testify v1.8.2
1616
golang.org/x/crypto v0.8.0
17+
golang.org/x/exp v0.0.0-20230321023759-10a507213a29
1718
golang.org/x/image v0.7.0
1819
golang.org/x/net v0.9.0
1920
gorm.io/driver/mysql v1.5.0
@@ -28,7 +29,6 @@ require (
2829
github.com/jinzhu/now v1.1.5 // indirect
2930
github.com/mattn/go-sqlite3 v1.14.16 // indirect
3031
github.com/pmezard/go-difflib v1.0.0 // indirect
31-
golang.org/x/exp v0.0.0-20230321023759-10a507213a29 // indirect
3232
golang.org/x/sys v0.7.0 // indirect
3333
gopkg.in/yaml.v3 v3.0.1 // indirect
3434
)

Diff for: internal/httpx/handler.go

+12-12
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,10 @@ package httpx
55

66
import (
77
"errors"
8-
"log"
98
"net/http"
109

1110
"github.com/go-json-experiment/json"
11+
"golang.org/x/exp/slog"
1212
)
1313

1414
// Error is a convenience function for returning an error with an associated HTTP status code.
@@ -32,25 +32,25 @@ func (se *StatusError) Status() int {
3232
return se.Code
3333
}
3434

35+
type env interface {
36+
Log() *slog.Logger
37+
}
38+
3539
// HandlerFunc adapts a function that returns an error to an http.HandlerFunc.
36-
func HandlerFunc[E any](envFn func(r *http.Request) *E, fn func(*E, http.ResponseWriter, *http.Request) error) http.HandlerFunc {
40+
func HandlerFunc[E env](envFn func(r *http.Request) E, fn func(E, http.ResponseWriter, *http.Request) error) http.HandlerFunc {
3741
return func(w http.ResponseWriter, r *http.Request) {
3842
env := envFn(r)
3943
err := fn(env, w, r)
4044
if err != nil {
41-
w.Header().Set("Content-Type", "application/json; charset=utf-8")
45+
status := http.StatusInternalServerError
4246
if se := new(StatusError); errors.As(err, &se) {
43-
log.Printf("HTTP: method: %s, path: %s, status: %d, error: %s", r.Method, r.URL.Path, se.Status(), err)
44-
w.WriteHeader(se.Status())
45-
json.MarshalFull(w, map[string]any{
46-
"error": se.Error(),
47-
})
48-
return
47+
status = se.Code
4948
}
50-
log.Printf("HTTP: method: %s, path: %s, status: %d, error: %s", r.Method, r.URL.Path, http.StatusInternalServerError, err)
51-
w.WriteHeader(http.StatusInternalServerError)
49+
env.Log().Error("HTTP", "method", r.Method, "path", r.URL.Path, "status", status, "error", err)
50+
w.Header().Set("Content-Type", "application/json; charset=utf-8")
51+
w.WriteHeader(status)
5252
json.MarshalFull(w, map[string]any{
53-
"error": http.StatusInternalServerError,
53+
"error": err.Error(),
5454
})
5555
}
5656
}

Diff for: main.go

+8-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
package main
22

33
import (
4+
"os"
5+
6+
"golang.org/x/exp/slog"
7+
48
"github.com/alecthomas/kong"
59
"gorm.io/gorm"
610
"gorm.io/gorm/logger"
@@ -9,6 +13,8 @@ import (
913
type Context struct {
1014
Debug bool
1115

16+
Logger *slog.Logger
17+
1218
gorm.Config
1319
gorm.Dialector
1420
}
@@ -29,7 +35,8 @@ var cli struct {
2935
func main() {
3036
ctx := kong.Parse(&cli)
3137
err := ctx.Run(&Context{
32-
Debug: cli.LogSQL,
38+
Debug: cli.LogSQL,
39+
Logger: slog.New(slog.NewTextHandler(os.Stderr)),
3340
Config: gorm.Config{
3441
Logger: logger.Default.LogMode(func() logger.LogLevel {
3542
if cli.LogSQL {

Diff for: mastodon/mastodon.go

+6
Original file line numberDiff line numberDiff line change
@@ -12,12 +12,18 @@ import (
1212
"github.com/davecheney/pub/internal/snowflake"
1313
"github.com/davecheney/pub/internal/streaming"
1414
"github.com/davecheney/pub/models"
15+
"golang.org/x/exp/slog"
1516
"gorm.io/gorm"
1617
)
1718

1819
type Env struct {
1920
*gorm.DB
2021
*streaming.Mux
22+
Logger *slog.Logger
23+
}
24+
25+
func (e *Env) Log() *slog.Logger {
26+
return e.Logger
2127
}
2228

2329
// authenticate authenticates the bearer token attached to the request and, if

Diff for: models/actor.go

+10-16
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
package models
22

33
import (
4-
"errors"
54
"fmt"
65
"net/http"
76
"time"
@@ -157,14 +156,15 @@ func NewActors(db *gorm.DB) *Actors {
157156

158157
// FindOrCreate finds an account by its URI, or creates it if it doesn't exist.
159158
func (a *Actors) FindOrCreate(uri string, createFn func(string) (*Actor, error)) (*Actor, error) {
160-
actor, err := a.FindByURI(uri)
161-
if err == nil {
162-
// found cached key
163-
return actor, nil
164-
}
165-
if !errors.Is(err, gorm.ErrRecordNotFound) {
159+
// use find to avoid record not found error in case of empty result
160+
var actors []Actor
161+
if err := a.db.Limit(1).Find(&actors, "uri = ?", uri).Error; err != nil {
166162
return nil, err
167163
}
164+
if len(actors) > 0 {
165+
// found cached key
166+
return &actors[0], nil
167+
}
168168

169169
acc, err := createFn(uri)
170170
if err != nil {
@@ -176,15 +176,9 @@ func (a *Actors) FindOrCreate(uri string, createFn func(string) (*Actor, error))
176176

177177
// FindByURI returns an account by its URI if it exists locally.
178178
func (a *Actors) FindByURI(uri string) (*Actor, error) {
179-
// use find to avoid record not found error in case of empty result
180-
var actors []Actor
181-
if err := a.db.Limit(1).Find(&actors, "uri = ?", uri).Error; err != nil {
182-
return nil, err
183-
}
184-
if len(actors) == 0 {
185-
return nil, gorm.ErrRecordNotFound
186-
}
187-
return &actors[0], nil
179+
var actor Actor
180+
err := a.db.Where("URI = ?", uri).Take(&actor).Error
181+
return &actor, err
188182
}
189183

190184
// Refesh schedules a refresh of an actor's data.

Diff for: models/env.go

+7-1
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,16 @@
11
package models
22

33
import (
4+
"golang.org/x/exp/slog"
45
"gorm.io/gorm"
56
)
67

78
type Env struct {
89
// DB is the database connection.
9-
DB *gorm.DB
10+
DB *gorm.DB
11+
Logger *slog.Logger
12+
}
13+
14+
func (e *Env) Log() *slog.Logger {
15+
return e.Logger
1016
}

Diff for: serve.go

+9-6
Original file line numberDiff line numberDiff line change
@@ -62,8 +62,9 @@ func (s *ServeCmd) Run(ctx *Context) error {
6262
r.Route("/api", func(r chi.Router) {
6363
envFn := func(r *http.Request) *mastodon.Env {
6464
return &mastodon.Env{
65-
DB: db.WithContext(r.Context()),
66-
Mux: &mux,
65+
DB: db.WithContext(r.Context()),
66+
Mux: &mux,
67+
Logger: ctx.Logger,
6768
}
6869
}
6970
r.Route("/v1", func(r chi.Router) {
@@ -150,8 +151,9 @@ func (s *ServeCmd) Run(ctx *Context) error {
150151

151152
envFn := func(r *http.Request) *activitypub.Env {
152153
return &activitypub.Env{
153-
DB: db.WithContext(r.Context()),
154-
Mux: &mux,
154+
DB: db.WithContext(r.Context()),
155+
Mux: &mux,
156+
Logger: ctx.Logger,
155157
}
156158
}
157159

@@ -182,7 +184,8 @@ func (s *ServeCmd) Run(ctx *Context) error {
182184

183185
modelEnvFn := func(r *http.Request) *models.Env {
184186
return &models.Env{
185-
DB: db.WithContext(r.Context()),
187+
DB: db.WithContext(r.Context()),
188+
Logger: ctx.Logger,
186189
}
187190
}
188191

@@ -223,7 +226,7 @@ func (s *ServeCmd) Run(ctx *Context) error {
223226
return svr.ListenAndServe()
224227
})
225228

226-
g.Add(workers.NewRelationshipRequestProcessor(db))
229+
g.Add(workers.NewRelationshipRequestProcessor(ctx.Logger, db))
227230
g.Add(workers.NewReactionRequestProcessor(db))
228231
g.Add(workers.NewStatusAttachmentRequestProcessor(db))
229232

Diff for: workers/relationships.go

+10-6
Original file line numberDiff line numberDiff line change
@@ -7,18 +7,22 @@ import (
77

88
"github.com/davecheney/pub/activitypub"
99
"github.com/davecheney/pub/models"
10+
"golang.org/x/exp/slog"
1011
"gorm.io/gorm"
1112
)
1213

1314
// RelationshipRequestProcessor handles delivery of relationship requests.
14-
func NewRelationshipRequestProcessor(db *gorm.DB) func(ctx context.Context) error {
15+
func NewRelationshipRequestProcessor(log *slog.Logger, db *gorm.DB) func(ctx context.Context) error {
16+
log = log.With("worker", "RelationshipRequestProcessor")
1517
return func(ctx context.Context) error {
16-
fmt.Println("RelationshipRequestProcessor started")
17-
defer fmt.Println("RelationshipRequestProcessor stopped")
18+
log.Info("started")
19+
defer log.Info("stopped")
1820

1921
db := db.WithContext(ctx)
2022
for {
21-
if err := process(db, relationshipRequestScope, processRelationshipRequest); err != nil {
23+
if err := process(db, relationshipRequestScope, func(db *gorm.DB, request *models.RelationshipRequest) error {
24+
return processRelationshipRequest(log, db, request)
25+
}); err != nil {
2226
return err
2327
}
2428
select {
@@ -35,8 +39,8 @@ func relationshipRequestScope(db *gorm.DB) *gorm.DB {
3539
return db.Preload("Actor").Preload("Target").Where("attempts < 3")
3640
}
3741

38-
func processRelationshipRequest(db *gorm.DB, request *models.RelationshipRequest) error {
39-
fmt.Println("RelationshipRequestProcessor: actor:", request.Actor.URI, "target:", request.Target.URI, "action:", request.Action)
42+
func processRelationshipRequest(log *slog.Logger, db *gorm.DB, request *models.RelationshipRequest) error {
43+
log.Info("", "request", request.ID, "actor_id", request.Actor.ID, "target_id", request.Target.ID, "action", request.Action)
4044
accounts := models.NewAccounts(db)
4145
account, err := accounts.AccountForActor(request.Actor)
4246
if err != nil {

0 commit comments

Comments
 (0)