Course menuForge Cloud

Level 2 · Lesson 2

Accept fast, repair later

Goal of this lesson

Save the check-in, queue its check-in number and hand back a receipt at once, then let a consumer function, the next free mechanic, write the repair tasks afterwards on the workshop’s own account.

About 45 min11 steps

Behind, or starting here? Download the code as it should be before this lesson, or in the course workspace run course-catch-up level-2/after-01-check-in-desk in the folder above your app. It offers to bring your own app folder to this point and keeps its app id (the id: line in manifest.yml, which links the code to your app on the site), so it stays the same app. Your old files are kept in a copy next to it.

Right now the person at the desk waits while the resolver talks to Jira. That is fine for one repair task and not for eight, and a function called from a page has only a few seconds before Forge stops it. This lesson splits the work, as a workshop does at reception: the desk accepts the check-in and answers at once, and a separate function does the slow part later.

Feel the wait

The same check-in goes to two desks: the one from lesson 1, and the one this lesson builds. Press the button and compare how long each one keeps the person at the desk waiting.

about 3 sSimulated timings

Lesson 1 · Wait for Jira asUser()

The resolver writes the repair task itself, then answers.

Button busy for 0.0 s

Its progress shows here.

Lesson 2 · Take a receipt asApp()

The resolver saves the check-in, puts { checkInId } in the queue and answers. The consumer writes the repair task later.

Button busy for 0.0 s

Its progress shows here.

Step 1: Add storage and the queue

Runs in the Atlassian cloud

Key-Value Store (KVS)in the workshop: the filing cabinet

The Key-Value Store keeps JSON values under string keys, hosted by Forge, from @forge/kvs. Each installation has its own store, so two sites never see each other’s data. Use a prefix in each key, such as checkin:, to keep different kinds of record apart. A value can be up to about 240 KiB, roughly 240,000 characters of text.

Think of it as a filing cabinet that belongs to the app: each folder has a label on the tab (the key, such as checkin: followed by a receipt number) and one record inside (the value). The app can file a record, take it out again by its label, or replace it. There are no tables and no searches across records; you always ask by label.

In the workshop Records filed under a label, and found again by it.

Further reading, optional: Atlassian docs on Storage reference (opens in a new tab)

Runs in the Atlassian cloud

Queue (@forge/events)in the workshop: the queue

A queue, from @forge/events, takes a small message now and hands it to a consumer function later. The function that pushed it answers straight away. The consumer runs on its own, and can be given a longer time limit than a function called from a page.

If you know Jira Service Management, you know the idea: requests wait in a queue until an agent picks them up, and the customer gets a reference number straight away instead of waiting on the phone. A Forge queue is the same, for code: messages wait until the consumer function picks them up.

The time limits, side by side:

Seconds before Forge stops the function, drawn to scale. The kind of invocation sets the limit.
  • UI calls (invoke from a page or panel) and product events25 s
  • Web triggers, Rovo actions, scheduled triggers and async events, by default55 s
  • The consumer in this course (timeoutSeconds: 120)120 s (2 min)
  • A queue consumer with timeoutSeconds, at most900 s (15 min)

The rule: A click is a short function. Long work belongs on a queue. A process that must stay up belongs in a container.

In the workshop Cars wait in the queue until a mechanic is free.

Further reading, optional: Atlassian docs on Events (opens in a new tab)

RunTerminal
npm install @forge/kvs @forge/events
Editpackage.json

npm install @forge/events @forge/kvs writes these lines.

"dependencies": {
"@forge/api": "^8.2.0",
"@forge/bridge": "^7.1.0",
Added: "@forge/events": "^3.0.7",
Added: "@forge/kvs": "^2.0.7",
"@forge/react": "^12.3.0",
"@forge/resolver": "^2.0.0",
"react": "^18.2.0"

Why: Key-Value Store (KVS) · Queue (@forge/events)

Stuck?2 common problems, and their fixes
  • “Cannot find module @forge/…”

    The code imports a package that is not installed. Install the one named in the message, then deploy:

    RunTerminal
    npm install @forge/api
    forge deploy
    Open in the FAQ
  • I added an npm package

    Install it so package.json lists it, then deploy. Forge bundles what package.json and your imports name:

    RunTerminal
    npm install @forge/api
    forge deploy
    Open in the FAQ

Step 2: Save, queue the check-in number, hand back a receipt

Runs in the Atlassian cloud

Queue eventin the workshop: the check-in number

What you push to a queue is a small event body. Keep it to an id, like the number on a check-in. The real data stays in storage, where the consumer reads it, so the event never carries more than it must and never goes stale.

In the workshop Only the number goes in the queue; the notes stay in the filing cabinet.

Runs in the Atlassian cloud

Tracking idin the workshop: the check-in receipt

The id the resolver returns at once, before any work is done. Here it is checkInId, a random UUID: a long, randomly generated id that is practically impossible to guess or to repeat. The desk keeps it and asks about that check-in every two seconds until it is done.

In the workshop Handed over straight away, with the number to ask about later.

See this on the Level 2 chart, in the step that files the check-in and puts its id on the queue.

A new file holds the whole pattern. The order matters: save first, then push. Push first, and the consumer may start before the check-in exists.

The deskCheck inDesk resolversubmitCheckInKey-Value Storethe whole check-inThe queueonly the numberThe consumerworks afterwardsthe receipt, at oncereads it1234save first, then push
New filesrc/checkins.js

A new file: check-ins are filed in the Key-Value Store, and only their id goes in the queue.

Added: import { randomUUID } from 'node:crypto';

Borrow a tool that makes long random ids, built into Node.js, the program that runs your functions.

Added: import { kvs } from '@forge/kvs';

Borrow Forge’s storage, the Key-Value Store.

Added: import { Queue } from '@forge/events';

Borrow Forge’s queues.

Added: import { STORE } from './lib/config';
Added:
Added: const queue = new Queue({ key: 'checkin-queue' });

The queue this app pushes check-ins to. The name must match the manifest.

Added:
Added: export const getCheckIn = (checkInId) => kvs.get(`${STORE.CHECK_IN}${checkInId}`);

Read one check-in from storage, filed under checkin: plus its id.

Added:
Added: export const saveCheckIn = (checkInId, checkIn) => kvs.set(`${STORE.CHECK_IN}${checkInId}`, { ...checkIn, updatedAt: new Date().toISOString() });

Save a check-in under the same name, with the time it changed. ...checkIn copies all its fields in.

Added:
Added: /**
Added: * Accept fast: file the whole check-in in the Key-Value Store, put only its id in
Added: * the queue, and return the receipt. Save first: the worker may start before this returns.
Added: */
Added: export async function acceptCheckIn(checkIn) {
Added: const checkInId = randomUUID();

Make the receipt number.

Added: await saveCheckIn(checkInId, { ...checkIn, status: 'waiting', checkpoint: {} });

Save the check-in first, marked as waiting.

Added: await queue.push({ body: { checkInId } });

Then put only its number on the queue.

Added: return checkInId;

Hand the number back at once, as the receipt.

Added: }

Why: Key-Value Store (KVS) · Queue event · Tracking id

Stuck?One common problem, and its fix
  • Checking a car in fails with “400 Bad Request” from the queue

    The queue has no consumer. Check that manifest.yml has a consumer whose queue matches the key in new Queue({ key: 'checkin-queue' }), then deploy.

    Open in the FAQ

Step 3: The desk uses the queue now

The desk no longer writes repair tasks itself, so it swaps the repair task helpers for the new check-in file, src/checkins.js:

Editsrc/desk.jsChange 1 of 2

The desk no longer writes repair tasks itself.

import Resolver from '@forge/resolver';
import api, { route } from '@forge/api';
Removed: import { LABELS, settings } from './lib/config';
Removed: import { paragraphs } from './lib/adf';
Added: import { settings } from './lib/config';
import { validateCheckIn } from './lib/validate';
Editsrc/desk.jsChange 2 of 2
import { validateCheckIn } from './lib/validate';
Added: import { acceptCheckIn, getCheckIn } from './checkins';

Borrow the new save-and-queue code instead of writing work items here.

const resolver = new Resolver();

Why: Queue (@forge/events)

Step 4: Check before acting on the workshop’s account

Runs in the Atlassian cloud

asApp()in the workshop: on the workshop’s account

asApp() calls a product API as the app itself, with the app’s scopes and no person attached. A consumer has nobody to act for, so it must use it. The app may be allowed more than the person who asked, so check the person’s own permission before the app acts for them.

In the workshop When nobody is logged in, the workshop acts on its own account.

Further reading, optional: Atlassian docs on Product REST APIs (opens in a new tab)

The consumer will write repair tasks as the app. Before accepting a check-in, ask Jira whether the person sending it could create work items in the Workshop space themselves:

Editsrc/desk.js

Ask Jira, as the person, whether they may create work items in the project.

const resolver = new Resolver();
Added: // The worker will create repair tasks on the workshop's own account. Before that,
Added: // check that the person asking could create work items in the project themselves.
Added: async function canCreateIn(projectKey) {

A helper that asks: may the person at the desk create work items in this space?

Added: const response = await api
Added: .asUser()
Added: .requestJira(route`/rest/api/3/mypermissions?projectKey=${projectKey}&permissions=CREATE_ISSUES`);

Jira’s “my permissions” check, the same Create permission you set in a permission scheme, asked as the person.

Added: if (!response.ok) return false;
Added: const data = await response.json();
Added: return data.permissions?.CREATE_ISSUES?.havePermission === true;

Yes only if Jira says so; anything else counts as no.

Added: }
Added:
// One repair task for the whole check-in, created on the login of the person asking.
resolver.define('submitCheckIn', async ({ payload }) => {
const check = validateCheckIn(payload);

Why: asApp() · asUser()

Stuck?One common problem, and its fix
  • Creating a repair task fails with “Jira answered 400”

    Usually the issue type. The app creates a Task in the space set by WORKSHOP_PROJECT_KEY. If your space has no Task type, set another one and deploy:

    RunTerminal
    forge variables set WORKSHOP_ISSUE_TYPE Story
    forge deploy
    Open in the FAQ

Step 5: Accept fast and hand back a receipt

submitCheckIn now checks, saves, pushes and returns the receipt. A second resolver, getCheckIn, lets the desk follow it:

Editsrc/desk.jsChange 1 of 4
  • submitCheckIn returns as soon as the check-in number is in the queue.
  • getCheckIn lets only the sender follow their receipt.
return data.permissions?.CREATE_ISSUES?.havePermission === true;
}
Removed: // One repair task for the whole check-in, created on the login of the person asking.
Removed: resolver.define('submitCheckIn', async ({ payload }) => {
Added: // Accept fast: check, save, queue, and return a receipt straight away.
Added: resolver.define('submitCheckIn', async ({ payload, context }) => {
const check = validateCheckIn(payload);
if (!check.ok) return { error: check.error };
Editsrc/desk.jsChange 2 of 4
const check = validateCheckIn(payload);
if (!check.ok) return { error: check.error };
Removed: const { projectKey, issueType } = settings();
Removed: const { car, notes } = check.checkIn;
Removed: const response = await api.asUser().requestJira(route`/rest/api/3/issue`, {
Removed: method: 'POST',
Removed: headers: { Accept: 'application/json', 'Content-Type': 'application/json' },
Removed: body: JSON.stringify({
Removed: fields: {
Removed: project: { key: projectKey },
Removed: issuetype: { name: issueType },
Removed: summary: car,
Removed: description: paragraphs(notes),
Removed: labels: [LABELS.CHECK_IN],
Removed: },
Removed: }),
Removed: });
Removed: if (!response.ok) {
Removed: return { error: `Jira answered ${response.status}: ${await response.text()}` };
Added: const { projectKey } = settings();
Added: if (!(await canCreateIn(projectKey))) {

Before the app acts for them, check the person could do it themselves.

Added: return { error: `You can’t create work items in ${projectKey}, so the workshop won’t either.` };
}
Editsrc/desk.jsChange 3 of 4
}
Removed: const issue = await response.json();
Removed: return { card: { key: issue.key, summary: car } };
Added: const checkInId = await acceptCheckIn({ ...check.checkIn, requestedBy: context.accountId });

Save and queue the check-in, noting who sent it, and get the receipt number.

Added: return { checkInId };

Answer the desk at once with just the receipt.

});
Editsrc/desk.jsChange 4 of 4
});
Added: // Only the person who checked the car in can follow its receipt.
Added: resolver.define('getCheckIn', async ({ payload, context }) => {

A second question the desk asks every two seconds: how is my check-in doing?

Added: const checkIn = typeof payload?.checkInId === 'string' ? await getCheckIn(payload.checkInId) : undefined;
Added: if (!checkIn || checkIn.requestedBy !== context.accountId) return { error: 'No check-in with that receipt.' };

Only the person who sent it may follow it. Anyone else is told it doesn’t exist.

Added: return { status: checkIn.status, cards: checkIn.cards ?? [], page: checkIn.page ?? null, error: checkIn.error ?? null };
Added: });
Added:
export const handler = resolver.getDefinitions();

Why: Tracking id · Product context

getCheckIn compares context.accountId with the person who checked the car in, so a receipt id on its own shows nothing to anyone else.

Stuck?One common problem, and its fix
  • My check-in stays “waiting” or ends “failed”

    The consumer ran into a problem. Read its log, which names the step that failed:

    RunTerminal
    forge logs --since 15m

    The usual causes are a missing WORKSHOP_PROJECT_KEY, a Jira space you cannot create work items in, or Forge LLM not being available on the site yet.

    Open in the FAQ

Step 6: Write a repair task on the workshop’s account

The code that writes repair tasks moves into its own file, now as the app. The space always comes from settings, never from the check-in, because the app may be allowed into spaces the person who sent it is not:

New filesrc/repairs/createRepairTask.js

A new file: the project always comes from settings, never from the browser.

Added: import api, { route } from '@forge/api';
Added: import { LABELS, LIMITS, settings } from '../lib/config';
Added: import { paragraphs } from '../lib/adf';
Added:
Added: /**
Added: * Creates one repair task on the workshop's own account (asApp). No user is
Added: * present in a queue consumer. The project always comes from settings.
Added: */
Added: export async function createRepairTask({ summary, notes, expert = false }) {

Create one repair task. expert = false means “not for the expert, unless told otherwise”.

Added: const { projectKey, issueType } = settings();
Added: const labels = expert ? [LABELS.CHECK_IN, LABELS.EXPERT] : [LABELS.CHECK_IN];

Every task gets check-in; tasks for the expert also get needs-expert.

Added: const response = await api.asApp().requestJira(route`/rest/api/3/issue`, {

Create the work item as the app itself, because nobody is watching when this runs.

Added: method: 'POST',
Added: headers: { Accept: 'application/json', 'Content-Type': 'application/json' },
Added: body: JSON.stringify({
Added: fields: {
Added: project: { key: projectKey },
Added: issuetype: { name: issueType },
Added: summary: summary.slice(0, LIMITS.SUMMARY),

Cut the summary to the longest Jira allows.

Added: description: paragraphs(notes),
Added: labels,
Added: },
Added: }),
Added: });
Added: if (!response.ok) {
Added: throw new Error(`Jira answered ${response.status}: ${await response.text()}`);
Added: }
Added: const issue = await response.json();
Added: return issue.key;

Give back the new work item’s key.

Added: }

Why: asApp()

Step 7: The next free mechanic takes the check-in

Runs in the Atlassian cloud

Consumer (worker function)in the workshop: the next free mechanic

A consumer is the function a consumer module runs for each event on its queue. It starts after the resolver has already answered, gets the event’s body, and has its own time limit. If it throws an error (stops and reports a problem), Forge can run it again with the same event, so it must be safe to run twice.

In the workshop Takes the next car from the queue and does the long work.

See this on the Level 2 chart, in the step where the queue consumer takes the id.

For now the consumer writes one repair task for the whole check-in, as the desk did, and records progress on the check-in in the store as it goes. The desk shows those statuses.

New filesrc/worker.js

A new file: one run per check-in number, after submitCheckIn has returned.

Added: import { getCheckIn, saveCheckIn } from './checkins';
Added: import { createRepairTask } from './repairs/createRepairTask';
Added:
Added: // Forge runs this once per check-in number in the checkin-queue, after
Added: // submitCheckIn has already returned. A message can arrive more than once, so
Added: // every step checks the checkpoint before doing work.
Added: export async function run(event) {

What runs for each check-in number on the queue.

Added: const { checkInId } = event.body;

Take the number out of the queue message.

Added: const checkIn = await getCheckIn(checkInId);

Read the full check-in from storage.

Added: if (!checkIn) {
Added: console.error(`Worker: no check-in ${checkInId}`);
Added: return;
Added: }
Added: const checkpoint = checkIn.checkpoint ?? {};

The notes on what is already done, so a second run never does it twice.

Added: const save = (status, extra = {}) => saveCheckIn(checkInId, { ...checkIn, ...extra, status, checkpoint });

A short way to save the progress, which the desk shows.

Added: try {
Added: await save('creating');
Added: if (!checkpoint.checkInTask) {

Only create the repair task if an earlier run didn’t already.

Added: checkpoint.checkInTask = await createRepairTask({ summary: checkIn.car, notes: checkIn.notes });
Added: await save('creating');
Added: }
Added: await save('done', { cards: [{ key: checkpoint.checkInTask, summary: checkIn.car }] });

Mark it done, with the repair task for the desk to show.

Added: } catch (error) {
Added: console.error(`Worker: check-in ${checkInId} failed:`, error);
Added: await save('failed', { error: error.message });

Something failed: save that, so the desk can say so.

Added: throw error;

Then fail on purpose, so Forge can run it again with the same check-in.

Added: }
Added: }

Why: Consumer (worker function) · Checkpoint

Stuck?One common problem, and its fix
  • My check-in stays “waiting” or ends “failed”

    The consumer ran into a problem. Read its log, which names the step that failed:

    RunTerminal
    forge logs --since 15m

    The usual causes are a missing WORKSHOP_PROJECT_KEY, a Jira space you cannot create work items in, or Forge LLM not being available on the site yet.

    Open in the FAQ

Step 8: Add the queue and its consumer to the manifest

Three changes:

  • The consumer, which joins the queue to its function.
  • That function, with a longer timeout.
  • The scope for storage.

The queue’s name, checkin-queue, must match new Queue({ key: 'checkin-queue' }) exactly.

Editmanifest.ymlChange 1 of 3

A consumer: the checkin-queue is worked by checkin-worker.

function: bell
events:
- avi:jira:created:issue
Added: consumer:

A new module: who works through a queue.

Added: - key: checkin-consumer
Added: queue: checkin-queue

Which queue: the same name as in checkins.js.

Added: function: checkin-worker

Which function to run for each message.

function:
- key: resolver
handler: index.handler
Editmanifest.ymlChange 2 of 3

The worker’s function, with a longer timeout.

handler: bell.run
- key: desk-resolver
handler: desk.handler
Added: - key: checkin-worker
Added: handler: worker.run

Its code: the run export in src/worker.js.

Added: timeoutSeconds: 120

Allow it up to two minutes, much longer than a page’s resolver gets.

resources:
- key: main
path: src/frontend/index.jsx
Editmanifest.ymlChange 3 of 3

A permission to use the Key-Value Store.

scopes:
- read:jira-work
- write:jira-work
Added: - storage:app

Permission to use the app’s own storage.

Why: Queue (@forge/events) · Consumer (worker function) · Runtime limits · Key-Value Store (KVS)

Stuck?2 common problems, and their fixes
  • Checking a car in fails with “400 Bad Request” from the queue

    The queue has no consumer. Check that manifest.yml has a consumer whose queue matches the key in new Queue({ key: 'checkin-queue' }), then deploy.

    Open in the FAQ
  • I changed manifest.yml

    Check it, then deploy:

    RunTerminal
    forge lint
    forge deploy

    If the change adds a scope or an outside host, forge deploy stops and asks for approval. See Deploy stops after a permission change.

    Open in the FAQ

Step 9: Quiet the bell for the workshop’s own repair tasks

Declared in manifest.yml

ignoreSelfin the workshop: the bell ignores the workshop’s own repair tasks

ignoreSelf: true in a trigger’s filter drops events that the app itself caused. Without it, every repair task the app writes rings its own bell, and a trigger that edits what it listens to can run in a loop.

In the workshop If the app itself wrote or changed the repair task, the bell stays quiet.

The Level 1 bell rings for every new work item, including the ones the consumer now writes. Let it ignore the app’s own:

Editmanifest.yml

Repair tasks the app creates no longer ring the bell.

function: bell
events:
- avi:jira:created:issue
Added: filter:
Added: ignoreSelf: true

Don’t ring for work items the app itself created.

consumer:
- key: checkin-consumer
queue: checkin-queue

Why: ignoreSelf · Product trigger

Stuck?One common problem, and its fix

Step 10: Build, deploy and sign the new approval

storage:app is a new scope, so this is a major version:

RunTerminal
npm run build:ui
forge deploy --approve MAJOR_VERSION_RULE
forge install --upgrade
Stuck?3 common problems, and their fixes
  • Deploy stops after a permission change

    That is expected, not an error. A new scope or outside host makes a new major version, which you approve. Then move each installation onto it. On your own developer site you are the admin, so you accept it yourself:

    RunTerminal
    forge deploy --approve MAJOR_VERSION_RULE
    forge install --upgrade
    Open in the FAQ
  • I changed the check-in desk (Level 2)

    The desk is built from static/desk/src into static/desk/build, which is what Forge serves. Build, then deploy:

    RunTerminal
    npm run build:ui
    forge deploy
    Open in the FAQ
  • The tunnel is running while I deploy or upgrade

    Stop it with Ctrl+C first, then deploy or upgrade, then start it again. While the tunnel runs, Jira runs the code on your laptop instead of your last deploy, so if you deploy with it running you cannot tell which version you are testing. Changes to the manifest only reach the site through a deploy, never through the tunnel.

    Open in the FAQ

Step 11: Check the car in and take a receipt

Open the check-in desk and check the BMW 3 Series in again, with the same notes. The first check-in after a deploy can keep the button busy for up to ten seconds while Forge starts the function; after that, the button is free almost at once, and the desk shows the check-in moving: in the queue, writing repair tasks, done. Open the new repair task: its reporter is the app, not you. forge logs shows no bell line for it.

Stuck?2 common problems, and their fixes
  • My check-in stays “waiting” or ends “failed”

    The consumer ran into a problem. Read its log, which names the step that failed:

    RunTerminal
    forge logs --since 15m

    The usual causes are a missing WORKSHOP_PROJECT_KEY, a Jira space you cannot create work items in, or Forge LLM not being available on the site yet.

    Open in the FAQ
  • Checking a car in fails with “400 Bad Request” from the queue

    The queue has no consumer. Check that manifest.yml has a consumer whose queue matches the key in new Queue({ key: 'checkin-queue' }), then deploy.

    Open in the FAQ

Compare with yours: download the code after this lesson.

Type at least two letters.