Skip to content
Merged
Show file tree
Hide file tree
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
39 changes: 35 additions & 4 deletions scraper-go/internal/adapters/adzuna/adapter.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import (

"github.com/Benevanio/Jobs_Scraper_Global/scraper-go/internal/adapters/adapterutil"
"github.com/Benevanio/Jobs_Scraper_Global/scraper-go/internal/domain"
"github.com/Benevanio/Jobs_Scraper_Global/scraper-go/internal/metrics"
"github.com/Benevanio/Jobs_Scraper_Global/scraper-go/internal/ports"
)

Expand Down Expand Up @@ -120,9 +121,17 @@ func (a *AdzunaAdapter) Search(ctx context.Context, keyword string, req domain.S

func (a *AdzunaAdapter) SearchBatch(ctx context.Context, keywords []string, req domain.ScrapeRequest) ([]domain.Job, error) {
if req.FullKeywordCoverage {
ctx = observeBatch(ctx, req.RunID, fullCoverageCount(keywords), a.appID, a.appKey)
return adapterutil.SearchAllKeywords(ctx, keywords, req, ports.ProviderAdzuna, a.searchKeyword)
}
slot := a.nextKeywordSlot(keywords, adzunaKeywordSlotSize())
selected := 0
for _, k := range slot {
if strings.TrimSpace(k) != "" {
selected++
}
}
ctx = observeBatch(ctx, req.RunID, selected, a.appID, a.appKey)
if len(slot) == 0 {
return nil, nil
}
Expand Down Expand Up @@ -183,12 +192,17 @@ func (a *AdzunaAdapter) nextKeywordSlot(keywords []string, slotSize int) []strin
return slot
}

func (a *AdzunaAdapter) searchKeyword(ctx context.Context, keyword string, req domain.ScrapeRequest) ([]domain.Job, error) {
func (a *AdzunaAdapter) searchKeyword(ctx context.Context, keyword string, req domain.ScrapeRequest) (output []domain.Job, resultErr error) {
keyword = strings.TrimSpace(keyword)
if keyword == "" {
return nil, nil
}

keywordStarted := time.Now()
observe(ctx, metrics.AdzunaProgressEvent{Kind: "keyword_started", Keyword: keyword}, 0, nil)
defer func() {
observe(ctx, metrics.AdzunaProgressEvent{Kind: "keyword_finished", Keyword: keyword, Received: len(output)}, time.Since(keywordStarted), resultErr)
}()
maxPages := req.MaxPagesPerKeyword
if maxPages <= 0 {
maxPages = defaultAdzunaMaxPages
Expand All @@ -212,7 +226,11 @@ func (a *AdzunaAdapter) searchKeyword(ctx context.Context, keyword string, req d
endpoint := a.buildURL(keyword, req, page)

pageCtx, cancel := context.WithTimeout(ctx, pageTimeout)
pageCtx = context.WithValue(pageCtx, pageProgressKey{}, pageProgress{page: page})
pageStarted := time.Now()
observe(pageCtx, metrics.AdzunaProgressEvent{Kind: "page_started", Keyword: keyword, Page: page}, 0, nil)
jobs, err := a.fetchPageWithRetry(pageCtx, endpoint, keyword, req.FullKeywordCoverage)
observe(pageCtx, metrics.AdzunaProgressEvent{Kind: "page_finished", Keyword: keyword, Page: page, Received: len(jobs)}, time.Since(pageStarted), err)
cancel()

if err != nil {
Expand Down Expand Up @@ -249,7 +267,13 @@ func (a *AdzunaAdapter) fetchPageWithRetry(ctx context.Context, endpoint, keywor
var lastErr error

for attempt := 0; attempt < 3; attempt++ {
jobs, err := a.fetchPage(ctx, endpoint, keyword)
page, _ := ctx.Value(pageProgressKey{}).(pageProgress)
page.attempt = attempt + 1
attemptCtx := context.WithValue(ctx, pageProgressKey{}, page)
if attempt > 0 {
observe(attemptCtx, metrics.AdzunaProgressEvent{Kind: "retry", Keyword: keyword, Page: page.page}, 0, nil)
}
jobs, err := a.fetchPage(attemptCtx, endpoint, keyword)
if err == nil {
return jobs, nil
}
Expand All @@ -265,6 +289,7 @@ func (a *AdzunaAdapter) fetchPageWithRetry(ctx context.Context, endpoint, keywor
return nil, err
}

observe(attemptCtx, metrics.AdzunaProgressEvent{Kind: "backoff", Keyword: keyword, Page: page.page}, time.Duration(attempt+1)*1500*time.Millisecond, err)
if err := adapterutil.Wait(ctx, time.Duration(attempt+1)*1500*time.Millisecond); err != nil {
return nil, err
}
Expand Down Expand Up @@ -307,18 +332,24 @@ type adzunaResponse struct {
} `json:"results"`
}

func (a *AdzunaAdapter) fetchPage(ctx context.Context, endpoint, keyword string) ([]domain.Job, error) {
func (a *AdzunaAdapter) fetchPage(ctx context.Context, endpoint, keyword string) (jobs []domain.Job, resultErr error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
if err != nil {
return nil, err
}
req.Header.Set("Accept", "application/json")

httpStarted := time.Now()
status := 0
defer func() {
observe(ctx, metrics.AdzunaProgressEvent{Kind: "http_finished", Keyword: keyword, HTTPStatus: status, Received: len(jobs)}, time.Since(httpStarted), resultErr)
}()
resp, err := a.client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
status = resp.StatusCode

if resp.StatusCode != http.StatusOK {
var at time.Time
Expand All @@ -341,7 +372,7 @@ func (a *AdzunaAdapter) fetchPage(ctx context.Context, endpoint, keyword string)
return []domain.Job{}, nil
}

jobs := make([]domain.Job, 0, len(data.Results))
jobs = make([]domain.Job, 0, len(data.Results))
for _, r := range data.Results {
// Espelha o salario do JS: "min-max" ou vazio.
salario := ""
Expand Down
91 changes: 91 additions & 0 deletions scraper-go/internal/adapters/adzuna/progress.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
package adzuna

import (
"context"
"errors"
"log/slog"
"net"
"net/url"
"strings"
"time"

"github.com/Benevanio/Jobs_Scraper_Global/scraper-go/internal/metrics"
)

type progressKey struct{}
type batchProgress struct {
runID string
generation uint64
selected, position int
started time.Time
keywordHadError bool
secrets []string
}

func observeBatch(ctx context.Context, runID string, selected int, secrets ...string) context.Context {
return context.WithValue(ctx, progressKey{}, &batchProgress{runID: runID, generation: metrics.BeginAdzunaProgress(runID, selected), selected: selected, started: time.Now(), secrets: secrets})
}
func fullCoverageCount(keywords []string) int {
seen := map[string]bool{}
for _, k := range keywords {
if k = strings.TrimSpace(k); k != "" {
seen[k] = true
}
}
return len(seen)
}
func observe(ctx context.Context, e metrics.AdzunaProgressEvent, duration time.Duration, err error) {
p, ok := ctx.Value(progressKey{}).(*batchProgress)
if !ok {
return
}
if e.Kind == "keyword_started" {
p.position++
p.keywordHadError = false
}
if e.Kind == "http_finished" && err != nil {
p.keywordHadError = true
}
if e.Kind == "keyword_finished" {
e.Failed = err != nil
e.HadError = p.keywordHadError || err != nil
}
var networkError net.Error
e.Timeout = errors.Is(err, context.DeadlineExceeded) || (errors.As(err, &networkError) && networkError.Timeout())
metrics.ObserveAdzunaProgress(p.runID, p.generation, e)
page, _ := ctx.Value(pageProgressKey{}).(pageProgress)
if e.Page == 0 {
e.Page = page.page
}
progress := 0.0
finished := p.position
if e.Kind != "keyword_finished" {
finished--
}
if p.selected > 0 {
progress = 100 * float64(max(0, finished)) / float64(p.selected)
}
attrs := []any{"run_id", p.runID, "provider", "adzuna", "event", e.Kind, "keyword", e.Keyword, "keyword_position", p.position, "keywords_selected", p.selected, "page", e.Page, "offset", e.Offset, "received", e.Received, "http_status", e.HTTPStatus, "duration_seconds", duration.Seconds(), "elapsed_seconds", time.Since(p.started).Seconds(), "last_activity", time.Now().UTC(), "attempt", page.attempt, "progress_percent", progress}
if e.Kind == "keyword_finished" {
attrs = append(attrs, "status", metrics.Status(err), "had_error", e.HadError)
}
if err != nil {
attrs = append(attrs, "error", safeProgressError(err, p.secrets), "error_type", metrics.ErrorType(err))
}
slog.Info("adzuna collection progress", attrs...)
}

// Page and attempt metadata are observational only; they never control pagination.
type pageProgressKey struct{}
type pageProgress struct{ page, attempt int }

func safeProgressError(err error, secrets []string) string {
message := err.Error()
for _, secret := range secrets {
if secret != "" {
message = strings.ReplaceAll(message, url.QueryEscape(secret), "[redacted]")
message = strings.ReplaceAll(message, secret, "[redacted]")
}
}
return message
}
Loading
Loading