Skip to content

Core\Queue\Id::toString

$id->toString(): string

Returns the job id as a string, so you can send it to a client and find the job again in a later request. Core\Queue\Id::parse reads the string back into an id.

The string has three parts joined by dots: the job's number, a random token and the queue. It contains only letters, digits, ., _ and -. You can put it in a URL, a header, a cookie or JSON without escaping. echo, string interpolation and as string give the same string.

The token is 16 random bytes. A string that a user changed or guessed finds no job: status throws a RuntimeError, and cancel returns false. The id does not say who may use the job. Save the string beside the user who started the job. In a later request, look it up with the signed-in user before you call status or cancel.

The examples below put an id in a link, read a saved id back in a later request, and send an id to the browser as JSON.

Return value

Returns string. A string of letters, digits, ., - and _. Core\Queue\Id::parse reads it back as an id for the same job. Keep the string secret like a password. Anybody who has it can check or cancel the job.

Examples

The examples below run with this configuration file.

nvs.toml
# The `jobs` database is kept in memory. It is deleted when the program ends.
[db.jobs]
driver = "sqlite"
path = ":memory:"
# The program may open the `jobs` database itself, to create the tables.
[capabilities.db]
connect = ["jobs"]
# `Core\Queue` saves its jobs in the `jobs` database.
# `workers = 0` starts no workers, so every job stays `Pending`.
[queue]
connection = "jobs"
workers = 0

Put the id in a link

<?nvs
// Shows how to put the id of a new job in a link.
use Core\Queue;
// On a real server, `nvs queue migrate` creates the queue tables.
// This database is in memory, so the example creates them itself.
var $db = Core\Db::connect('jobs');
var $jobs = <<<'SQL'
create table nvs_jobs (id integer primary key autoincrement, queue varchar(255) not null,
script text not null, args text, state smallint not null, attempts integer not null,
max_attempts integer not null, backoff_ms bigint not null, run_at bigint not null,
tag varchar(255), dedupe_key varchar(255), dedupe_pending varchar(255),
created_at bigint not null, claimed_at bigint, errors text, grants text, limits text,
non_transactional smallint, token text, constraint nvs_jobs_dedupe unique (dedupe_pending))
SQL;
$db->execute($jobs, []);
var $job = Queue::push('jobs/export.nvs', { queue: 'exports', arguments: ['table' => 'orders'] });
// `toString` returns the id with a random token in it. This prints it as `1.<token>.ZXhwb3J0cw`.
// The last part is the queue name `exports`, in an encoded form.
string $text = $job->toString();
array<string> $parts = Core\Str::split($text, '.');
echo $parts[0], '.<token>.', $parts[2], "\n";
// The string contains no character that a URL must escape.
// `Core\Uri::encodeComponent` returns it unchanged, so this prints `unchanged`.
echo Core\Uri::encodeComponent($text) == $text ? 'unchanged' : 'changed', "\n";
// An id in a string with `"$job"` gives the same text as `toString`.
// This prints `same`.
string $link = "/exports/status?job=$job";
echo $link == '/exports/status?job=' . $text ? 'same' : 'different', "\n";
Output
1.<token>.ZXhwb3J0cw
unchanged
same

Find the job in a later request

<?nvs
// Shows how to save the id of a job beside its user, and find the job again later.
use Core\Db\Row;
use Core\Queue;
use Core\Queue\Id;
// On a real server, `nvs queue migrate` creates the queue tables.
// This database is in memory, so the example creates them itself.
var $db = Core\Db::connect('jobs');
var $jobs = <<<'SQL'
create table nvs_jobs (id integer primary key autoincrement, queue varchar(255) not null,
script text not null, args text, state smallint not null, attempts integer not null,
max_attempts integer not null, backoff_ms bigint not null, run_at bigint not null,
tag varchar(255), dedupe_key varchar(255), dedupe_pending varchar(255),
created_at bigint not null, claimed_at bigint, errors text, grants text, limits text,
non_transactional smallint, token text, constraint nvs_jobs_dedupe unique (dedupe_pending))
SQL;
var $dead = <<<'SQL'
create table nvs_dead_jobs (id bigint not null, queue varchar(255) not null,
script text not null, args text, attempts integer not null, max_attempts integer not null,
backoff_ms bigint not null, run_at bigint not null, tag varchar(255),
dedupe_key varchar(255), created_at bigint not null, failed_at bigint not null,
errors text not null, token text, primary key (id))
SQL;
$db->execute($jobs, []);
$db->execute($dead, []);
// The program has its own table. It saves who started each export.
$db->execute('create table exports (job text primary key, user_id integer not null)', []);
class Exports
{
// Returns the job for this string, if this user started it. Otherwise it returns `null`.
public static function find(Core\Db\Connection $db, string $text, int $user): ?Id
{
string $sql = 'select job from exports where job = ? and user_id = ?';
foreach ($db->query($sql, [$text, $user]) as Row $row) {
return Id::parse($row->string('job') ?? '');
}
return null;
}
}
// User 7 starts an export. `toString` gives the string that the program saves.
var $job = Queue::push('jobs/export.nvs', { queue: 'exports', arguments: ['table' => 'orders'] });
string $text = $job->toString();
$db->execute('insert into exports (job, user_id) values (?, ?)', [$text, 7]);
// In a later request, user 7 sends the string back. The job is found, and this prints `Pending`.
?Id $mine = Exports::find($db, $text, 7);
echo $mine != null && Queue::status($mine) == Queue::State::Pending ? 'Pending' : 'not found', "\n";
// User 8 sends the same string. The program saved it for user 7, so this prints `not found`.
?Id $other = Exports::find($db, $text, 8);
echo $other == null ? 'not found' : 'found', "\n";
// A string with a changed token finds no job. `Queue::status` throws a `RuntimeError`,
// so this prints `no such job`.
array<string> $parts = Core\Str::split($text, '.');
var $guess = Id::parse($parts[0] . '.AAAAAAAAAAAAAAAAAAAAAA.' . $parts[2]);
try {
Queue::status($guess);
echo 'found', "\n";
} catch (RuntimeError $e) {
echo 'no such job', "\n";
}
Output
Pending
not found
no such job

Send the id as json

<?nvs
// Shows a request that sends a job id and the state of its job to the browser as JSON.
use Core\Db\Row;
use Core\Queue;
use Core\Queue\Id;
// On a real server, `nvs queue migrate` creates the queue tables.
// This database is in memory, so the example creates them itself.
var $db = Core\Db::connect('jobs');
var $jobs = <<<'SQL'
create table nvs_jobs (id integer primary key autoincrement, queue varchar(255) not null,
script text not null, args text, state smallint not null, attempts integer not null,
max_attempts integer not null, backoff_ms bigint not null, run_at bigint not null,
tag varchar(255), dedupe_key varchar(255), dedupe_pending varchar(255),
created_at bigint not null, claimed_at bigint, errors text, grants text, limits text,
non_transactional smallint, token text, constraint nvs_jobs_dedupe unique (dedupe_pending))
SQL;
$db->execute($jobs, []);
$db->execute('create table exports (job text primary key, user_id integer not null)', []);
// An earlier request started an export for user 7 and saved its id.
var $job = Queue::push('jobs/export.nvs', { queue: 'exports', arguments: ['table' => 'orders'] });
$db->execute('insert into exports (job, user_id) values (?, ?)', [$job->toString(), 7]);
// In a real program, the session gives the signed-in user.
int $user = 7;
// The browser sends the id back in the query. Here the token was changed.
?Id $asked = Id::tryParse(Core\Request::queryParameter('job') ?? '');
if ($asked == null) {
Core\Response::sendJson(['error' => 'not a job id']);
} else {
// The program checks its own table before it reads the state of the job.
// No row has this id, so the state stays `unknown`.
string $state = 'unknown';
string $sql = 'select job from exports where job = ? and user_id = ?';
foreach ($db->query($sql, [$asked->toString(), $user]) as Row $row) {
$state = Queue::status($asked) == Queue::State::Pending ? 'waiting' : 'started';
}
// `toString` gives the id as JSON can send it, with no escaping.
// This sends `{"job":"1.AAAAAAAAAAAAAAAAAAAAAA.ZXhwb3J0cw","state":"unknown"}`.
Core\Response::sendJson(['job' => $asked->toString(), 'state' => $state]);
}
Output
{"job":"1.AAAAAAAAAAAAAAAAAAAAAA.ZXhwb3J0cw","state":"unknown"}