Skip to content

Run a Photo Job ​

Add a background check to the App from Save and List Photos. POST /api/v1/photos/:id/check queues a saved photo ID and returns 202 Accepted. The worker loads that record and logs its ID.

Enable Jobs ​

Stop forj dev and add jobs to the render.components list in .goforj.yml.

yaml
render:
  components: [cli, web_api, database_sqlite, jobs]

From the Project root, render the added component and generate the job.

bash
forj render &&
  forj make:job photos:check --no-open

The generator creates internal/photos/check_job.go and registers its constructor and handler in app/wire/inject_jobs_app.go. Confirm QUEUE_DRIVER=workerpool in .env. This local driver needs the HTTP producer and worker in the same App process.

Load the Saved Photo ​

Replace internal/photos/check_job.go. In the internal/queues import, substitute your module path for example.com/photodrop.

go
package photos

import (
	"context"
	"encoding/json"
	"log"
	"time"

	"example.com/photodrop/internal/queues"
	"github.com/goforj/queue"
)

// CheckJobTypeName identifies the job during dispatch and registration.
const CheckJobTypeName = "photos:check"

// CheckJobPayload identifies the saved photo to load.
type CheckJobPayload struct {
	PhotoID int64 `json:"photo_id"`
}

// CheckJob loads photo records in a worker.
type CheckJob struct {
	queues *queues.Manager
	photos *PhotoRepo
}

// NewCheckJob receives the generated queue manager and registered repository.
func NewCheckJob(queues *queues.Manager, photos *PhotoRepo) *CheckJob {
	return &CheckJob{queues: queues, photos: photos}
}

// Queue submits a photo check with one retry after the initial attempt.
func (j *CheckJob) Queue(ctx context.Context, payload CheckJobPayload) error {
	data, err := json.Marshal(payload)
	if err != nil {
		return err
	}
	_, err = j.queues.WithContext(ctx).Dispatch(
		queue.NewJob(CheckJobTypeName).Payload(data).OnQueue("default").
			Retry(1).Backoff(time.Second).Timeout(10*time.Second),
	)
	return err
}

// HandleTask loads the saved photo and logs its ID.
func (j *CheckJob) HandleTask(ctx context.Context, msg queue.Message) error {
	var payload CheckJobPayload
	if err := msg.Bind(&payload); err != nil {
		return err
	}
	if _, err := j.photos.WithContext(ctx).ByID(payload.PhotoID); err != nil {
		return err
	}
	log.Printf("photo checked id=%d", payload.PhotoID)
	return nil
}

Retry(1) permits at most two attempts. For this workerpool driver, the ten-second timeout covers the job run, including its retry and backoff. The repository query uses that worker context. The job reads the record and logs its ID on each successful delivery.

Queue from a Separate Endpoint ​

In internal/photos/controller.go, replace the Controller struct and NewController with the following. Retain the existing Index and Store handlers and routes when adding the check endpoint.

go
// Controller exposes photo metadata and background checks over HTTP.
type Controller struct {
	service  *Service
	checkJob *CheckJob
}

// NewController receives the service and job constructed by Wire.
func NewController(service *Service, checkJob *CheckJob) *Controller {
	return &Controller{service: service, checkJob: checkJob}
}

Append this entry to the slice returned by Routes.

go
web.NewRoute(http.MethodPost, "/photos/:id/check", c.Check),

Create internal/photos/check.go.

go
package photos

import (
	"context"
	"net/http"
	"strconv"

	"github.com/goforj/web"
)

// Check submits a saved photo reference to the worker and returns after dispatch.
func (c *Controller) Check(ctx web.Context) error {
	id, err := strconv.ParseInt(ctx.Param("id"), 10, 64)
	if err != nil || id <= 0 {
		return ctx.JSON(http.StatusBadRequest, map[string]string{"error": "invalid_photo_id"})
	}
	if err := c.checkJob.Queue(context.WithoutCancel(ctx.Context()), CheckJobPayload{PhotoID: id}); err != nil {
		return err
	}
	return ctx.JSON(http.StatusAccepted, map[string]any{"photo_id": id, "status": "queued"})
}

context.WithoutCancel lets an accepted check outlive its HTTP response while preserving context values. The job's timeout still bounds the worker run.

Verify the Worker ​

Start the combined App from the Project root.

bash
forj dev

After Dev ready, use a second terminal to request a check. Use the same port as in Save and List Photos. Replace 1 with the numeric ID saved in that lesson.

bash
curl -i -X POST http://localhost:3000/api/v1/photos/1/check

Expect 202 Accepted with the queued photo ID in the response body.

json
{"photo_id":1,"status":"queued"}

Look for photo checked id=1 in the App terminal to confirm the worker loaded the saved record. A check for a missing ID can queue successfully and then fail at lookup.

Observe One Retry ​

For a local demonstration, stop forj dev and create internal/photos/retry_demo.go.

go
package photos

import (
	"errors"
	"log"
	"sync/atomic"
)

// retryDemoFailed limits the local demonstration to one simulated failure per process.
var retryDemoFailed atomic.Bool

// retryDemo fails once so the worker can demonstrate its configured retry.
func retryDemo(photoID int64) error {
	if retryDemoFailed.CompareAndSwap(false, true) {
		log.Printf("photo retry demo id=%d", photoID)
		return errors.New("temporary photo check demo failure")
	}
	return nil
}

Temporarily insert this block in HandleTask after the repository lookup and before the success log.

go
if err := retryDemo(payload.PhotoID); err != nil {
	return err
}

Start forj dev again and send the same check request once from a second terminal. The App terminal should show these messages about one second apart.

text
photo retry demo id=1
photo checked id=1

The first attempt returns the simulated error. Its one retry loads the record again and succeeds. Stop the App, remove the temporary block and retry_demo.go, then restart with forj dev to restore the normal handler.

workerpool holds pending work in memory. Use a shared queue backend before splitting HTTP and workers into separate processes, and verify durability against that backend. See Retries and Idempotency before adding side effects such as sending mail or writing files.

Next Steps ​

Add job dispatch tests to check what the app queues before starting a worker. Use Deploy an App to build and check this app as a release.