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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ hire
/capture-apply-form
/catalog-coverage
/classify-mail
/changes-webhook
/close-chronic-boards
/cv-previews
/discord-sync
Expand Down
44 changes: 44 additions & 0 deletions cmd/changes-webhook/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
// Command changes-webhook pushes the job change feed to the API customers who subscribed to
// it (POST /api/v1/webhooks/changes): signed, batched POSTs from each subscription's stored
// position in job_changes. One run claims every due subscription, delivers it until it has
// caught up with the feed (bounded per run) and exits; run it every minute.
//
// A customer endpoint failing is normal and does not fail the run: the worker records it on
// the subscription, retries by backoff and eventually disables it. The process exits non-zero
// only on an infrastructure error (database unreachable, a claim query failing).
//
// Needs only DATABASE_URL.
package main

import (
"context"
"log"

"github.com/strelov1/freehire/internal/engage/changehook"
"github.com/strelov1/freehire/internal/platform/db"
"github.com/strelov1/freehire/internal/platform/worker"
)

func main() {
worker.Main(run)
}

func run() int {
ctx, _, pool, cleanup, err := worker.Bootstrap(context.Background())
if err != nil {
log.Printf("database: %v", err)
return 1
}
defer cleanup()

stats, err := changehook.NewWorker(db.New(pool), changehook.NewSender()).Run(ctx)
if err != nil {
log.Printf("changes-webhook: %v", err)
return 1
}
if stats.Subscriptions > 0 {
log.Printf("changes-webhook: %d subscription(s), %d change(s) delivered, %d failed, %d disabled",
stats.Subscriptions, stats.Changes, stats.Failed, stats.Disabled)
}
return 0
}
2 changes: 1 addition & 1 deletion docs/agents/workers.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ Each worker's entry lives in one of these files, grouped by what it works on. A
- [Enrichment and search](workers/search.md): `enrich`, `search-drain`, `reindex`, `facetd`, `build-suggestions`, `search-settings-drift`, `serve-probe`, `search-ping`
- [Backfills and company data](workers/companies.md): `backfill-derive`, `backfill-company-type-hint`, `backfill-telegram-prefilter`, `backfill-company-info-wikipedia`, `backfill-catalog-history`, `publish-logo-domains`, `report-company-website-twins`, `merge-companies`
- [Operations and quality](workers/ops.md): `migrate`, `llm-probe`, `queue-metrics`, `quality-audit`, `catalog-coverage`, `report-cv-letters`, `report-skill-gaps`, `report-classify-drift`
- [Users, billing and mail](workers/engage.md): `billing-sync`, `discord-sync`, `pro-welcome-mail`, `cv-lifecycle-mail`, `mentorship-remind`, `message-notify`, `mentor-busy-sync`, `email-events`, `social-digest`, `linkedin-auth`, `linkedin-token-refresh`, `sweep-tracer-clicks`
- [Users, billing and mail](workers/engage.md): `billing-sync`, `discord-sync`, `pro-welcome-mail`, `cv-lifecycle-mail`, `mentorship-remind`, `message-notify`, `mentor-busy-sync`, `email-events`, `social-digest`, `linkedin-auth`, `linkedin-token-refresh`, `sweep-tracer-clicks`, `changes-webhook`

## Locking

Expand Down
1 change: 1 addition & 0 deletions docs/agents/workers/engage.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,4 @@ Part of the [worker index](../workers.md): what each `cmd/<name>` worker does, w
- `linkedin-auth` — **run by hand**, roughly once every sixty days: grants, records and inspects the credential the digest posts to LinkedIn with. `-url` prints the address to open in a browser, `-code <value>` exchanges what that browser handed back, `-token <value>` stores one minted in the Developer Portal's own token generator instead, `-status` reports what is stored and when it dies (never the token itself). Not a route on purpose — a sign-in flow for an audience of one, whose authorization would then be whatever that route's turned out to be; a command needs SSH, which is authorization we already have. **The exchange is also the only way to learn whether LinkedIn issued a refresh token**, which decides whether the credential renews itself or needs a person; it logs the answer explicitly. Needs `DATABASE_URL` and the four `LINKEDIN_*` values.
- `linkedin-token-refresh` — daily: renews that credential a fortnight before expiry when LinkedIn permits it, and warns when it does not. Both paths ship because programmatic refresh tokens go to approved Marketing Developer Platform partners only and the Community Management API is not that program — so a null refresh token is the EXPECTED case, not an error. **A warning is a published gauge, not a red unit**: this fleet already runs ~37 permanently failing ingest units, so a non-zero exit repeated daily for two weeks trains an operator to ignore it. `freehire_social_token_expires_in_seconds`, `freehire_social_token_grant_expires_in_seconds` and `freehire_social_token_renewable` go to the node_exporter textfile collector when `PROM_TEXTFILE_DIR` is set (negative seconds mean "no credential stored", which must not look like a broken exporter). A non-zero exit is reserved for a credential that is ALREADY dead. Needs `DATABASE_URL` and the four `LINKEDIN_*` values; without them it is a no-op that never opens the pool. See [internal/engage/linkedinauth/AGENTS.md](../../../internal/engage/linkedinauth/AGENTS.md).
- `sweep-tracer-clicks` — daily: deletes CV tracer-link clicks (`cv_link_clicks`) older than `TRACER_CLICK_RETENTION_DAYS` (default 180, read through the strict worker reader). The privacy policy promises those records are gone after 180 days, so it **deletes by default** — there is no dry run, because a retention promise that only reports keeps nothing. The tracer tokens stay: an old PDF must keep redirecting. Idempotent, so a missed or repeated run costs nothing. Needs only `DATABASE_URL`.
- `changes-webhook` — every minute: delivers the job change feed (`job_changes`) to API customers' webhook subscriptions (`change_webhooks`, managed at `/me/change-webhooks`; `internal/engage/changehook`). Each subscription is read from its stored `(cursor_xid, cursor_id)` through the feed query (`ListJobChangesForWebhook`, the public feed's plus company_slug), filtered by company and kind, and POSTed as a signed batch of up to 100 changes; the cursor moves only after a 2xx, so delivery is at-least-once and clients dedupe on `seq`. Failures back off 30 s doubling to 1 h; 25 in a row, or one `410`, disable the subscription. It claims with a 5-minute lease (`next_attempt_at`) so overlapping runs do not double-send, and skips accounts without a live `api`/`api_data` plan. A failing customer endpoint is recorded on its subscription and never fails the unit; it exits 1 only on an infrastructure error (database unreachable, claim query failing). Runs on `core` (136.243.174.114), like the other non-crawl workers. Needs only `DATABASE_URL`. A separate run-once worker rather than a pass of an existing one because nothing else here polls the feed, a slow customer endpoint must not hold up the saved-search digests or ingest, and the timer cadence is the delivery latency.
2 changes: 1 addition & 1 deletion internal/engage/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,4 @@ reports the whole graph at once, including imports that exist only in test files

## Packages

`broadcast` `buddy` `community` `companyfeedback` `companywatch` `cvlifecycle` `discordlink` `emailevents` `emailnotify` `emailprefs` `limitnudge` `maildaily` `mailpreview` `mentorship` `messaging` `notify` `nudge` `onboarding` `problemreport` `prowelcome` `pushnotify` `referral` `reminder` `report` `slots` `socialdigest` `subscription` `telegramnotify` `vote` `webhooknotify`
`broadcast` `buddy` `changehook` `community` `companyfeedback` `companywatch` `cvlifecycle` `discordlink` `emailevents` `emailnotify` `emailprefs` `limitnudge` `maildaily` `mailpreview` `mentorship` `messaging` `notify` `nudge` `onboarding` `problemreport` `prowelcome` `pushnotify` `referral` `reminder` `report` `slots` `socialdigest` `subscription` `telegramnotify` `vote` `webhooknotify`
84 changes: 84 additions & 0 deletions internal/engage/changehook/batch.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
package changehook

import (
"fmt"
"time"

"github.com/strelov1/freehire/internal/platform/db"
)

// pageSize is how many feed rows one delivery step reads, and so the most changes one POST
// carries.
const pageSize = 100

// Event types, in the X-Freehire-Event header and the body's `type`.
const (
EventChanges = "job.changes"
EventTest = "webhook.test"
)

// Change is one transition in a delivery: the feed's JobChange plus the company it belongs
// to. Apply it only when Seq is greater than the last Seq you applied for that PublicSlug.
type Change struct {
PublicSlug string `json:"public_slug"`
CompanySlug string `json:"company_slug"`
Seq int64 `json:"seq"`
Kind string `json:"kind"`
At time.Time `json:"at"`
ClosedReason string `json:"closed_reason,omitempty"`
}

// Event is the JSON body of one delivery. ID is the same for a retry of the same batch.
type Event struct {
ID string `json:"id"`
Type string `json:"type"`
Changes []Change `json:"changes"`
}

// Filter is what a subscription wants: the kinds (never empty) and, when CompanySlugs is
// not empty, only these companies.
type Filter struct {
CompanySlugs []string
Kinds []string
}

func (f Filter) match(r db.ListJobChangesForWebhookRow) bool {
return contains(f.Kinds, r.Kind) && (len(f.CompanySlugs) == 0 || contains(f.CompanySlugs, r.CompanySlug))
}

func contains(set []string, s string) bool {
for _, v := range set {
if v == s {
return true
}
}
return false
}

// Batch is the changes of one feed page the subscription wants, in feed order. Rows it does
// not want still move its position, which is the caller's business.
func (f Filter) Batch(rows []db.ListJobChangesForWebhookRow) []Change {
var out []Change
for _, r := range rows {
if f.match(r) {
out = append(out, Change{PublicSlug: r.PublicSlug, CompanySlug: r.CompanySlug, Seq: r.ID,
Kind: r.Kind, At: r.At.Time.UTC(), ClosedReason: r.Reason})
}
}
return out
}

// deliveryID names a batch by its subscription and the feed position it ends at, so a retry
// of the same batch carries the same id.
func deliveryID(sub int64, last db.ListJobChangesForWebhookRow) string {
return fmt.Sprintf("%d-%d-%d", sub, last.Xid, last.ID)
}

// backoff is the wait after the nth consecutive failure (0-based): 30 s doubling to 1 h.
func backoff(failures int64) time.Duration {
const base, ceiling = 30 * time.Second, time.Hour
if failures >= 7 { // 30s * 2^7 is past the ceiling
return ceiling
}
return min(base<<failures, ceiling)
}
85 changes: 85 additions & 0 deletions internal/engage/changehook/changehook_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
package changehook

import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"testing"
"time"

"github.com/jackc/pgx/v5/pgtype"

"github.com/strelov1/freehire/internal/platform/db"
)

func TestSignAndVerify(t *testing.T) {
body := []byte(`{"id":"1-2-3","type":"job.changes","changes":[]}`)
now := time.Unix(1_800_000_000, 0)
sig := Sign("whsec_x", now.Unix(), body)

// The documented construction, written out: HMAC-SHA256(secret, "<ts>.<body>"), hex, "v1=".
mac := hmac.New(sha256.New, []byte("whsec_x"))
mac.Write([]byte("1800000000." + string(body)))
if want := "v1=" + hex.EncodeToString(mac.Sum(nil)); sig != want {
t.Fatalf("Sign = %q, want %q", sig, want)
}
ts := "1800000000"
for _, tc := range []struct {
name, secret, ts, sig string
body []byte
now time.Time
want error
}{
{"valid", "whsec_x", ts, sig, body, now, nil},
{"within tolerance", "whsec_x", ts, sig, body, now.Add(4 * time.Minute), nil},
{"wrong secret", "whsec_y", ts, sig, body, now, ErrBadSignature},
{"body changed", "whsec_x", ts, sig, append(body[:len(body)-1:len(body)-1], ' ', '}'), now, ErrBadSignature},
{"timestamp changed", "whsec_x", "1800000001", sig, body, now, ErrBadSignature},
{"replayed later", "whsec_x", ts, sig, body, now.Add(6 * time.Minute), ErrStale},
{"garbage timestamp", "whsec_x", "soon", sig, body, now, ErrBadSignature},
} {
if got := Verify(tc.secret, tc.ts, tc.sig, tc.body, tc.now, DefaultTolerance); got != tc.want {
t.Errorf("%s: Verify = %v, want %v", tc.name, got, tc.want)
}
}
}

var kinds3 = []string{"opened", "closed", "reopened"}

func row(id int64, kind, company string) db.ListJobChangesForWebhookRow {
return db.ListJobChangesForWebhookRow{ID: id, Xid: 10, Kind: kind, CompanySlug: company, PublicSlug: "job-" + company,
At: pgtype.Timestamptz{Time: time.Unix(1_800_000_000, 0), Valid: true}}
}

func TestBatchFiltersByCompanyAndKindKeepingOrder(t *testing.T) {
rows := []db.ListJobChangesForWebhookRow{row(1, "opened", "acme"), row(2, "closed", "other"), row(3, "closed", "acme"), row(4, "reopened", "acme")}

all := Filter{Kinds: kinds3}.Batch(rows)
if len(all) != 4 {
t.Fatalf("no company filter: %d changes, want 4", len(all))
}
got := Filter{CompanySlugs: []string{"acme"}, Kinds: []string{"opened", "closed"}}.Batch(rows)
if len(got) != 2 || got[0].Seq != 1 || got[1].Seq != 3 {
t.Fatalf("filtered = %+v, want seq 1 then 3", got)
}
if got[1].ClosedReason != "" || got[1].CompanySlug != "acme" {
t.Fatalf("change = %+v", got[1])
}
if n := len(Filter{CompanySlugs: []string{"nobody"}, Kinds: kinds3}.Batch(rows)); n != 0 {
t.Fatalf("unmatched company delivered %d changes", n)
}
}

func TestBackoffDoublesToTheCeiling(t *testing.T) {
for n, want := range map[int64]time.Duration{0: 30 * time.Second, 1: time.Minute, 2: 2 * time.Minute, 6: 32 * time.Minute, 7: time.Hour, 24: time.Hour} {
if got := backoff(n); got != want {
t.Errorf("backoff(%d) = %v, want %v", n, got, want)
}
}
}

func TestDeliveryIDIsStableForABatch(t *testing.T) {
if a, b := deliveryID(7, row(9, "closed", "x")), deliveryID(7, row(9, "closed", "x")); a != b || a != "7-10-9" {
t.Fatalf("ids %q %q", a, b)
}
}
66 changes: 66 additions & 0 deletions internal/engage/changehook/send.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package changehook

import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"strconv"
"time"

"github.com/strelov1/freehire/internal/platform/safehttp"
)

// requestTimeout bounds one delivery attempt: a slow endpoint must not hold the run.
const requestTimeout = 10 * time.Second

// ErrGone is a 410 from the endpoint: the one answer that says "stop", so the subscription
// is disabled at once instead of being retried.
var ErrGone = errors.New("changehook: endpoint responded 410 Gone")

// Sender POSTs signed events through an SSRF-guarded client.
type Sender struct{ http *http.Client }

// NewSender is the production sender: safehttp refuses private and loopback addresses, and
// redirects are not followed (a redirect is a failed delivery, so a signed body never leaves
// for a URL the owner did not register).
func NewSender() *Sender { return newSender(safehttp.NewClient(requestTimeout)) }

// newSender takes any client; tests use it to reach a loopback server.
func newSender(c *http.Client) *Sender {
c.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
return &Sender{http: c}
}

// Send signs and POSTs ev. A 2xx is success, 410 is ErrGone, anything else an error to retry.
func (s *Sender) Send(ctx context.Context, dest, secret string, ev Event) error {
body, err := json.Marshal(ev)
if err != nil {
return fmt.Errorf("changehook: encode event: %w", err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, dest, bytes.NewReader(body))
if err != nil {
return fmt.Errorf("changehook: build request: %w", err)
}
ts := time.Now().Unix()
req.Header.Set("Content-Type", "application/json")
req.Header.Set(HeaderTimestamp, strconv.FormatInt(ts, 10))
req.Header.Set(HeaderSignature, Sign(secret, ts, body))
req.Header.Set(HeaderDelivery, ev.ID)
req.Header.Set(HeaderEvent, ev.Type)

resp, err := s.http.Do(req)
if err != nil {
return fmt.Errorf("changehook: %w", err)
}
defer resp.Body.Close()
switch {
case resp.StatusCode == http.StatusGone:
return ErrGone
case resp.StatusCode < 200 || resp.StatusCode >= 300:
return fmt.Errorf("changehook: endpoint responded %d", resp.StatusCode)
}
return nil
}
64 changes: 64 additions & 0 deletions internal/engage/changehook/sign.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
// Package changehook pushes the job change feed (job_changes, GET /api/v1/jobs/changes) to
// the HTTPS endpoints of API customers: signed, batched, at-least-once deliveries driven by a
// persisted per-subscription position in the feed. The subscription rows are change_webhooks
// (migration 0264); cmd/changes-webhook runs the delivery loop.
//
// It is separate from webhooknotify and notify, which deliver saved-search digests to one
// unsigned URL per account on that engine's own retry rules.
package changehook

import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"errors"
"strconv"
"strings"
"time"
)

// The headers of every delivery. The signature covers the timestamp and the exact body.
const (
HeaderSignature = "X-Freehire-Signature"
HeaderTimestamp = "X-Freehire-Timestamp"
HeaderDelivery = "X-Freehire-Delivery"
HeaderEvent = "X-Freehire-Event"

signatureVersion = "v1="
)

// DefaultTolerance is how far a delivery's timestamp may be from the receiver's clock before
// Verify refuses it, so a captured request cannot be replayed later.
const DefaultTolerance = 5 * time.Minute

// Sign is the signature header value for a body sent at ts (unix seconds):
// "v1=" + hex(HMAC-SHA256(secret, ts + "." + body)).
func Sign(secret string, ts int64, body []byte) string {
mac := hmac.New(sha256.New, []byte(secret))
mac.Write([]byte(strconv.FormatInt(ts, 10)))
mac.Write([]byte{'.'})
mac.Write(body)
return signatureVersion + hex.EncodeToString(mac.Sum(nil))
}

var (
ErrBadSignature = errors.New("changehook: signature does not match")
ErrStale = errors.New("changehook: timestamp outside the tolerance")
)

// Verify is what a receiver does with a delivery: the timestamp header, the signature
// header and the raw body, as received. It is here so the receiving side is tested against
// the sending side and the documented example is real code.
func Verify(secret, timestampHeader, signatureHeader string, body []byte, now time.Time, tolerance time.Duration) error {
ts, err := strconv.ParseInt(strings.TrimSpace(timestampHeader), 10, 64)
if err != nil {
return ErrBadSignature
}
if d := now.Sub(time.Unix(ts, 0)); d > tolerance || d < -tolerance {
return ErrStale
}
if !hmac.Equal([]byte(Sign(secret, ts, body)), []byte(strings.TrimSpace(signatureHeader))) {
return ErrBadSignature
}
return nil
}
Loading
Loading