thoth.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package thoth
  2. import (
  3. "context"
  4. "crypto/tls"
  5. "fmt"
  6. "time"
  7. "github.com/TecharoHQ/anubis"
  8. iptoasnv1 "github.com/TecharoHQ/thoth-proto/gen/techaro/thoth/iptoasn/v1"
  9. grpcprom "github.com/grpc-ecosystem/go-grpc-middleware/providers/prometheus"
  10. "github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/timeout"
  11. "github.com/prometheus/client_golang/prometheus"
  12. "google.golang.org/grpc"
  13. "google.golang.org/grpc/credentials"
  14. "google.golang.org/grpc/credentials/insecure"
  15. healthv1 "google.golang.org/grpc/health/grpc_health_v1"
  16. )
  17. type Client struct {
  18. conn *grpc.ClientConn
  19. health healthv1.HealthClient
  20. IPToASN iptoasnv1.IpToASNServiceClient
  21. }
  22. func New(ctx context.Context, thothURL, apiToken string, plaintext bool) (*Client, error) {
  23. clMetrics := grpcprom.NewClientMetrics(
  24. grpcprom.WithClientHandlingTimeHistogram(
  25. grpcprom.WithHistogramBuckets([]float64{0.001, 0.01, 0.1, 0.3, 0.6, 1, 3, 6, 9, 20, 30, 60, 90, 120}),
  26. ),
  27. )
  28. prometheus.DefaultRegisterer.Register(clMetrics)
  29. do := []grpc.DialOption{
  30. grpc.WithChainUnaryInterceptor(
  31. timeout.UnaryClientInterceptor(500*time.Millisecond),
  32. clMetrics.UnaryClientInterceptor(),
  33. authUnaryClientInterceptor(apiToken),
  34. ),
  35. grpc.WithChainStreamInterceptor(
  36. clMetrics.StreamClientInterceptor(),
  37. authStreamClientInterceptor(apiToken),
  38. ),
  39. grpc.WithUserAgent(fmt.Sprint("Techaro/anubis:", anubis.Version)),
  40. }
  41. if plaintext {
  42. do = append(do, grpc.WithTransportCredentials(insecure.NewCredentials()))
  43. } else {
  44. do = append(do, grpc.WithTransportCredentials(credentials.NewTLS(&tls.Config{})))
  45. }
  46. conn, err := grpc.NewClient(
  47. thothURL,
  48. do...,
  49. )
  50. if err != nil {
  51. return nil, fmt.Errorf("can't dial thoth at %s: %w", thothURL, err)
  52. }
  53. hc := healthv1.NewHealthClient(conn)
  54. return &Client{
  55. conn: conn,
  56. health: hc,
  57. IPToASN: NewIpToASNWithCache(iptoasnv1.NewIpToASNServiceClient(conn)),
  58. }, nil
  59. }
  60. func (c *Client) Close() error {
  61. if c.conn != nil {
  62. return c.conn.Close()
  63. }
  64. return nil
  65. }
  66. func (c *Client) WithIPToASNService(impl iptoasnv1.IpToASNServiceClient) {
  67. c.IPToASN = impl
  68. }