Skip to content
2 changes: 1 addition & 1 deletion backend/src/modules/admin/scrapers/scrapers.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ export const ScraperStatusSchema = z.object({
lastRun: z.object({
runId: z.string(),
providers: z.array(z.string()).nullable().optional(),
status: z.enum(["success", "partial", "failed", "timeout", "canceled"]),
status: z.enum(["success", "partial", "partial_success", "failed", "timeout", "canceled"]),
finishedAt: z.string().datetime(),
jobsSaved: z.number().int().nonnegative(),
jobsIndexed: z.number().int().nonnegative(),
Expand Down
33 changes: 33 additions & 0 deletions backend/tests/unit/modules/admin/scraperResult.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,36 @@ it("retains partial execution counts and accepts an empty initial history", () =
expect(result.lastRun?.status).toBe("partial");
expect(result.lastRun?.jobsIndexed).toBe(210);
});

it.each(["success", "partial", "partial_success", "failed", "timeout", "canceled"] as const)(
"preserva o status %s e os contadores retornados pelo Go",
(status) => {
const payload = {
running: false,
lastRun: {
runId: "fixture-operational-result",
providers: ["greenhouse"],
status,
finishedAt: "2026-11-12T20:00:00Z",
jobsSaved: 210,
jobsIndexed: 209,
errorType: status === "partial" ? "timeout" : "",
},
};
expect(ScraperStatusSchema.parse(payload)).toEqual(payload);
},
);

it("continua rejeitando status desconhecido no resultado da coleta", () => {
expect(ScraperStatusSchema.safeParse({
running: false,
lastRun: {
runId: "fixture-invalid-result",
status: "unknown",
finishedAt: "2026-11-12T20:00:00Z",
jobsSaved: 0,
jobsIndexed: 0,
errorType: "",
},
}).success).toBe(false);
});
36 changes: 36 additions & 0 deletions backend/tests/unit/modules/admin/scrapers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,42 @@ describe("scraperClient", () => {
vi.restoreAllMocks();
});

it.each(["partial", "partial_success"] as const)(
"preserva %s na resposta Go e permite listar o scraper",
async (status) => {
const payload = {
name: "go-scraper",
running: false,
lastRunAt: "2026-11-12T20:00:00Z",
jobsCollected: 210,
lastRun: {
runId: "fixture-partial-run",
providers: ["greenhouse"],
status,
finishedAt: "2026-11-12T20:00:00Z",
jobsSaved: 210,
jobsIndexed: 209,
errorType: "",
},
};
vi.stubGlobal("fetch", vi.fn().mockImplementation(async (input: string | URL | Request) => ({
ok: true,
status: 200,
json: async () => String(input).includes("/admin/jobs/count") ? { total: 210 } : payload,
})));

await expect(scraperClient.getStatus()).resolves.toEqual(payload);
await expect(new ScrapersService().listScrapers()).resolves.toEqual([{
name: "go-scraper",
status: "idle",
running: false,
lastRunAt: payload.lastRunAt,
jobsCollected: 210,
}]);
},
);


it("calls trigger endpoint and returns json", async () => {
vi.stubGlobal(
"fetch",
Expand Down
17 changes: 17 additions & 0 deletions docs/scraper-greenhouse-cinco-janelas.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Greenhouse em cinco janelas

Manifesto greenhouse-v2: 3339 boards preservados do v1, sem remoções ou duplicações. A redistribuição preserva a ordem anterior e divide a sequência em 668/668/668/668/667.

| Grupo | America/Sao_Paulo | Adapters |
|---|---|---:|
| greenhouse-1 | 00h–01h | 668 |
| greenhouse-2 | 06h–07h | 668 |
| greenhouse-3 | 11h–12h | 668 |
| greenhouse-4 | 17h–18h | 668 |
| greenhouse-5 | 21h–22h | 667 |

As outras 17 janelas permanecem intactas, incluindo Jooble 20h–21h. 22h–00h permanece livre. O preset usa grupos fixos; chamadas manuais e configuração customizada mantêm o seletor anterior.

SCRAPER_GREENHOUSE_WINDOW_MAX_ADAPTERS tem padrão 680 e é independente do tamanho efetivo dos grupos. Um limite menor que algum grupo impede a execução, sem truncamento.

Migração: o hash canônico é fixado sob uma chave versionada greenhouse-v2 com fencing pelo lock global. O pin imutável v1 permanece preservado. Claims de ocorrência diários mantêm as mesmas chaves e TTL de 48h: uma ocorrência já consumida não é reexecutada com a nova versão. Não se reaproveita o checkpoint rotativo manual nos grupos fixos. Em uma troca no meio do dia, a cobertura integral da nova distribuição começa no dia seguinte; não se força replay das janelas anteriores. Nenhuma chave/dado existente é apagado.
18 changes: 18 additions & 0 deletions docs/scraper-resultado-operacional.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Resultado operacional da coleta

`collection: N task(s) failed` era produzido em `pipeline.ScrapeAllSources`, depois de drenar os jobs, e propagado pelo cronjob como falha terminal. A política agora retorna `partial_success` sem erro terminal quando pelo menos `SCRAPER_MIN_SUCCESS_PERCENT` (padrão 50, intervalo 1–100) dos adapters selecionados concluíram todas as suas tarefas sem erro. O denominador inclui os não despachados. Tarefa com jobs e erro continua falhando, mas seus jobs são processados.

Erros de processamento, cancelamento, lock e deadline do ciclo continuam fatais. Timeout local do adapter é falha individual; não implica deadline do ciclo. O relatório final contém resultado técnico da coleta e resultado operacional, e é emitido depois da tentativa de liberar o lock, inclusive em falhas anteriores à coleta. `LastRun.Status` usa success/partial_success/failed; o motivo original permanece no relatório. As métricas legadas mantêm seu contrato técnico.

Contadores têm unidades distintas:

- Adapters: sucesso exige conclusão de todas as tarefas, sem qualquer erro. Falhas, timeouts e cancelamentos são categorias exclusivas, nessa prioridade: cancelamento, timeout, outros erros. Uma falha pode gerar vários diagnósticos por tarefa.
- `tasksCanceled` legado inclui tarefas com timeout. Por isso 2 timeouts podem produzir tasksCanceled=2 e cancelled=0 no resumo do provider. O relatório separa TaskTimeouts e TaskCancellations.
- `Saved()`/PersistedOperations = Inserted + Updated: operações de upsert, inclusive merges tardios de duplicatas já gravadas. PersistedDocuments conta os documentos aprovados distintos retornados pelo processamento.
- Indexed conta entradas concluídas, inclusive skips idempotentes. O buffer pode consolidar várias gravações do mesmo documento. Portanto saved=5720 e indexed=5719 não demonstram perda de índice por si só. Sem o log original não se atribui uma causa específica ao benchmark.
- IndexPending conta o buffer ainda aguardando indexação; IndexUnconfirmedInputs conta entradas de chamadas que falharam, descontando reconciliações confirmadas. Não se calcula pendência por saved-indexed. PersistencePending conta itens ainda no buffer de classificação/persistência; falhas de batches são informadas separadamente. Esses buffers não representam uma auditoria do backlog durável global.
- Received mede entradas consumidas pelo processamento antes de falha terminal; Collected mede jobs entregues pelos adapters ao coordenador, inclusive depois de uma falha de processamento.

Diagnóstico preserva o texto original, board estável, timeout, DNS e conexão tipados; códigos HTTP só são classificados com evidência explícita. Unknown continua unknown.

Validação rápida: fixtures determinísticas em pipeline e cronjob, sem chamadas à API; os testes existentes de recuperação cobrem falhas de persistência/indexação, deadline e drain.
1 change: 1 addition & 0 deletions scraper-go/cmd/server/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@ func searchConfigFromRuntime(
WaitBetweenSearchesMs: req.WaitBetweenSearchesMs,
PageTimeoutMs: req.PageTimeoutMs,
MaxConcurrency: config.ResolveEffectiveConcurrency(req.MaxConcurrency, runtimeCfg.MaxConcurrency),
MinSuccessPercent: runtimeCfg.MinSuccessPercent,
ProviderMaxConcurrency: min(runtimeCfg.ProviderMaxConcurrency, config.ResolveEffectiveConcurrency(req.MaxConcurrency, runtimeCfg.MaxConcurrency)),
ProviderConcurrencyOverrides: runtimeCfg.ProviderConcurrencyOverrides,
ClassificationBatchSize: runtimeCfg.ClassificationBatchSize,
Expand Down
2 changes: 2 additions & 0 deletions scraper-go/cmd/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,8 @@ func run(adapterList []ports.JobSource, runtimeCfg config.RuntimeConfig) {

schedulerCfg.ScrapeTimeout = runtimeCfg.ScrapeTimeout
schedulerCfg.ProviderWindows = runtimeCfg.ProviderWindows
schedulerCfg.MinSuccessPercent = runtimeCfg.MinSuccessPercent
schedulerCfg.GreenhouseWindowMaxAdapters = runtimeCfg.GreenhouseWindowMaxAdapters
schedulerCfg.GreenhouseBatchSize = runtimeCfg.GreenhouseBatchSize

schedulerCfg.MaxConcurrency = runtimeCfg.MaxConcurrency
Expand Down
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