Skip to content

Commit

Permalink
restructure
Browse files Browse the repository at this point in the history
  • Loading branch information
mleku committed Jan 3, 2024
1 parent 57c05b3 commit ff23dd8
Show file tree
Hide file tree
Showing 13 changed files with 147 additions and 138 deletions.
2 changes: 2 additions & 0 deletions cmd/replicatrd/replicatr/alias.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"net/http"
"sync"

"github.com/Hubmakerlabs/replicatr/pkg/nostr/nip1"
"github.com/fasthttp/websocket"
"github.com/nbd-wtf/go-nostr"
"github.com/nbd-wtf/go-nostr/nip11"
Expand All @@ -21,6 +22,7 @@ type (
TagMap = nostr.TagMap
EventEnvelope = nostr.EventEnvelope
OKEnvelope = nostr.OKEnvelope
EventID = nip1.EventID
CountEnvelope = nostr.CountEnvelope
ClosedEnvelope = nostr.ClosedEnvelope
ReqEnvelope = nostr.ReqEnvelope
Expand Down
28 changes: 28 additions & 0 deletions cmd/replicatrd/replicatr/handlecount.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package replicatr

func (rl *Relay) handleCountRequest(ctx Ctx, ws *WebSocket,
filter *Filter) (subtotal int64) {

// overwrite the filter (for example, to eliminate some kinds or tags that
// we know we don't support)
for _, ovw := range rl.OverwriteCountFilter {
ovw(ctx, filter)
}
// then check if we'll reject this filter
for _, reject := range rl.RejectCountFilter {
if rej, msg := reject(ctx, filter); rej {
rl.E.Chk(ws.WriteJSON(NoticeEnvelope(msg)))
return 0
}
}
// run the functions to count (generally it will be just one)
var e error
var res int64
for _, count := range rl.CountEvents {
if res, e = count(ctx, filter); rl.E.Chk(e) {
rl.E.Chk(ws.WriteJSON(NoticeEnvelope(e.Error())))
}
subtotal += res
}
return
}
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,9 @@ import (
err "errors"

"github.com/Hubmakerlabs/replicatr/pkg/nostr/normalize"
"github.com/pkg/errors"
)

func (rl *Relay) handleRequest(ctx Ctx, id string,
func (rl *Relay) handleFilter(ctx Ctx, id string,
eose *WaitGroup, ws *WebSocket, f *Filter) (e error) {

defer eose.Done()
Expand All @@ -17,7 +16,7 @@ func (rl *Relay) handleRequest(ctx Ctx, id string,
ovw(ctx, f)
}
if f.Limit < 0 {
e = errors.New("blocked: filter invalidated")
e = err.New("blocked: filter invalidated")
rl.E.Chk(e)
return
}
Expand Down Expand Up @@ -57,29 +56,3 @@ func (rl *Relay) handleRequest(ctx Ctx, id string,
return nil
}

func (rl *Relay) handleCountRequest(ctx Ctx, ws *WebSocket,
filter *Filter) (subtotal int64) {

// overwrite the filter (for example, to eliminate some kinds or tags that
// we know we don't support)
for _, ovw := range rl.OverwriteCountFilter {
ovw(ctx, filter)
}
// then check if we'll reject this filter
for _, reject := range rl.RejectCountFilter {
if rej, msg := reject(ctx, filter); rej {
rl.E.Chk(ws.WriteJSON(NoticeEnvelope(msg)))
return 0
}
}
// run the functions to count (generally it will be just one)
var e error
var res int64
for _, count := range rl.CountEvents {
if res, e = count(ctx, filter); rl.E.Chk(e) {
rl.E.Chk(ws.WriteJSON(NoticeEnvelope(e.Error())))
}
subtotal += res
}
return
}
15 changes: 15 additions & 0 deletions cmd/replicatrd/replicatr/handlenip11.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package replicatr

import (
"encoding/json"
"net/http"
)

func (rl *Relay) HandleNIP11(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/nostr+json")
info := rl.Info
for _, ovw := range rl.OverwriteRelayInfo {
info = ovw(r.Context(), r, info)
}
rl.E.Chk(json.NewEncoder(w).Encode(info))
}
37 changes: 37 additions & 0 deletions cmd/replicatrd/replicatr/helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,52 @@ import (
"strings"
"unsafe"

"github.com/nbd-wtf/go-nostr"
"github.com/sebest/xff"
log2 "mleku.online/git/log"
)

const (
wsKey = iota
subscriptionIdKey
)

var (
log = log2.GetLogger()
fails = log.D.Chk
hexDecode, encodeToHex = hex.DecodeString, hex.EncodeToString
)

func RequestAuth(ctx Ctx) {
ws := GetConnection(ctx)
ws.authLock.Lock()
if ws.Authed == nil {
ws.Authed = make(chan struct{})
}
ws.authLock.Unlock()
log.E.Chk(ws.WriteJSON(nostr.AuthEnvelope{Challenge: &ws.Challenge}))
}

func GetConnection(ctx Ctx) *WebSocket { return ctx.Value(wsKey).(*WebSocket) }

func GetAuthed(ctx Ctx) string { return GetConnection(ctx).AuthedPublicKey }

func GetIP(ctx Ctx) string { return xff.GetRemoteAddr(GetConnection(ctx).Request) }

func GetSubscriptionID(ctx Ctx) string { return ctx.Value(subscriptionIdKey).(string) }

func GetOpenSubscriptions(ctx Ctx) Filters {
if subs, ok := listeners.Load(GetConnection(ctx)); ok {
res := make(Filters, 0, listeners.Size()*2)
subs.Range(func(_ string, sub *Listener) bool {
res = append(res, sub.filters...)
return true
})
return res
}
return nil
}

func pointerHasher[V any](_ maphash.Seed, k *V) uint64 {
return uint64(uintptr(unsafe.Pointer(k)))
}
Expand Down
22 changes: 22 additions & 0 deletions cmd/replicatrd/replicatr/http.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package replicatr

import (
"net/http"

"github.com/rs/cors"
)

// ServeHTTP implements http.Handler interface.
func (rl *Relay) ServeHTTP(w ResponseWriter, r *Request) {
if rl.ServiceURL == "" {
rl.ServiceURL = getServiceBaseURL(r)
}
if r.Header.Get("Upgrade") == "websocket" {
rl.HandleWebsocket(w, r)
} else if r.Header.Get("Accept") == "application/nostr+json" {
cors.AllowAll().Handler(http.HandlerFunc(rl.HandleNIP11)).ServeHTTP(w, r)
} else {
rl.serveMux.ServeHTTP(w, r)
}
}

Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ import (
"golang.org/x/exp/slices"
)

// RejectKind04Snoopers prevents reading NIP-04 messages from people not
// RejectKind4Snoopers prevents reading NIP-04 messages from people not
// involved in the conversation.
func RejectKind04Snoopers(ctx Ctx, filter *Filter) (bool, string) {
func RejectKind4Snoopers(ctx Ctx, filter *Filter) (bool, string) {
// prevent kind-4 events from being returned to unauthed users, only when
// authentication is a thing
if !slices.Contains(filter.Kinds, 4) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,10 @@ func PreventTooManyIndexableTags(max int, ignoreKinds []int,
return !isApplicable
}
}

return func(ctx Ctx, event *Event) (reject bool, msg string) {
if ignore(event.Kind) {
return false, ""
}

ntags := 0
for _, tag := range event.Tags {
if len(tag) > 0 && len(tag[0]) == 1 {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package replicatr
import (
"context"

"github.com/nbd-wtf/go-nostr"
"golang.org/x/exp/slices"
)

Expand Down Expand Up @@ -47,7 +46,7 @@ func RemoveSearchQueries(ctx Ctx, filter *Filter) {
filter.Search = ""
}

func RemoveAllButKinds(kinds ...uint16) func(Ctx, *nostr.Filter) {
func RemoveAllButKinds(kinds ...uint16) func(Ctx, *Filter) {
return func(ctx Ctx, filter *Filter) {
if n := len(filter.Kinds); n > 0 {
newKinds := make([]int, 0, n)
Expand Down
46 changes: 23 additions & 23 deletions cmd/replicatrd/replicatr/relay.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,29 +35,6 @@ type (
OnEventSaved func(ctx Ctx, event *Event)
)

func NewRelay(appName string) (r *Relay) {
r = &Relay{
Log: log2.New(os.Stderr, appName, 0),
Info: &Info{
Software: "https://github.com/Hubmakerlabs/replicatr/cmd/khatru",
Version: "n/a",
SupportedNIPs: make([]int, 0),
},
upgrader: websocket.Upgrader{
ReadBufferSize: ReadBufferSize,
WriteBufferSize: WriteBufferSize,
CheckOrigin: func(r *http.Request) bool { return true },
},
clients: xsync.NewTypedMapOf[*websocket.Conn, struct{}](pointerHasher[websocket.Conn]),
serveMux: &http.ServeMux{},
WriteWait: WriteWait,
PongWait: PongWait,
PingPeriod: PingPeriod,
MaxMessageSize: MaxMessageSize,
}
return
}

type Relay struct {
ServiceURL string
RejectEvent []RejectEvent
Expand Down Expand Up @@ -92,3 +69,26 @@ type Relay struct {
PingPeriod time.Duration // Send pings to peer with this period. Must be less than pongWait.
MaxMessageSize int64 // Maximum message size allowed from peer.
}

func NewRelay(appName string) (r *Relay) {
r = &Relay{
Log: log2.New(os.Stderr, appName, 0),
Info: &Info{
Software: "https://github.com/Hubmakerlabs/replicatr/cmd/khatru",
Version: "n/a",
SupportedNIPs: make([]int, 0),
},
upgrader: websocket.Upgrader{
ReadBufferSize: ReadBufferSize,
WriteBufferSize: WriteBufferSize,
CheckOrigin: func(r *http.Request) bool { return true },
},
clients: xsync.NewTypedMapOf[*websocket.Conn, struct{}](pointerHasher[websocket.Conn]),
serveMux: &http.ServeMux{},
WriteWait: WriteWait,
PongWait: PongWait,
PingPeriod: PingPeriod,
MaxMessageSize: MaxMessageSize,
}
return
}
41 changes: 0 additions & 41 deletions cmd/replicatrd/replicatr/utils.go

This file was deleted.

Loading

0 comments on commit ff23dd8

Please sign in to comment.