# Queue

> Queues: durable background work, delivered at least once.

```python
jobs = noclick.Queue.from_name("invoices", create_if_missing=True)
jobs.put({"invoice": "INV-1042"})

for msg in jobs.iterate(lease_s=60):
    print("Sending", msg.body["invoice"])
    msg.ack()
```

A message you take is leased to you for `lease_s` seconds: `ack()` it when
the work is done, or it comes back for another try (so handle a message twice
safely). A message that fails `max_attempts` times moves to the dead letters,
where you can retry or discard it. An agent can take the messages instead:
`triggers=[noclick.OnQueue(jobs)]` makes each one a turn.

## Queue

```typescript
class Queue
```

A durable queue of JSON messages, delivered at least once. `put` adds work; `get` and
`iterate` take it under a lease. `Queue.fromName("invoices", { createIfMissing: true })` is
lazy. There's no `Queue.get(id)`, since `get` takes a message: `Queue.fromId(id).hydrate()`.

| Attribute | Type | Description |
| --- | --- | --- |
| `id` | `string` |  |
| `name` | `string` |  |
| `depth` | `number` | Messages waiting to be taken, delayed ones included (as of the last load; `size()` reads it fresh). |
| `inFlight` | `number` | Messages leased and not yet acked. |
| `deadLetterCount` | `number` | Messages that failed `maxAttempts` times. |
| `maxAttempts` | `number` | Deliveries a message gets before it's a dead letter. |
| `usedBy` | `UsedBy[]` | Who consumes it: agents with an `OnQueue` trigger (`kind` `agent`) and apps that bind it. |
| `region` | `RegionName | null` | The region it keeps its data in, fixed when it was created. |
| `userId` | `string | null` |  |
| `createdAt` | `Date | null` |  |
| `consoleUrl` | `string | null` | This queue in the developer console (null off the hosted API). |

Types:

```typescript
/** An app that binds a database or a bucket, under its `binding` name. */
interface UsedBy {
  kind: string;
  id: string;
  name: string;
  binding: string | null;
}

type RegionName = "us-east" | "us-west" | "eu" | "ap" | "in";
```

### Queue.create

```typescript
static create(
  name: string,
  options?: QueueCreateOptions & AllowExisting,
): Promise<Queue>
```

Create a queue, unique by name per user (a taken name throws `Conflict` with `existingId`, or with
`allowExisting: true` returns the queue already there, as it is). `region` keeps its messages there
for good: `us-east` only for now (another, or a default elsewhere, throws `InvalidRequest`).

Parameters:

- `name` (`string`, required)
- `options.maxAttempts` (`number`): Deliveries a message gets before it's a dead letter (1 to 100; 5 by default).
- `options.region` (`RegionName`): Where it runs or keeps its data (`regions()`); omitted, your account's default region.
- `options.allowExisting` (`boolean`): A taken name returns the object already there, as it is: nothing about it changes.
- `options.user` (`UserOption`, default: the current user): `undefined` = the ambient user (`asUser`), `null` = the account itself.
- `options.client` (`NoClick`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.

Returns: The new queue, empty.

Types:

```typescript
/** `undefined` = the ambient user (from `asUser`), `null` = the account itself. */
type UserOption = UserRef | null | undefined;

/** A `User` or your own id for the user. */
type UserRef = string | UserLike;

/** Anything that can name a user lazily (a `User`). */
interface UserLike {
  _userId(): Promise<string>;
}

type RegionName = "us-east" | "us-west" | "eu" | "ap" | "in";
```

### Queue.fromName

```typescript
static fromName(
  name: string,
  options?: QueueCreateOptions & { createIfMissing?: boolean },
): Queue
```

A lazy reference to the queue called `name`. A `maxAttempts` you pass is set on it every run. With
`createIfMissing` it's created on first use; without it, a missing queue throws `NotFound`.

Parameters:

- `name` (`string`, required)
- `options.createIfMissing` (`boolean`)
- `options.maxAttempts` (`number`, default `null`): Deliveries a message gets before it's a dead letter (1 to 100; 5 by default).
- `options.region` (`RegionName`): Where it runs or keeps its data (`regions()`); omitted, your account's default region.
- `options.user` (`UserOption`, default: the current user): `undefined` = the ambient user (`asUser`), `null` = the account itself.
- `options.client` (`NoClick`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.

Returns: A queue that loads (or is created) on first use. Nothing is sent yet.

Types:

```typescript
/** `undefined` = the ambient user (from `asUser`), `null` = the account itself. */
type UserOption = UserRef | null | undefined;

/** A `User` or your own id for the user. */
type UserRef = string | UserLike;

/** Anything that can name a user lazily (a `User`). */
interface UserLike {
  _userId(): Promise<string>;
}

type RegionName = "us-east" | "us-west" | "eu" | "ap" | "in";
```

### Queue.fromId

```typescript
static fromId(queueId: string, options?: CallOptions): Queue
```

A lazy reference by id; `await Queue.fromId(id).hydrate()` loads it now.

Parameters:

- `queueId` (`string`, required)
- `options.client` (`NoClick`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.
- `options.user` (`UserOption`, default: the current user): `undefined` = the ambient user (`asUser`), `null` = the account itself.

Returns: A queue that loads the first time you use it. Nothing is sent yet.

Types:

```typescript
/** `undefined` = the ambient user (from `asUser`), `null` = the account itself. */
type UserOption = UserRef | null | undefined;

/** A `User` or your own id for the user. */
type UserRef = string | UserLike;

/** Anything that can name a user lazily (a `User`). */
interface UserLike {
  _userId(): Promise<string>;
}
```

### Queue.list

```typescript
static list(options?: ReadOptions & { limit?: number }): Promise<Queue[]>
```

The current user's queues (or those `userFilter` covers), newest first.

Parameters:

- `options.limit` (`number`): Return at most this many.
- `options.userFilter` (`UserFilter`): Which users the read covers (`user_id` query), instead of acting as one (`user`).
- `options.user` (`UserOption`, default: the current user): `undefined` = the ambient user (`asUser`), `null` = the account itself.
- `options.client` (`NoClick`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.

Returns: Every matching queue, newest first, fetched page by page.

Types:

```typescript
/**
 * Which users a read covers: `ALL_USERS`, `NO_USER`, a `User` or your id for one. Sent as the
 * `user_id` query parameter, never as the `NoClick-User` header, so it filters without acting as the user.
 */
type UserFilter = typeof ALL_USERS | typeof NO_USER | UserRef;

/** A `User` or your own id for the user. */
type UserRef = string | UserLike;

/** Anything that can name a user lazily (a `User`). */
interface UserLike {
  _userId(): Promise<string>;
}

/** `undefined` = the ambient user (from `asUser`), `null` = the account itself. */
type UserOption = UserRef | null | undefined;
```

### Queue.listPage

```typescript
static listPage(options?: ReadOptions & PageOptions): Promise<Page<Queue>>
```

One page of queues; pass `nextCursor` back as `cursor`.

Parameters:

- `options.cursor` (`string | null`): The `next_cursor` of the page before; omit it for the first page.
- `options.limit` (`number`): Return at most this many.
- `options.userFilter` (`UserFilter`): Which users the read covers (`user_id` query), instead of acting as one (`user`).
- `options.user` (`UserOption`, default: the current user): `undefined` = the ambient user (`asUser`), `null` = the account itself.
- `options.client` (`NoClick`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.

Returns: A page whose `data` holds the queues and whose `next_cursor` is `None` on the last page.

Types:

```typescript
/**
 * Which users a read covers: `ALL_USERS`, `NO_USER`, a `User` or your id for one. Sent as the
 * `user_id` query parameter, never as the `NoClick-User` header, so it filters without acting as the user.
 */
type UserFilter = typeof ALL_USERS | typeof NO_USER | UserRef;

/** A `User` or your own id for the user. */
type UserRef = string | UserLike;

/** Anything that can name a user lazily (a `User`). */
interface UserLike {
  _userId(): Promise<string>;
}

/** `undefined` = the ambient user (from `asUser`), `null` = the account itself. */
type UserOption = UserRef | null | undefined;
```

### Queue.update

```typescript
update(options: { maxAttempts: number }): Promise<this>
```

Change how many deliveries a message gets before it's a dead letter (1 to 100).

Parameters:

- `options.maxAttempts` (`number`, required)

Returns: This queue, with its new `max_attempts`.

### Queue.put

```typescript
put(
  body: unknown,
  options?: { delayS?: number; dedupeKey?: string },
): Promise<string>
```

Add a message (any JSON, up to 256 KB), hidden for `delayS` seconds (up to 7 days). Its id.
`dedupeKey` (up to 128 characters) makes the put safe to repeat: for 24 hours another put with
the same key adds nothing and returns the first message's id.

Parameters:

- `body` (`unknown`, required)
- `options.delayS` (`number`)
- `options.dedupeKey` (`string`)

Returns: The new message's id (the first one's, for a repeated `dedupe_key`).

### Queue.putMany

```typescript
putMany(
  bodies: readonly unknown[],
  options?: { delayS?: number },
): Promise<string[]>
```

Add up to 100 messages in one call, all or none. Their ids, in order.

Parameters:

- `bodies` (`readonly unknown[]`, required)
- `options.delayS` (`number`)

Returns: The new messages' ids, in the order you gave them.

### Queue.get

```typescript
get(
  options?: { timeoutS?: number; leaseS?: number },
): Promise<QueueMessage | null>
```

Take the next message, waiting up to `timeoutS` seconds (at most 60; 0 by default) for one.
It's leased for `leaseS` seconds (60 by default, up to 12 hours). Null if none arrived.

Parameters:

- `options.timeoutS` (`number`, default `0`)
- `options.leaseS` (`number`, default `60`)

Returns: The message, or `None` if none arrived in time.

### Queue.iterate

```typescript
async *iterate(
  options?: { leaseS?: number; signal?: AbortSignal; stopWhenEmpty?: boolean },
): AsyncGenerator<QueueMessage>
```

Take messages as they arrive, each leased for `leaseS`; long-polls until you `break` or `signal`
aborts. With `stopWhenEmpty` it ends instead the first time nothing is waiting (messages leased
to someone else, or delayed, don't keep it going), to drain a queue in a batch job.

Parameters:

- `options.leaseS` (`number`, default `60`)
- `options.stopWhenEmpty` (`boolean`)
- `options.signal` (`AbortSignal`)

Returns: Each message as it's taken. Without `stop_when_empty` it never ends on its own, so `break` when you're done.

### Queue.size

```typescript
size(): Promise<number>
```

How many messages wait (delayed included; leased and dead letters not), read now.

Returns: The queue's depth.

### Queue.peek

```typescript
peek(options?: { limit?: number }): Promise<QueueMessage[]>
```

The oldest messages, waiting and in flight, without taking them (nothing is leased).

Parameters:

- `options.limit` (`number`, default `10`): Return at most this many.

Returns: Up to `limit` (at most 100) messages, with their `status` and `attempts`.

### Queue.deadLetters

```typescript
deadLetters(options?: { limit?: number }): Promise<QueueMessage[]>
```

The messages that failed `maxAttempts` times, newest first; kept 14 days.

Parameters:

- `options.limit` (`number`): Return at most this many.

Returns: Every dead letter (or the first `limit`), fetched page by page.

### Queue.depthHistory

```typescript
depthHistory(options?: { hours?: number }): Promise<QueueDepth[]>
```

How deep the queue has been over the last `hours` (24 by default, up to 168), a point every 15 minutes.

Parameters:

- `options.hours` (`number`, default `24`)

Returns: A `QueueDepth` (`at`, `depth`, `in_flight`) per point, oldest first.

### Queue.clear

```typescript
clear(): Promise<void>
```

Drop every waiting message and every dead letter; messages in flight finish as usual.

### Queue.export

```typescript
export(): Promise<Operation<ExportBundle>>
```

Export every message as it stands at one moment, dead letters included, as JSON Lines: one per
line, oldest first, with its `status` (`waiting`, `delayed`, `in_flight` or `dead`), `attempts`
and `body`. `wait()` resolves to an `ExportBundle`: a zip at `url` holding the file.

Returns: An operation whose `wait()` gives an `ExportBundle`: a zip at `url` holding the files.

### Queue.delete

```typescript
delete(): Promise<TrashItem>
```

Delete the queue and its messages: it goes to the trash, restorable for 30 days. One an app binds
or an `OnQueue` trigger reads throws `Conflict`. Returns its `TrashItem`.

Returns: Its `TrashItem`: `restore()` puts it back, messages and all.

## QueueMessage

```typescript
class QueueMessage
```

One message on a queue. A message you took with `get` or `iterate` is leased to you until
`leaseExpiresAt`: `ack()` when done, `nack()` to hand it back now as a failed try, `release()` to
hand it back without spending one. A dead letter (from
`deadLetters()`) says why its last attempt failed in `lastError`; `retry()` puts it back and
`discard()` deletes it.

| Attribute | Type | Description |
| --- | --- | --- |
| `id` | `string` |  |
| `queueId` | `string` |  |
| `body` | `unknown` | The message as you put it: JSON. |
| `status` | `QueueMessageStatus` | `waiting`, `delayed`, `in_flight` or `dead`. |
| `attempts` | `number` | How many times it has been delivered, this delivery included. |
| `enqueuedAt` | `Date | null` |  |
| `visibleAt` | `Date | null` | When a delayed message can first be taken (null once it can). |
| `leaseExpiresAt` | `Date | null` | When your lease ends and the message goes back (null unless you hold it). |
| `lastError` | `string | null` | Why its last attempt failed (null if none has). |
| `deadLetteredAt` | `Date | null` | When it became a dead letter (null unless it is one). |

Types:

```typescript
type QueueMessageStatus = "waiting" | "delayed" | "in_flight" | "dead";
```

### QueueMessage.ack

```typescript
ack(): Promise<void>
```

Mark it done: deleted, never delivered again. A late ack (the lease ran out) throws `Conflict`.

### QueueMessage.nack

```typescript
nack(options?: { delayS?: number; error?: string }): Promise<void>
```

Hand it back for another try after `delayS` seconds; it counts as an attempt. `error` (up to
2 KB) says why: it's the message's `lastError`, which a dead letter keeps.

Parameters:

- `options.delayS` (`number`)
- `options.error` (`string`)

### QueueMessage.release

```typescript
release(options?: { delayS?: number }): Promise<void>
```

Hand it back untouched after `delayS` seconds without spending an attempt (`attempts` goes back,
`lastError` stays): for a failure that isn't the message's, like an account out of money, so a
backlog doesn't burn its tries. It keeps coming back until the cause is fixed.

Parameters:

- `options.delayS` (`number`)

### QueueMessage.retry

```typescript
retry(): Promise<void>
```

Put a dead letter back on the queue, with its attempts reset.

### QueueMessage.discard

```typescript
discard(): Promise<void>
```

Delete a dead letter for good.

## QueueDepth

```typescript
interface QueueDepth
```

How full a queue was at one moment.

| Attribute | Type | Description |
| --- | --- | --- |
| `at` | `Date | null` |  |
| `depth` | `number` |  |
| `inFlight` | `number` |  |
