Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ratelimit requests to plc directory and bsky.social from Palomar #329

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions cmd/palomar/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,15 @@ import (
"encoding/json"
"fmt"
"log/slog"
"net"
"net/http"
"net/url"
"os"
"strings"
"time"

_ "github.com/joho/godotenv/autoload"
"golang.org/x/time/rate"

"github.com/bluesky-social/indigo/atproto/identity"
"github.com/bluesky-social/indigo/search"
Expand Down Expand Up @@ -132,6 +135,16 @@ var runCmd = &cli.Command{
Value: 20,
EnvVars: []string{"PALOMAR_INDEX_MAX_CONCURRENCY"},
},
&cli.IntFlag{
Name: "plc-rate-limit",
Usage: "max number of requests per second to PLC registry",
Value: 20,
},
&cli.IntFlag{
Name: "bsky-social-rate-limit",
Usage: "max number of requests per second to bsky.social",
Value: 20,
},
},
Action: func(cctx *cli.Context) error {
logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
Expand All @@ -149,11 +162,33 @@ var runCmd = &cli.Command{
return fmt.Errorf("failed to get elasticsearch: %w", err)
}

plcRateLimiter := rate.NewLimiter(rate.Limit(cctx.Int("plc-rate-limit")), 1)
bskySocialRateLimiter := rate.NewLimiter(rate.Limit(cctx.Int("bsky-social-rate-limit")), 1)

plcAddr, err := url.Parse(cctx.String("atp-plc-host"))
if err != nil {
return fmt.Errorf("failed to parse PLC URL: %w", err)
}

// TODO: replace this with "bingo" resolver
base := identity.BaseDirectory{
PLCURL: cctx.String("atp-plc-host"),
HTTPClient: http.Client{
Timeout: time.Second * 15,
Transport: &http.Transport{
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
if strings.HasPrefix(addr, plcAddr.Host) {
if err := plcRateLimiter.Wait(ctx); err != nil {
return nil, fmt.Errorf("failed to wait for PLC rate limiter: %w", err)
}
} else if strings.Contains(addr, ".bsky.social/") {
if err := bskySocialRateLimiter.Wait(ctx); err != nil {
return nil, fmt.Errorf("failed to wait for bsky.social rate limiter: %w", err)
}
}
return net.DialTimeout(network, addr, time.Second*15)
},
},
},
TryAuthoritativeDNS: true,
SkipDNSDomainSuffixes: []string{".bsky.social"},
Expand Down
Loading