Tidy stale comments and duplicated helpers
Comments carried over from web_server (CVLayout.vue, messageResolver, the Spotify token code) and ones outdated by later changes (the email window now anchors on ReceivedAt, failed emails are retried) are corrected. truncateRunes had a copy in handlers and in services; there is now one, services.TruncateRunes. cleanEmailBody's regexes are compiled once, a status check that could never fire is gone, and api.js loses its unused put/patch helpers. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
@@ -10,14 +10,13 @@ import "adam-french.co.uk/job-tracker/internal/handlers"
|
|||||||
// Resolver is the root of the GraphQL schema and the only dependency every
|
// Resolver is the root of the GraphQL schema and the only dependency every
|
||||||
// resolver has. Rather than listing dependencies individually it holds the
|
// resolver has. Rather than listing dependencies individually it holds the
|
||||||
// same handlers.Store the REST handlers use, so GraphQL and REST share one
|
// same handlers.Store the REST handlers use, so GraphQL and REST share one
|
||||||
// database handle and one set of third-party caches.
|
// database handle and the same services.
|
||||||
//
|
//
|
||||||
// The generated code embeds *Resolver in per-type resolver structs, which is
|
// The generated code embeds *Resolver in per-type resolver structs, which is
|
||||||
// why one-line `struct{ *Resolver }` declarations appear at the bottom of some
|
// why one-line `struct{ *Resolver }` declarations appear at the bottom of some
|
||||||
// resolvers files. A type only gets one when a field of it needs a resolver:
|
// resolvers files. A type only gets one when a field of it needs a resolver:
|
||||||
// queryResolver and mutationResolver always, messageResolver and
|
// queryResolver and mutationResolver always. Every object type binds its
|
||||||
// rowingResolver for their unsigned-to-Int fields. Most object types bind
|
// fields straight to the model and has none.
|
||||||
// every field straight to the model and have none.
|
|
||||||
type Resolver struct {
|
type Resolver struct {
|
||||||
Store *handlers.Store
|
Store *handlers.Store
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -152,16 +152,6 @@ type PostingExtractor interface {
|
|||||||
ExtractPosting(ctx context.Context, url, title, text string) (claude.JobPosting, error)
|
ExtractPosting(ctx context.Context, url, title, text string) (claude.JobPosting, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
// truncateRunes cuts s to at most max runes, on a rune boundary so the result
|
|
||||||
// is still valid UTF-8 for Postgres and for JSON.
|
|
||||||
func truncateRunes(s string, max int) string {
|
|
||||||
runes := []rune(s)
|
|
||||||
if len(runes) <= max {
|
|
||||||
return s
|
|
||||||
}
|
|
||||||
return string(runes[:max])
|
|
||||||
}
|
|
||||||
|
|
||||||
// bindCapture decodes a size-limited JSON body, answering 400 itself when it
|
// bindCapture decodes a size-limited JSON body, answering 400 itself when it
|
||||||
// cannot.
|
// cannot.
|
||||||
func bindCapture(ctx *gin.Context, into any) bool {
|
func bindCapture(ctx *gin.Context, into any) bool {
|
||||||
@@ -192,7 +182,7 @@ func (store *Store) JobCaptureExtract(ctx *gin.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
posting, err := store.Extractor.ExtractPosting(ctx.Request.Context(),
|
posting, err := store.Extractor.ExtractPosting(ctx.Request.Context(),
|
||||||
truncateRunes(input.URL, 2000), truncateRunes(input.Title, 500), truncateRunes(text, maxPageRunes))
|
services.TruncateRunes(input.URL, 2000), services.TruncateRunes(input.Title, 500), services.TruncateRunes(text, maxPageRunes))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Println("Job extract failed:", err)
|
log.Println("Job extract failed:", err)
|
||||||
var readErr *claude.ReadError
|
var readErr *claude.ReadError
|
||||||
@@ -215,7 +205,7 @@ func (store *Store) JobCapture(ctx *gin.Context) {
|
|||||||
if !bindCapture(ctx, &input) {
|
if !bindCapture(ctx, &input) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
input.Description = truncateRunes(strings.TrimSpace(input.Description), maxPageRunes)
|
input.Description = services.TruncateRunes(strings.TrimSpace(input.Description), maxPageRunes)
|
||||||
|
|
||||||
app, action, err := services.UpsertJobApplication(store.DB, input, time.Now())
|
app, action, err := services.UpsertJobApplication(store.DB, input, time.Now())
|
||||||
var invalid *services.JobInputError
|
var invalid *services.JobInputError
|
||||||
|
|||||||
@@ -140,15 +140,6 @@ func TestCaptureTokenAdminEndpoints(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestTruncateRunes(t *testing.T) {
|
|
||||||
if got := truncateRunes("££££", 2); got != "££" {
|
|
||||||
t.Fatalf("got %q; the cut must fall on a rune boundary", got)
|
|
||||||
}
|
|
||||||
if got := truncateRunes("short", 10); got != "short" {
|
|
||||||
t.Fatalf("got %q", got)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// fakeExtractor answers every page with posting and err, recording the
|
// fakeExtractor answers every page with posting and err, recording the
|
||||||
// arguments it was called with.
|
// arguments it was called with.
|
||||||
type fakeExtractor struct {
|
type fakeExtractor struct {
|
||||||
|
|||||||
+12
-13
@@ -1,11 +1,3 @@
|
|||||||
package models
|
|
||||||
|
|
||||||
import (
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"gorm.io/gorm"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Package models holds the GORM entities, which are also the GraphQL object
|
// Package models holds the GORM entities, which are also the GraphQL object
|
||||||
// types: gqlgen.yml maps each GraphQL type straight onto the struct here, so
|
// types: gqlgen.yml maps each GraphQL type straight onto the struct here, so
|
||||||
// graph/model/ only contains generated input and payload types. That means
|
// graph/model/ only contains generated input and payload types. That means
|
||||||
@@ -23,6 +15,13 @@ import (
|
|||||||
// - IDs are uint here and the ID scalar in GraphQL. gqlgen.yml binds the
|
// - IDs are uint here and the ID scalar in GraphQL. gqlgen.yml binds the
|
||||||
// two directly (graphql.UintID), so an `ID uint` field needs no resolver.
|
// two directly (graphql.UintID), so an `ID uint` field needs no resolver.
|
||||||
// On the wire an id is a quoted decimal string, "12".
|
// On the wire an id is a quoted decimal string, "12".
|
||||||
|
package models
|
||||||
|
|
||||||
|
import (
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
// JobAppReference is a reusable snippet for filling in job application forms
|
// JobAppReference is a reusable snippet for filling in job application forms
|
||||||
// (a stock answer, a profile link, and so on), grouped by Category and
|
// (a stock answer, a profile link, and so on), grouped by Category and
|
||||||
@@ -41,11 +40,11 @@ type JobAppReference struct {
|
|||||||
// ProcessedEmail records that the email pipeline has already looked at a
|
// ProcessedEmail records that the email pipeline has already looked at a
|
||||||
// message, so it is never classified twice.
|
// message, so it is never classified twice.
|
||||||
//
|
//
|
||||||
// Unlike every other model it has no DeletedAt and so is NOT soft deleted —
|
// Like JobLead it has no DeletedAt and so is NOT soft deleted — the dedup
|
||||||
// the dedup check must see every historical row. Its CreatedAt also drives
|
// check must see every historical row. Its ReceivedAt drives the next sync's
|
||||||
// the next sync's time window, so the most recent row here is effectively the
|
// time window, so the newest row here is effectively the pipeline's cursor. A
|
||||||
// pipeline's cursor. A row is written even when classification failed, with
|
// row is written even when classification failed, with Action "error"; see
|
||||||
// Action "error", which means failures are never retried.
|
// Attempts for how those are retried.
|
||||||
type ProcessedEmail struct {
|
type ProcessedEmail struct {
|
||||||
ID uint `gorm:"primarykey" json:"id"`
|
ID uint `gorm:"primarykey" json:"id"`
|
||||||
CreatedAt time.Time `json:"createdAt"`
|
CreatedAt time.Time `json:"createdAt"`
|
||||||
|
|||||||
@@ -74,8 +74,6 @@ type EmailSyncService struct {
|
|||||||
mu sync.Mutex
|
mu sync.Mutex
|
||||||
}
|
}
|
||||||
|
|
||||||
// Microsoft Graph API response types
|
|
||||||
|
|
||||||
// Microsoft Graph API response types. The IMAP backend parses raw RFC822
|
// Microsoft Graph API response types. The IMAP backend parses raw RFC822
|
||||||
// messages into these same structs (see parseRawEmail) so that everything
|
// messages into these same structs (see parseRawEmail) so that everything
|
||||||
// downstream of fetchEmails is backend-agnostic.
|
// downstream of fetchEmails is backend-agnostic.
|
||||||
@@ -177,8 +175,8 @@ var statusOrder = map[string]int{
|
|||||||
// Token persistence
|
// Token persistence
|
||||||
|
|
||||||
// SaveMSGraphToken persists an OAuth token to disk with 0600 permissions.
|
// SaveMSGraphToken persists an OAuth token to disk with 0600 permissions.
|
||||||
// Like the Spotify equivalent it copies into a local struct so the on-disk
|
// It copies into a local struct so the on-disk shape does not depend on the
|
||||||
// shape does not depend on the oauth2 package's own JSON tags.
|
// oauth2 package's own JSON tags.
|
||||||
func SaveMSGraphToken(path string, tok *oauth2.Token) error {
|
func SaveMSGraphToken(path string, tok *oauth2.Token) error {
|
||||||
data := struct {
|
data := struct {
|
||||||
AccessToken string `json:"access_token"`
|
AccessToken string `json:"access_token"`
|
||||||
@@ -450,7 +448,6 @@ func (s *EmailSyncService) SyncEmails(ctx context.Context) error {
|
|||||||
since = oldestRetryable.ReceivedAt
|
since = oldestRetryable.ReceivedAt
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fetch emails from Microsoft Graph
|
|
||||||
emails, err := s.fetchEmails(ctx, since)
|
emails, err := s.fetchEmails(ctx, since)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("fetching emails: %w", err)
|
return fmt.Errorf("fetching emails: %w", err)
|
||||||
@@ -767,10 +764,6 @@ func (s *EmailSyncService) createJobApplication(analysis *EmailAnalysis) (string
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if app.Status == "" {
|
|
||||||
app.Status = "applied"
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := s.DB.Create(&app).Error; err != nil {
|
if err := s.DB.Create(&app).Error; err != nil {
|
||||||
return "", nil, fmt.Errorf("creating job application: %w", err)
|
return "", nil, fmt.Errorf("creating job application: %w", err)
|
||||||
}
|
}
|
||||||
@@ -827,6 +820,13 @@ func (s *EmailSyncService) updateJobApplication(existing *models.JobApplication,
|
|||||||
return "updated", &existing.ID, nil
|
return "updated", &existing.ID, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Whitespace patterns for cleanEmailBody. Tags are stripped with htmlAnyTag
|
||||||
|
// (job_sources.go).
|
||||||
|
var (
|
||||||
|
emailSpaces = regexp.MustCompile(`[ \t]+`)
|
||||||
|
emailBlankRuns = regexp.MustCompile(`\n{3,}`)
|
||||||
|
)
|
||||||
|
|
||||||
// cleanEmailBody reduces an email body to plain-ish text before it is sent to
|
// cleanEmailBody reduces an email body to plain-ish text before it is sent to
|
||||||
// the classifier, cutting token cost and noise.
|
// the classifier, cutting token cost and noise.
|
||||||
//
|
//
|
||||||
@@ -839,8 +839,7 @@ func cleanEmailBody(content string, contentType string) string {
|
|||||||
|
|
||||||
if strings.EqualFold(contentType, "html") {
|
if strings.EqualFold(contentType, "html") {
|
||||||
// Strip HTML tags
|
// Strip HTML tags
|
||||||
tagRegex := regexp.MustCompile(`<[^>]*>`)
|
text = htmlAnyTag.ReplaceAllString(text, " ")
|
||||||
text = tagRegex.ReplaceAllString(text, " ")
|
|
||||||
|
|
||||||
// Decode common HTML entities
|
// Decode common HTML entities
|
||||||
replacer := strings.NewReplacer(
|
replacer := strings.NewReplacer(
|
||||||
@@ -856,10 +855,8 @@ func cleanEmailBody(content string, contentType string) string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Collapse whitespace
|
// Collapse whitespace
|
||||||
spaceRegex := regexp.MustCompile(`[ \t]+`)
|
text = emailSpaces.ReplaceAllString(text, " ")
|
||||||
text = spaceRegex.ReplaceAllString(text, " ")
|
text = emailBlankRuns.ReplaceAllString(text, "\n\n")
|
||||||
nlRegex := regexp.MustCompile(`\n{3,}`)
|
|
||||||
text = nlRegex.ReplaceAllString(text, "\n\n")
|
|
||||||
text = strings.TrimSpace(text)
|
text = strings.TrimSpace(text)
|
||||||
|
|
||||||
// Cut everything from the first signature marker onwards. The idx > 0
|
// Cut everything from the first signature marker onwards. The idx > 0
|
||||||
@@ -953,8 +950,7 @@ func parseReceivedAt(raw string) time.Time {
|
|||||||
|
|
||||||
// saveProcessed writes the outcome of an attempt: updating the existing row
|
// saveProcessed writes the outcome of an attempt: updating the existing row
|
||||||
// when this was a retry, inserting when it is the first attempt. Update is
|
// when this was a retry, inserting when it is the first attempt. Update is
|
||||||
// used rather than Save so the row keeps its original CreatedAt, which the
|
// used rather than Save so the row keeps its original CreatedAt.
|
||||||
// fetch window depends on.
|
|
||||||
func (s *EmailSyncService) saveProcessed(found bool, existing, record *models.ProcessedEmail) {
|
func (s *EmailSyncService) saveProcessed(found bool, existing, record *models.ProcessedEmail) {
|
||||||
var err error
|
var err error
|
||||||
if found {
|
if found {
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import (
|
|||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
"unicode"
|
"unicode"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
"adam-french.co.uk/job-tracker/internal/claude"
|
"adam-french.co.uk/job-tracker/internal/claude"
|
||||||
"adam-french.co.uk/job-tracker/internal/models"
|
"adam-french.co.uk/job-tracker/internal/models"
|
||||||
@@ -432,7 +433,7 @@ func (s *JobLeadService) storeLeads(ctx context.Context, src models.JobSource, j
|
|||||||
// snippet in place rather than losing the lead.
|
// snippet in place rather than losing the lead.
|
||||||
if job.detailID != "" && lead.Matched && lead.State == LeadNew {
|
if job.detailID != "" && lead.Matched && lead.State == LeadNew {
|
||||||
if full, err := s.fetchReedDescription(ctx, job.detailID); err == nil && full != "" {
|
if full, err := s.fetchReedDescription(ctx, job.detailID); err == nil && full != "" {
|
||||||
lead.Description = truncateRunes(full, maxLeadRunes)
|
lead.Description = TruncateRunes(full, maxLeadRunes)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
fresh = append(fresh, lead)
|
fresh = append(fresh, lead)
|
||||||
@@ -473,7 +474,7 @@ func newLead(src models.JobSource, job fetchedJob, filter leadFilter, tracked ma
|
|||||||
Company: company,
|
Company: company,
|
||||||
Location: strings.TrimSpace(job.Location),
|
Location: strings.TrimSpace(job.Location),
|
||||||
URL: strings.TrimSpace(job.URL),
|
URL: strings.TrimSpace(job.URL),
|
||||||
Description: truncateRunes(job.Description, maxLeadRunes),
|
Description: TruncateRunes(job.Description, maxLeadRunes),
|
||||||
PostedAt: job.PostedAt,
|
PostedAt: job.PostedAt,
|
||||||
LastSeenAt: now,
|
LastSeenAt: now,
|
||||||
State: LeadNew,
|
State: LeadNew,
|
||||||
@@ -686,10 +687,10 @@ func containsWord(text, word string) bool {
|
|||||||
}
|
}
|
||||||
start := from + i
|
start := from + i
|
||||||
end := start + len(word)
|
end := start + len(word)
|
||||||
before := []rune(text[:start])
|
before, _ := utf8.DecodeLastRuneInString(text[:start])
|
||||||
after := []rune(strings.TrimPrefix(text[end:], "s"))
|
after, _ := utf8.DecodeRuneInString(strings.TrimPrefix(text[end:], "s"))
|
||||||
if (len(before) == 0 || !isWordRune(before[len(before)-1])) &&
|
// RuneError is what an empty side decodes to, and is not a word rune.
|
||||||
(len(after) == 0 || !isWordRune(after[0])) {
|
if !isWordRune(before) && !isWordRune(after) {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
from = start + 1
|
from = start + 1
|
||||||
@@ -777,7 +778,7 @@ func (s *JobLeadService) scoreLeads(ctx context.Context, profile *models.JobSear
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *JobLeadService) scoreLead(ctx context.Context, profile string, lead *models.JobLead) (LeadScore, error) {
|
func (s *JobLeadService) scoreLead(ctx context.Context, profile string, lead *models.JobLead) (LeadScore, error) {
|
||||||
return s.Scorer.ScorePosting(ctx, truncateRunes(profile, maxProfileRunes),
|
return s.Scorer.ScorePosting(ctx, TruncateRunes(profile, maxProfileRunes),
|
||||||
lead.JobTitle, lead.Company, lead.Location, lead.Description)
|
lead.JobTitle, lead.Company, lead.Location, lead.Description)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -802,7 +803,7 @@ func LoadJobSearchProfile(db *gorm.DB) (*models.JobSearchProfile, error) {
|
|||||||
// SaveJobSearchProfile stores an edited profile, bounding the free text.
|
// SaveJobSearchProfile stores an edited profile, bounding the free text.
|
||||||
func SaveJobSearchProfile(db *gorm.DB, profile *models.JobSearchProfile) error {
|
func SaveJobSearchProfile(db *gorm.DB, profile *models.JobSearchProfile) error {
|
||||||
profile.ID = jobSearchProfileID
|
profile.ID = jobSearchProfileID
|
||||||
profile.Profile = truncateRunes(strings.TrimSpace(profile.Profile), maxProfileRunes)
|
profile.Profile = TruncateRunes(strings.TrimSpace(profile.Profile), maxProfileRunes)
|
||||||
profile.MinScore = min(max(profile.MinScore, 0), 100)
|
profile.MinScore = min(max(profile.MinScore, 0), 100)
|
||||||
return db.Save(profile).Error
|
return db.Save(profile).Error
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -491,9 +491,9 @@ func htmlToText(content string) string {
|
|||||||
return strings.TrimSpace(strings.Join(lines, "\n"))
|
return strings.TrimSpace(strings.Join(lines, "\n"))
|
||||||
}
|
}
|
||||||
|
|
||||||
// truncateRunes cuts s to at most max runes, on a rune boundary so the result
|
// TruncateRunes cuts s to at most max runes, on a rune boundary so the result
|
||||||
// is still valid UTF-8 for Postgres and for JSON.
|
// is still valid UTF-8 for Postgres and for JSON.
|
||||||
func truncateRunes(s string, max int) string {
|
func TruncateRunes(s string, max int) string {
|
||||||
runes := []rune(s)
|
runes := []rune(s)
|
||||||
if len(runes) <= max {
|
if len(runes) <= max {
|
||||||
return s
|
return s
|
||||||
|
|||||||
@@ -279,3 +279,12 @@ func TestWithWorkplace(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestTruncateRunes(t *testing.T) {
|
||||||
|
if got := TruncateRunes("££££", 2); got != "££" {
|
||||||
|
t.Fatalf("got %q; the cut must fall on a rune boundary", got)
|
||||||
|
}
|
||||||
|
if got := TruncateRunes("short", 10); got != "short" {
|
||||||
|
t.Fatalf("got %q", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -101,7 +101,7 @@ func firstApplication(query *gorm.DB) (*models.JobApplication, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// JobCaptureInput is a posting to add to the tracker. Its JSON form is the
|
// JobCaptureInput is a posting to add to the tracker. Its JSON form is the
|
||||||
// body of POST /jobs/capture: the popup's fields.
|
// body of POST /jobs/api/capture: the popup's fields.
|
||||||
type JobCaptureInput struct {
|
type JobCaptureInput struct {
|
||||||
JobTitle string `json:"jobTitle"`
|
JobTitle string `json:"jobTitle"`
|
||||||
Company string `json:"company"`
|
Company string `json:"company"`
|
||||||
|
|||||||
+3
-6
@@ -35,12 +35,11 @@ export class ApiError extends Error {
|
|||||||
* @param {string} method
|
* @param {string} method
|
||||||
* @param {string} path route below the API base, with its leading slash
|
* @param {string} path route below the API base, with its leading slash
|
||||||
* @param {object} [options]
|
* @param {object} [options]
|
||||||
* @param {*} [options.body] JSON-serialisable body, or a FormData for
|
* @param {*} [options.body] JSON-serialisable body
|
||||||
* multipart uploads (axios sets the boundary itself)
|
|
||||||
* @param {string} [options.fallback] message to use when the backend sent no
|
* @param {string} [options.fallback] message to use when the backend sent no
|
||||||
* `error` string — callers pass the sentence their UI shows
|
* `error` string — callers pass the sentence their UI shows
|
||||||
* Any other option (`headers`, `params`, `onUploadProgress`, `signal`, …) is
|
* Any other option (`headers`, `params`, `signal`, …) is handed to axios
|
||||||
* handed to axios unchanged.
|
* unchanged.
|
||||||
*/
|
*/
|
||||||
async function request(method, path, { body, fallback, ...config } = {}) {
|
async function request(method, path, { body, fallback, ...config } = {}) {
|
||||||
try {
|
try {
|
||||||
@@ -67,6 +66,4 @@ export const api = {
|
|||||||
get: (path, options) => request("get", path, options),
|
get: (path, options) => request("get", path, options),
|
||||||
delete: (path, options) => request("delete", path, options),
|
delete: (path, options) => request("delete", path, options),
|
||||||
post: (path, body, options) => request("post", path, { ...options, body }),
|
post: (path, body, options) => request("post", path, { ...options, body }),
|
||||||
put: (path, body, options) => request("put", path, { ...options, body }),
|
|
||||||
patch: (path, body, options) => request("patch", path, { ...options, body }),
|
|
||||||
};
|
};
|
||||||
|
|||||||
Reference in New Issue
Block a user