SHADE is young: 0.1.0-next.2 is a pre-release, and 0.1.0 isn't out yet.

SHADE
Developers

kv: a module's own key-value storage

Every module, trusted or untrusted, can keep its own keys and counters: kv. A trusted module calls moduleKv(ctx) from the module SDK; an untrusted one calls shade.kv in the sandbox. Both reach the same service in core, with the same checks and the same quotas. Keys are records: they live in Postgres (module_kv), are in the backup, and an account's keys are found, exported and erased with their account.

Declaring it

kv is a capability (see Capabilities). Declare it with what it keeps:

export default defineModule({
  name: 'readme-cards',
  // …
  capabilities: {
    kv: {
      data: { purpose: 'readmeCards.keeps', personal: 'none' },  // a key of the module's own texts
      maxKeys: 20_000,                                          // default 10 000, at most 100 000
      maxValueBytes: 64 * 1024                                  // default 256 KB, at most 1 MB
    }
  }
})
  • data.personal says whether it keeps anything about a person: none, account (keys for an account, through forAccount) or person (other personal data, which needs a source named kv in the module's personalData).
  • Unless it is none, data.retention names one of the module's own retention kinds (its retention part). Keys not written within that kind's period are deleted (see Retention below).
  • need: 'optional' makes it a switch an admin turns on; until then every call is refused.
  • The consent shows the quotas in words ("at most 20000 keys", "values of at most 64 KB") and what it keeps. An update that raises a quota, starts keeping data about a person or changes the retention kind asks again.
  • Untrusted modules keep nothing about a person in kv: their data.personal must be none (they have no account routes to scope keys to an account, and no retention or personal data parts to declare it with).

A trusted module: moduleKv(ctx)

import { moduleKv } from '@shadestack/module-sdk/server'

// In a route, hook or schedule: the context SHADE gave the module's code.
const kv = moduleKv(ctx)

await kv.set('card:octocat', { stars: 120, at: new Date().toISOString() })
const card = await kv.get<{ stars: number, at: string }>('card:octocat')   // null when missing or expired

await kv.set('session:abc', { step: 2 }, { ttlMs: 30 * 60_000 })           // expires after 30 minutes
const views = await kv.increment('views')                                  // 1, 2, 3 … atomically
await kv.increment('stock:mug', -1)                                        // counts down too

const page = await kv.list({ prefix: 'card:', limit: 50 })                 // { keys: [{ key, updatedAt }], cursor }
const next = page.cursor ? await kv.list({ prefix: 'card:', cursor: page.cursor }) : null

await kv.delete('card:octocat')
MethodWhat it does
get(key)The value, or a counter's count; null for a key that is not there or has expired.
set(key, value, { ttlMs?, ifUnchanged? })Stores what JSON keeps of value (a Date becomes its text). ttlMs (1 second to 366 days) makes it expire. Replaces a counter. With ifUnchanged, only while the key still holds that value as get gave it (null: while it is not there); CONFLICT (kv.errors.changed) otherwise.
delete(key)Removes the key; nothing happens when it isn't there.
list({ prefix?, limit?, cursor? })Keys starting with prefix, in key order, at most limit (default 100, at most 1000), with updatedAt; cursor is the last key of the page when there are more. _ and % are plain characters.
increment(key, by = 1)Adds a whole number to a counter in one atomic statement and returns the new count. A missing or expired key starts at by. CONFLICT on a key that holds a value.
forAccount(accountId)The same methods for one account's keys (below).
  • A list or map kept in one key is changed by read, change, write. Two calls doing that at once lose one change, unless the write says what it read: set(key, next, { ifUnchanged: before }). A refused write reads again and redoes its change:
    for (;;) {
      const tags = await kv.get<string[]>('tags')
      try {
        await kv.set('tags', [...(tags ?? []), 'new'], { ifUnchanged: tags })
        break
      } catch (error) {
        if ((error as { code?: string }).code !== 'CONFLICT') throw error
      }
    }
    

    A counter needs none of this: increment is atomic.
  • Keys are texts of 1 to 200 characters without control characters.
  • Errors are SHADE's own: VALIDATION (a key, value or option it doesn't take, a value over maxValueBytes), CONFLICT ("The module's kv is full (20000 keys)", a value where a counter is asked for), FORBIDDEN (no kv capability), NOT_FOUND (forAccount with an id that is no account).
  • The module is the one SHADE made the context for (moduleOfContext). Setting ctx.plugin, or copying the context, never reaches another module's keys; a context SHADE didn't make for a module is refused.
  • Every call checks the capability first, so switching an optional kv off stops it at once.

An account's keys: forAccount

// In an account route (`auth: 'account'`): the signed-in account is request.account (request.account after the accounts pull request).
const cart = moduleKv(ctx).forAccount(request.account!.id)
await cart.set('cart', [{ product: 'mug', quantity: 2 }])
await cart.increment('visits')
  • Declare data: { personal: 'account', retention: '<kind>' }.
  • An account's keys are apart from the module's own and from every other account's: moduleKv(ctx).list() never shows them.
  • They are found and exported on the Personal data screen and in the account's own download, erased with the person, and deleted when the account is deleted, by an admin or by the account (see Personal data per person (shade/features/privacy/README.md in the shade repository)).
  • They count toward the module's maxKeys.

An untrusted module: shade.kv

import { connect } from 'shade'

export default {
  async fetch(request, env) {
    const shade = connect(env)
    const views = await shade.kv.increment('views')
    await shade.kv.set('last-visit', new Date().toISOString(), { ttlMs: 86_400_000 })
    const page = await shade.kv.list({ prefix: 'card:' }) // as a trusted module's: { keys, cursor }
    return Response.json({ views, keys: page.keys })
  }
}

get, set(key, value, { ttlMs, ifUnchanged }), delete, list({ prefix, limit, cursor }) and increment(key, by) go through the bridge (kv.*) to the same service, as the module itself. A sandbox package built before the declaration keeps kv with today's limits (10 000 keys of 256 KB). A refused call answers with the error's code (FORBIDDEN, CONFLICT, VALIDATION) and is counted for the module like any capability refusal.

Retention and uninstalling

  • Expired keys read as missing at once. The core schedule kv.purge, on the worker container role every 15 minutes, deletes them.
  • Keys past their retention: for a module whose kv names a retention kind, the same schedule deletes the keys not written within the kind's period (by updated_at), also while the module is off, with an audit entry (retention.purge, target <plugin>.<kind>). The kind still has its own purge, which may delete nothing: { key: 'carts', label: 'shop.retention.carts', defaultDays: 30, minDays: 1, purge: async () => 0 }.
  • Without a retention kind (personal: 'none'), keys stay until the module deletes them or is uninstalled.
  • Uninstalling a trusted module backs its keys up with its data (module_backups, table module_kv) and deletes them. Removing an untrusted module deletes them; Export saves them first.

Where it is

PartWhat
shade/features/kv/server/kv.tsmoduleKv(ctx), ModuleKv, KvValue, the quotas' defaults; kvOfAccounts, forgetKvOfAccounts, kvRowsOf, forgetKv for privacy and uninstalling.
shade/features/kv/server/manifest.tsThe kv capability's definition (kvCapability, KvParamsSchema) and its privacy entry (registerKvPrivacy), registered when shade/exports/manifest-parts.ts loads it.
shade/features/kv/server/purge.tsKV_PURGE_SCHEDULE (kv.purge, expired keys: purgeKvKeys, purgeExpiredKv); purgeKv, registered with retention for the keys a retention kind limits.
shade/features/kv/server/kv.sql.tsmodule_kv (moduleKvData): module, key, account_id, value (jsonb), counter (bigint), expires_at, updated_at; primary key module and key. An account's key is stored as \u001f<account id>\u001f<key>.
shade/kernel/modules/capabilities.tsrequireCapability(ctx, 'kv'): refuses a module without it and gives the parameters agreed to (the module manager's activeCapabilityParams).
shade/features/privacy/server/privacy.tsregisterAccountData, registerAccountDirectory, eraseAccountData: data kept by account id.
shade/features/packages/server/untrusted.tsThe bridge's kv.* (sandboxCall, kvCall).
apps/api/src/sandbox/workers.tsThe shade module's kv.

How it works:

  • A new key is added in a transaction under a lock per module, after counting the module's keys, so writes at the same moment never pass maxKeys. Expired keys are deleted first when the module is full. Changing a key it has needs no lock.
  • increment on a counter is one UPDATE … SET counter = counter + $by; a new counter is an INSERT … ON CONFLICT DO UPDATE, so increments at the same moment all count.
  • Redis holds nothing of kv. It may later speed up counters and expiry, rebuilt from the table.
  • Untrusted modules' keys were in uploaded_plugin_data until migration 0010_kv_uploaded_plugin_data_into_plugin_kv moved every row into module_kv (same module and key, value and time) and dropped the old table.

Tests

  • shade/test/features/kv/server/kv.test.ts (Postgres):
    • get, set, delete, list and increment for a trusted module, and a key that expires;
    • "counts atomically under concurrent increments", from a trusted module and through the bridge;
    • "keeps to its quota": ten new keys at once for five places keep five; a value over its limit; an account's keys counting; an untrusted module held to its own declaration;
    • "checks the kv capability on every call, for both kinds of module": not declared, optional and off, core's own context, and refusals counted for an untrusted module;
    • "keeps one module from another's keys": two trusted and two untrusted modules with the same keys, a forged ctx.plugin, accounts' keys apart from each other and from the module's own;
    • "exports and erases an account's keys with the account": the privacy lookup, the erase, an admin deleting the account;
    • "purges by the declared retention kind", following the admin's period;
    • uninstalling backs the keys up, then deletes them;
    • the migration moving uploaded_plugin_data into module_kv with each row's module and key.
  • apps/api/test/sandbox/host.test.ts: "gives an untrusted module kv.increment only with the kv capability, atomically", in real workerd.
  • shade/test/kernel/modules/capabilities.test.ts: kv for both kinds, its quotas' limits, and untrusted modules keeping nothing about a person.
  • shade/test/features/accounts/server/accounts.test.ts: an account deleting their own account deletes their keys.
  • apps/api/test/bootstrap/worker.test.ts: kv.purge runs on the worker every 15 minutes.