package apollo import ( "bytes" "context" "encoding/json" "errors" "fmt" "io" "net/http" "strconv" "strings" "time" "github.com/warmbly/warmbly/internal/models" ) const defaultBaseURL = "https://api.apollo.io/api/v1" // Errors a caller branches on. Messages are written for the person who pasted // the key, so they can be shown as they are. var ( ErrKey = errors.New("Apollo rejected this API key") ErrForbidden = errors.New("this Apollo API key is not allowed to read lists and contacts. Use a master key, or a key with access to lists and contact search") ErrRateLimited = errors.New("Apollo is rate limiting this account. Try again in a few minutes") ErrUnavailable = errors.New("Apollo did not answer. Try again in a few minutes") ) // Client calls Apollo's REST API with one workspace's API key. type Client struct { key string base string http *http.Client // sleep is replaced in tests so retries do not wait. sleep func(ctx context.Context, d time.Duration) error } // NewClient builds a client for one API key. func NewClient(key string) *Client { return &Client{ key: strings.TrimSpace(key), base: defaultBaseURL, http: &http.Client{Timeout: 30 * time.Second}, sleep: sleepCtx, } } func sleepCtx(ctx context.Context, d time.Duration) error { t := time.NewTimer(d) defer t.Stop() select { case <-ctx.Done(): return ctx.Err() case <-t.C: return nil } } // do sends one request, retrying a rate limit or a server error a few times. func (c *Client) do(ctx context.Context, method, path string, body any, out any) error { var raw []byte if body != nil { b, err := json.Marshal(body) if err != nil { return err } raw = b } var lastErr error for attempt := 0; attempt < 4; attempt++ { var rd io.Reader if raw != nil { rd = bytes.NewReader(raw) } req, err := http.NewRequestWithContext(ctx, method, c.base+path, rd) if err != nil { return err } req.Header.Set("x-api-key", c.key) req.Header.Set("Accept", "application/json") req.Header.Set("Cache-Control", "no-cache") if raw != nil { req.Header.Set("Content-Type", "application/json") } resp, err := c.http.Do(req) if err != nil { if ctx.Err() != nil { return ctx.Err() } lastErr = ErrUnavailable if serr := c.sleep(ctx, backoff(attempt, "")); serr != nil { return serr } continue } data, _ := io.ReadAll(io.LimitReader(resp.Body, 8<<20)) _ = resp.Body.Close() switch { case resp.StatusCode >= 200 && resp.StatusCode < 300: if out == nil { return nil } if err := json.Unmarshal(data, out); err != nil { return fmt.Errorf("apollo: decode %s: %w", path, err) } return nil case resp.StatusCode == http.StatusUnauthorized: return ErrKey case resp.StatusCode == http.StatusForbidden: return ErrForbidden case resp.StatusCode == http.StatusTooManyRequests: lastErr = ErrRateLimited case resp.StatusCode >= 500: lastErr = ErrUnavailable default: return &APIError{Status: resp.StatusCode, Message: apiMessage(data)} } if serr := c.sleep(ctx, backoff(attempt, resp.Header.Get("Retry-After"))); serr != nil { return serr } } return lastErr } // backoff honours a Retry-After of up to a minute, else grows 1s, 2s, 4s. func backoff(attempt int, retryAfter string) time.Duration { if s, err := strconv.Atoi(strings.TrimSpace(retryAfter)); err == nil && s > 0 && s <= 60 { return time.Duration(s) * time.Second } return time.Duration(1< SearchPageSize { perPage = SearchPageSize } body := map[string]any{ "page": page, "per_page": perPage, "sort_by_field": "contact_created_at", "sort_ascending": true, } if listID != "" { body["contact_label_ids"] = []string{listID} } var out struct { Contacts []Person `json:"contacts"` Pagination struct { TotalEntries int `json:"total_entries"` TotalPages int `json:"total_pages"` } `json:"pagination"` } if err := c.do(ctx, http.MethodPost, "/contacts/search", body, &out); err != nil { return nil, 0, 0, err } return out.Contacts, out.Pagination.TotalEntries, out.Pagination.TotalPages, nil } // MatchBatchSize is the most people one bulk match takes. const MatchBatchSize = 10 // MatchDetail identifies one person to enrich. type MatchDetail struct { Email string `json:"email,omitempty"` FirstName string `json:"first_name,omitempty"` LastName string `json:"last_name,omitempty"` OrganizationName string `json:"organization_name,omitempty"` Domain string `json:"domain,omitempty"` LinkedinURL string `json:"linkedin_url,omitempty"` } // MatchResult is a bulk match's answer: one entry per detail, nil where // Apollo found nobody. type MatchResult struct { Matches []*Person CreditsConsumed int } // BulkMatch enriches up to MatchBatchSize people. Personal emails and phone // numbers are never revealed: they cost extra credits and phones need a webhook. func (c *Client) BulkMatch(ctx context.Context, details []MatchDetail) (*MatchResult, error) { if len(details) == 0 { return &MatchResult{}, nil } if len(details) > MatchBatchSize { return nil, fmt.Errorf("apollo: at most %d people per match", MatchBatchSize) } body := map[string]any{ "details": details, "reveal_personal_emails": false, "reveal_phone_number": false, } var out struct { Matches []*Person `json:"matches"` CreditsConsumed int `json:"credits_consumed"` } if err := c.do(ctx, http.MethodPost, "/people/bulk_match", body, &out); err != nil { return nil, err } res := &MatchResult{Matches: make([]*Person, len(details)), CreditsConsumed: out.CreditsConsumed} if len(out.Matches) == len(details) { copy(res.Matches, out.Matches) return res, nil } // Apollo left the unmatched out: line the rest up by address. byEmail := map[string]*Person{} for _, m := range out.Matches { if m != nil && m.Email != "" { byEmail[strings.ToLower(strings.TrimSpace(m.Email))] = m } } for i, d := range details { if d.Email != "" { res.Matches[i] = byEmail[strings.ToLower(strings.TrimSpace(d.Email))] } } return res, nil } func truncate(s string, n int) string { r := []rune(s) if len(r) <= n { return s } return string(r[:n]) }