A client whose only link was voided while current must not count the animal; B linking its own animal to a client of A must not wait on A's lock. Also a relation create racing the archive of its animal, and a replay changing the initial relation's role.
861 lines
30 KiB
TypeScript
861 lines
30 KiB
TypeScript
/**
|
|
* V1-1.4 animals and relations (M3) on the real stack of `pnpm db:sandbox`:
|
|
* RPCs through PostgREST with real sessions per role, identical refusals, no
|
|
* lock taken outside the caller's workspace, then concurrent writes (replays,
|
|
* identical relations, end and void races, caps, the budget shared with the
|
|
* clients, relation creates against archives, a mixed burst across M2 and
|
|
* M3 without deadlock), the D9a guard through GoTrue admin, and timings.
|
|
* Contract: docs/development/V1-1_OWNERS_ANIMALS.md §5.3, §7.1, §9, §10, §12.
|
|
*/
|
|
import { randomUUID } from 'node:crypto'
|
|
import {
|
|
adminDeleteUser,
|
|
confirmedAccount,
|
|
errorCode,
|
|
rest,
|
|
rpc,
|
|
sql,
|
|
stack,
|
|
type Account,
|
|
type RestResult,
|
|
} from './stack'
|
|
|
|
const workspaceOf = (userId: string) =>
|
|
sql(`select id from public.workspaces where personal_user_id = '${userId}'`)
|
|
const budgetOf = (ws: string) =>
|
|
sql(
|
|
`select coalesce((select hour_count || '/' || day_count from private.workspace_write_budgets where workspace_id = '${ws}'), 'none')`,
|
|
)
|
|
const idOf = (result: RestResult) => (result.body as { id: string }).id
|
|
const messageOf = (result: RestResult) =>
|
|
result.status === 200 ? 'ok' : (result.body as { message: string }).message
|
|
/** The error as the client sees it: status, code, message, details, hint. */
|
|
const shape = (result: RestResult) => {
|
|
const body = result.body as Record<string, unknown>
|
|
return [
|
|
result.status,
|
|
body.code,
|
|
body.message,
|
|
body.details ?? null,
|
|
body.hint ?? null,
|
|
]
|
|
}
|
|
const NOT_FOUND = [403, '42501', 'not_found', null, null]
|
|
|
|
function createClient(account: Account, ws: string, displayName: string) {
|
|
return rpc(
|
|
'create_client',
|
|
{
|
|
workspace_id: ws,
|
|
create_request_id: randomUUID(),
|
|
kind: 'person',
|
|
display_name: displayName,
|
|
},
|
|
account.token,
|
|
)
|
|
}
|
|
function createAnimal(
|
|
account: Account,
|
|
ws: string,
|
|
fields: Record<string, unknown>,
|
|
requestId = randomUUID(),
|
|
) {
|
|
return rpc(
|
|
'create_animal',
|
|
{
|
|
workspace_id: ws,
|
|
create_request_id: requestId,
|
|
species_id: 'equine',
|
|
sex: 'unknown',
|
|
...fields,
|
|
},
|
|
account.token,
|
|
)
|
|
}
|
|
function link(
|
|
account: Account,
|
|
animalId: string,
|
|
clientId: string,
|
|
relationRole = 'owner',
|
|
requestId = randomUUID(),
|
|
) {
|
|
return rpc(
|
|
'create_animal_client_relation',
|
|
{
|
|
animal_id: animalId,
|
|
client_id: clientId,
|
|
create_request_id: requestId,
|
|
relation_role: relationRole,
|
|
},
|
|
account.token,
|
|
)
|
|
}
|
|
const animalUpdate = (animalId: string, revision: number, name: string) => ({
|
|
animal_id: animalId,
|
|
expected_revision: revision,
|
|
name,
|
|
species_id: 'equine',
|
|
sex: 'unknown',
|
|
species_detail: null,
|
|
breed: null,
|
|
birth_year: null,
|
|
birth_date: null,
|
|
})
|
|
|
|
describe('animals and relations through PostgREST, per role', () => {
|
|
let a: Account
|
|
let b: Account
|
|
let wA: string
|
|
let marie: string
|
|
let eclair: string
|
|
let relation: string
|
|
|
|
beforeAll(async () => {
|
|
a = await confirmedAccount('an-a')
|
|
b = await confirmedAccount('an-b')
|
|
wA = await workspaceOf(a.id)
|
|
marie = idOf(await createClient(a, wA, 'Marie Dupont'))
|
|
const created = await createAnimal(a, wA, {
|
|
name: 'Éclair',
|
|
sex: 'male',
|
|
breed: 'Selle Français',
|
|
birth_year: '2015',
|
|
birth_date: '2015-04-12',
|
|
client_id: marie,
|
|
relation_role: 'owner',
|
|
started_on: '2020-01-01',
|
|
})
|
|
expect(created.status).toBe(200)
|
|
eclair = idOf(created)
|
|
relation = (created.body as { relation_id: string }).relation_id
|
|
})
|
|
|
|
it('A creates, reads by id, searches, lists and changes a relation', async () => {
|
|
expect(
|
|
(
|
|
await rest(
|
|
`/animals?select=id,name,species_id,sex,birth_year,birth_date,revision&id=eq.${eclair}`,
|
|
a.token,
|
|
)
|
|
).body,
|
|
).toEqual([
|
|
{
|
|
id: eclair,
|
|
name: 'Éclair',
|
|
species_id: 'equine',
|
|
sex: 'male',
|
|
birth_year: 2015,
|
|
birth_date: '2015-04-12',
|
|
revision: 1,
|
|
},
|
|
])
|
|
expect(
|
|
(
|
|
await rest(
|
|
`/animal_client_relations?select=client_id,relation_role,started_on,ended_at,voided_at&animal_id=eq.${eclair}`,
|
|
a.token,
|
|
)
|
|
).body,
|
|
).toEqual([
|
|
{
|
|
client_id: marie,
|
|
relation_role: 'owner',
|
|
started_on: '2020-01-01',
|
|
ended_at: null,
|
|
voided_at: null,
|
|
},
|
|
])
|
|
const found = await rpc(
|
|
'search_animals',
|
|
{ workspace_id: wA, query: 'francais' },
|
|
a.token,
|
|
)
|
|
expect(found.body).toMatchObject([
|
|
{
|
|
id: eclair,
|
|
current_owner_count: 1,
|
|
current_owners: [
|
|
{ client_id: marie, display_name: 'Marie Dupont', archived: false },
|
|
],
|
|
},
|
|
])
|
|
expect(
|
|
(
|
|
await rpc(
|
|
'search_clients',
|
|
{ workspace_id: wA, query: 'marie' },
|
|
a.token,
|
|
)
|
|
).body,
|
|
).toMatchObject([{ id: marie, current_animal_count: 1 }])
|
|
expect(
|
|
(await rpc('list_client_animals', { client_id: marie }, a.token)).body,
|
|
).toMatchObject([
|
|
{ relation_id: relation, animal_id: eclair, is_current: true },
|
|
])
|
|
expect(
|
|
(await rpc('client_archive_preview', { client_id: marie }, a.token)).body,
|
|
).toEqual({ count: 1, animals: [{ id: eclair, name: 'Éclair' }] })
|
|
expect(
|
|
(
|
|
await rpc(
|
|
'end_animal_client_relation',
|
|
{ relation_id: relation, expected_revision: 1, ended_on: null },
|
|
a.token,
|
|
)
|
|
).body,
|
|
).toEqual({ revision: 2 })
|
|
expect(
|
|
(
|
|
await rpc(
|
|
'update_animal_client_relation',
|
|
{
|
|
relation_id: relation,
|
|
expected_revision: 2,
|
|
started_on: '2020-01-01',
|
|
ended_on: '2024-06-30',
|
|
},
|
|
a.token,
|
|
)
|
|
).body,
|
|
).toEqual({ revision: 3 })
|
|
expect(
|
|
(await rpc('list_client_animals', { client_id: marie }, a.token)).body,
|
|
).toMatchObject([{ relation_id: relation, is_current: false }])
|
|
})
|
|
|
|
it('B gets nothing of A, and the same refusal as for an unknown id on every write', async () => {
|
|
expect(
|
|
(await rest(`/animals?select=id&id=eq.${eclair}`, b.token)).body,
|
|
).toEqual([])
|
|
const head = await rest(
|
|
`/animal_client_relations?select=id&workspace_id=eq.${wA}`,
|
|
b.token,
|
|
{ method: 'HEAD', headers: { Prefer: 'count=exact' } },
|
|
)
|
|
expect(head.headers.get('content-range')).toBe('*/0')
|
|
for (const [fn, args] of [
|
|
['search_animals', { workspace_id: wA }],
|
|
['list_client_animals', { client_id: marie }],
|
|
] as const) {
|
|
expect((await rpc(fn, args, b.token)).body).toEqual([])
|
|
}
|
|
expect(
|
|
(await rpc('client_archive_preview', { client_id: marie }, b.token)).body,
|
|
).toEqual({ count: 0, animals: [] })
|
|
const pairs: [string, Record<string, unknown>, Record<string, unknown>][] =
|
|
[
|
|
[
|
|
'update_animal',
|
|
animalUpdate(eclair, 1, 'X'),
|
|
animalUpdate(randomUUID(), 1, 'X'),
|
|
],
|
|
[
|
|
'set_animal_archived',
|
|
{ animal_id: eclair, archived: true },
|
|
{ animal_id: randomUUID(), archived: true },
|
|
],
|
|
[
|
|
'end_animal_client_relation',
|
|
{ relation_id: relation, expected_revision: 3, ended_on: null },
|
|
{ relation_id: randomUUID(), expected_revision: 3, ended_on: null },
|
|
],
|
|
[
|
|
'update_animal_client_relation',
|
|
{
|
|
relation_id: relation,
|
|
expected_revision: 3,
|
|
started_on: null,
|
|
ended_on: null,
|
|
},
|
|
{
|
|
relation_id: randomUUID(),
|
|
expected_revision: 3,
|
|
started_on: null,
|
|
ended_on: null,
|
|
},
|
|
],
|
|
[
|
|
'void_animal_client_relation',
|
|
{ relation_id: relation, expected_revision: 3 },
|
|
{ relation_id: randomUUID(), expected_revision: 3 },
|
|
],
|
|
[
|
|
'create_animal_client_relation',
|
|
{
|
|
animal_id: eclair,
|
|
client_id: marie,
|
|
create_request_id: randomUUID(),
|
|
relation_role: 'keeper',
|
|
},
|
|
{
|
|
animal_id: randomUUID(),
|
|
client_id: marie,
|
|
create_request_id: randomUUID(),
|
|
relation_role: 'keeper',
|
|
},
|
|
],
|
|
]
|
|
for (const [fn, foreign, unknown] of pairs) {
|
|
const x = await rpc(fn, foreign, b.token)
|
|
const y = await rpc(fn, unknown, b.token)
|
|
expect([fn, ...shape(x)]).toEqual([fn, ...shape(y)])
|
|
expect([fn, ...shape(x)]).toEqual([fn, ...NOT_FOUND])
|
|
}
|
|
const wB = await workspaceOf(b.id)
|
|
const bAnimal = idOf(await createAnimal(b, wB, { name: 'Animal B' }))
|
|
expect(shape(await link(b, bAnimal, marie))).toEqual(NOT_FOUND)
|
|
expect(
|
|
shape(
|
|
await createAnimal(b, wB, {
|
|
name: 'X',
|
|
client_id: marie,
|
|
relation_role: 'owner',
|
|
}),
|
|
),
|
|
).toEqual(NOT_FOUND)
|
|
expect(shape(await createAnimal(b, wA, { name: 'X' }))).toEqual(NOT_FOUND)
|
|
})
|
|
|
|
it('refuses direct writes, the anon key and the service key; error bodies carry no value', async () => {
|
|
const attempts: [string, string, RequestInit, number][] = [
|
|
[
|
|
'/animals',
|
|
a.token,
|
|
{
|
|
method: 'POST',
|
|
body: JSON.stringify({
|
|
workspace_id: wA,
|
|
name: 'Direct',
|
|
species_id: 'equine',
|
|
sex: 'male',
|
|
}),
|
|
},
|
|
403,
|
|
],
|
|
[
|
|
`/animals?id=eq.${eclair}`,
|
|
a.token,
|
|
{ method: 'PATCH', body: JSON.stringify({ workspace_id: wA }) },
|
|
403,
|
|
],
|
|
[`/animals?id=eq.${eclair}`, a.token, { method: 'DELETE' }, 403],
|
|
[
|
|
`/animal_client_relations?id=eq.${relation}`,
|
|
a.token,
|
|
{ method: 'PATCH', body: JSON.stringify({ voided_at: null }) },
|
|
403,
|
|
],
|
|
[
|
|
`/animal_client_relations?id=eq.${relation}`,
|
|
a.token,
|
|
{ method: 'DELETE' },
|
|
403,
|
|
],
|
|
['/animals?select=id', stack.anonKey, {}, 401],
|
|
[
|
|
'/rpc/search_animals',
|
|
stack.anonKey,
|
|
{ method: 'POST', body: JSON.stringify({ workspace_id: wA }) },
|
|
401,
|
|
],
|
|
['/animal_client_relations?select=id', stack.serviceKey, {}, 403],
|
|
[
|
|
'/rpc/void_animal_client_relation',
|
|
stack.serviceKey,
|
|
{
|
|
method: 'POST',
|
|
body: JSON.stringify({ relation_id: relation, expected_revision: 3 }),
|
|
},
|
|
403,
|
|
],
|
|
[
|
|
'/rpc/lock_relation_for_write',
|
|
a.token,
|
|
{
|
|
method: 'POST',
|
|
body: JSON.stringify({
|
|
p_relation_id: relation,
|
|
p_expected_revision: 3,
|
|
}),
|
|
},
|
|
404,
|
|
],
|
|
]
|
|
for (const [path, token, init, status] of attempts) {
|
|
const result = await rest(path, token, init)
|
|
expect([path, result.status]).toEqual([path, status])
|
|
if (status !== 404) expect(errorCode(result)).toBe('42501')
|
|
expect(result.text).not.toContain('Éclair')
|
|
}
|
|
const invalid = await createAnimal(a, wA, {
|
|
name: 'Secret-Name-Value',
|
|
birth_year: '2015',
|
|
birth_date: '2015-02-30',
|
|
})
|
|
expect(shape(invalid)).toEqual([400, 'P0001', 'invalid_input', null, null])
|
|
expect(invalid.text).not.toMatch(/Secret-Name|2015-02-30/)
|
|
})
|
|
|
|
it('cuts a deactivated or unconfirmed account', async () => {
|
|
await sql(`update public.profiles set active = false where id = '${a.id}'`)
|
|
expect((await rest('/animals?select=id', a.token)).body).toEqual([])
|
|
expect(
|
|
shape(
|
|
await rpc(
|
|
'set_animal_archived',
|
|
{ animal_id: eclair, archived: true },
|
|
a.token,
|
|
),
|
|
),
|
|
).toEqual(NOT_FOUND)
|
|
await sql(`update public.profiles set active = true where id = '${a.id}'`)
|
|
await sql(
|
|
`update auth.users set email_confirmed_at = null where id = '${a.id}'`,
|
|
)
|
|
expect(
|
|
(await rest('/animal_client_relations?select=id', a.token)).body,
|
|
).toEqual([])
|
|
await sql(
|
|
`update auth.users set email_confirmed_at = now() where id = '${a.id}'`,
|
|
)
|
|
expect((await rest('/animals?select=id', a.token)).body).toEqual([
|
|
{ id: eclair },
|
|
])
|
|
})
|
|
|
|
it('a caller outside the workspace never waits on its locks', async () => {
|
|
const bAnimal = idOf(
|
|
await createAnimal(b, await workspaceOf(b.id), { name: 'Lock probe' }),
|
|
)
|
|
const holder = sql(`begin;
|
|
select 1 from public.clients where id = '${marie}' for update;
|
|
select 1 from public.animals where id = '${eclair}' for update;
|
|
select 1 from public.animal_client_relations where id = '${relation}' for update;
|
|
select pg_sleep(2); commit;`)
|
|
await new Promise((resolve) => setTimeout(resolve, 300))
|
|
const started = Date.now()
|
|
const results = await Promise.all([
|
|
rpc('update_animal', animalUpdate(eclair, 1, 'X'), b.token),
|
|
rpc(
|
|
'void_animal_client_relation',
|
|
{ relation_id: relation, expected_revision: 3 },
|
|
b.token,
|
|
),
|
|
link(b, eclair, marie, 'contact'),
|
|
link(b, bAnimal, marie, 'contact'),
|
|
])
|
|
const elapsed = Date.now() - started
|
|
await holder
|
|
expect(results.map(shape)).toEqual(Array(4).fill(NOT_FOUND))
|
|
expect(elapsed).toBeLessThan(1000)
|
|
console.log(
|
|
`[measure] A's client, animal and relation locked 2 s: B's four refusals answered in ${elapsed} ms`,
|
|
)
|
|
})
|
|
|
|
it('hides animal and relation audit rows from the platform owner (N9)', async () => {
|
|
expect(
|
|
Number(
|
|
await sql(
|
|
`select count(*) from audit.audit_logs where resource_id in ('${eclair}', '${relation}')`,
|
|
),
|
|
),
|
|
).toBe(4)
|
|
const ownerId = await sql(
|
|
`select id from auth.users where email = 'owner@faunosteo.local'`,
|
|
)
|
|
const asOwner = await sql(`begin; set local role authenticated;
|
|
select set_config('request.jwt.claims', '{"sub":"${ownerId}","role":"authenticated"}', true);
|
|
select count(*) from audit.audit_logs where resource_id in ('${eclair}', '${relation}'); commit;`)
|
|
expect(asOwner.split('\n').pop()).toBe('0')
|
|
})
|
|
|
|
it('D9a: GoTrue admin cannot delete an account whose workspace holds an animal', async () => {
|
|
const g = await confirmedAccount('an-d9a')
|
|
const wG = await workspaceOf(g.id)
|
|
expect((await createAnimal(g, wG, { name: 'Seul' })).status).toBe(200)
|
|
expect(await adminDeleteUser(g.id)).not.toBe(200)
|
|
expect(
|
|
await sql(
|
|
`select (select count(*) from auth.users where id = '${g.id}') || '/' ||
|
|
(select count(*) from public.profiles where id = '${g.id}') || '/' ||
|
|
(select count(*) from public.animals where workspace_id = '${wG}')`,
|
|
),
|
|
).toBe('1/1/1')
|
|
})
|
|
})
|
|
|
|
describe('concurrent writes', () => {
|
|
let a: Account
|
|
let wA: string
|
|
let clients: string[]
|
|
|
|
beforeAll(async () => {
|
|
a = await confirmedAccount('an-race')
|
|
wA = await workspaceOf(a.id)
|
|
clients = []
|
|
for (let i = 0; i < 24; i++)
|
|
clients.push(idOf(await createClient(a, wA, `Race client ${i}`)))
|
|
})
|
|
|
|
it('one create_animal request sent 8 times at once: one animal, one relation, two writes counted', async () => {
|
|
const before = Number((await budgetOf(wA)).split('/')[0])
|
|
const requestId = randomUUID()
|
|
const results = await Promise.all(
|
|
Array.from({ length: 8 }, () =>
|
|
createAnimal(
|
|
a,
|
|
wA,
|
|
{ name: 'Replayed', client_id: clients[0], relation_role: 'owner' },
|
|
requestId,
|
|
),
|
|
),
|
|
)
|
|
expect(results.map((r) => r.status)).toEqual(Array(8).fill(200))
|
|
expect(new Set(results.map((r) => JSON.stringify(r.body))).size).toBe(1)
|
|
expect(
|
|
await sql(
|
|
`select (select count(*) from public.animals where create_request_id = '${requestId}') || '/' ||
|
|
(select count(*) from public.animal_client_relations where create_request_id = '${requestId}')`,
|
|
),
|
|
).toBe('1/1')
|
|
expect(Number((await budgetOf(wA)).split('/')[0])).toBe(before + 2)
|
|
})
|
|
|
|
it('two contents racing on one request id: one created, the other refused', async () => {
|
|
const requestId = randomUUID()
|
|
const results = await Promise.all([
|
|
createAnimal(a, wA, { name: 'Racer X' }, requestId),
|
|
createAnimal(a, wA, { name: 'Racer Y' }, requestId),
|
|
])
|
|
expect(results.map(messageOf).sort()).toEqual(['ok', 'request_conflict'])
|
|
})
|
|
|
|
it('10 identical relations at once (distinct request ids): one row, nine duplicate_relation', async () => {
|
|
const animal = idOf(await createAnimal(a, wA, { name: 'Dup target' }))
|
|
const results = await Promise.all(
|
|
Array.from({ length: 10 }, () => link(a, animal, clients[1], 'keeper')),
|
|
)
|
|
const messages = results.map(messageOf)
|
|
expect(messages.filter((m) => m === 'ok')).toHaveLength(1)
|
|
expect(messages.filter((m) => m === 'duplicate_relation')).toHaveLength(9)
|
|
expect(
|
|
await sql(
|
|
`select count(*) from public.animal_client_relations where animal_id = '${animal}'`,
|
|
),
|
|
).toBe('1')
|
|
})
|
|
|
|
it('end and void racing on one revision: exactly one applies, the relation is ended or voided, never both', async () => {
|
|
for (let round = 0; round < 6; round++) {
|
|
const animal = idOf(
|
|
await createAnimal(a, wA, { name: `End-void ${round}` }),
|
|
)
|
|
const relation = idOf(await link(a, animal, clients[2]))
|
|
const results = await Promise.all([
|
|
rpc(
|
|
'end_animal_client_relation',
|
|
{ relation_id: relation, expected_revision: 1, ended_on: null },
|
|
a.token,
|
|
),
|
|
rpc(
|
|
'void_animal_client_relation',
|
|
{ relation_id: relation, expected_revision: 1 },
|
|
a.token,
|
|
),
|
|
rpc(
|
|
'end_animal_client_relation',
|
|
{ relation_id: relation, expected_revision: 1, ended_on: null },
|
|
a.token,
|
|
),
|
|
])
|
|
const messages = results.map(messageOf)
|
|
expect(messages.filter((m) => m === 'ok')).toHaveLength(1)
|
|
expect(messages.filter((m) => m === 'conflict')).toHaveLength(2)
|
|
const state = await sql(
|
|
`select (ended_at is not null) || '/' || (voided_at is not null) || '/' || revision
|
|
from public.animal_client_relations where id = '${relation}'`,
|
|
)
|
|
expect(['true/false/2', 'false/true/2']).toContain(state)
|
|
}
|
|
})
|
|
|
|
it('at 18 current relations, 6 concurrent links: exactly 2 pass', async () => {
|
|
const animal = idOf(await createAnimal(a, wA, { name: 'Crowded' }))
|
|
for (let i = 0; i < 18; i++)
|
|
expect((await link(a, animal, clients[i], 'contact')).status).toBe(200)
|
|
const results = await Promise.all(
|
|
clients.slice(18, 24).map((c) => link(a, animal, c, 'contact')),
|
|
)
|
|
const messages = results.map(messageOf)
|
|
expect(messages.filter((m) => m === 'ok')).toHaveLength(2)
|
|
expect(messages.filter((m) => m === 'limit_reached')).toHaveLength(4)
|
|
expect(
|
|
await sql(
|
|
`select count(*) from public.animal_client_relations where animal_id = '${animal}' and ended_at is null and voided_at is null`,
|
|
),
|
|
).toBe('20')
|
|
})
|
|
|
|
it('a relation create racing the archive of its client: created before, or refused archived after', async () => {
|
|
const outcomes = new Set<string>()
|
|
for (let round = 0; round < 10; round++) {
|
|
const client = idOf(await createClient(a, wA, `Archive race ${round}`))
|
|
const animal = idOf(
|
|
await createAnimal(a, wA, { name: `Archive race ${round}` }),
|
|
)
|
|
const [linked, archived] = await Promise.all([
|
|
link(a, animal, client),
|
|
rpc(
|
|
'set_client_archived',
|
|
{ client_id: client, archived: true },
|
|
a.token,
|
|
),
|
|
])
|
|
expect(messageOf(archived)).toBe('ok')
|
|
expect(['ok', 'archived']).toContain(messageOf(linked))
|
|
outcomes.add(messageOf(linked))
|
|
const rows = await sql(
|
|
`select count(*) from public.animal_client_relations where animal_id = '${animal}'`,
|
|
)
|
|
expect(rows).toBe(messageOf(linked) === 'ok' ? '1' : '0')
|
|
}
|
|
console.log(
|
|
`[measure] relation create vs client archive, 10 rounds: outcomes ${[...outcomes].join(', ')}`,
|
|
)
|
|
})
|
|
|
|
it('a relation create racing the archive of its animal: created before, or refused archived after', async () => {
|
|
for (let round = 0; round < 10; round++) {
|
|
const animal = idOf(
|
|
await createAnimal(a, wA, { name: `Animal archive race ${round}` }),
|
|
)
|
|
const [linked, archived] = await Promise.all([
|
|
link(a, animal, clients[3], 'keeper'),
|
|
rpc(
|
|
'set_animal_archived',
|
|
{ animal_id: animal, archived: true },
|
|
a.token,
|
|
),
|
|
])
|
|
expect(messageOf(archived)).toBe('ok')
|
|
expect(['ok', 'archived']).toContain(messageOf(linked))
|
|
expect(
|
|
await sql(
|
|
`select count(*) from public.animal_client_relations where animal_id = '${animal}'`,
|
|
),
|
|
).toBe(messageOf(linked) === 'ok' ? '1' : '0')
|
|
}
|
|
})
|
|
|
|
it('the budget is one counter for clients, animals and relations: at 990, 30 mixed writes, exactly 10 pass', async () => {
|
|
const animals: string[] = []
|
|
for (let i = 0; i < 10; i++)
|
|
animals.push(idOf(await createAnimal(a, wA, { name: `Budget ${i}` })))
|
|
await sql(
|
|
`update private.workspace_write_budgets set hour_count = 990 where workspace_id = '${wA}'`,
|
|
)
|
|
const results = await Promise.all(
|
|
Array.from({ length: 30 }, (_, i) =>
|
|
i % 3 === 0
|
|
? createClient(a, wA, `Budget client ${i}`)
|
|
: i % 3 === 1
|
|
? createAnimal(a, wA, { name: `Budget new ${i}` })
|
|
: link(a, animals[i % 10], clients[i % 24], 'contact'),
|
|
),
|
|
)
|
|
const messages = results.map(messageOf)
|
|
expect(messages.filter((m) => m === 'ok')).toHaveLength(10)
|
|
expect(messages.filter((m) => m === 'rate_limited')).toHaveLength(20)
|
|
expect((await budgetOf(wA)).split('/')[0]).toBe('1000')
|
|
await sql(
|
|
`update private.workspace_write_budgets set hour_count = 0, day_count = 0 where workspace_id = '${wA}'`,
|
|
)
|
|
})
|
|
|
|
it('caps of the workspace under concurrency: 20 000 animals and 100 000 relations', async () => {
|
|
const e = await confirmedAccount('an-caps')
|
|
const wE = await workspaceOf(e.id)
|
|
const client = idOf(await createClient(e, wE, 'Cap client'))
|
|
await sql(`insert into public.animals (workspace_id, name, species_id, sex, create_request_id, create_request_digest)
|
|
select '${wE}', 'Bulk ' || g, 'equine', 'male', gen_random_uuid(), '\\x00' from generate_series(1, 19998) g;
|
|
insert into public.animal_client_relations (workspace_id, animal_id, client_id, relation_role, ended_at, create_request_id, create_request_digest)
|
|
select '${wE}', a.id, '${client}', 'contact', now(), gen_random_uuid(), '\\x00'
|
|
from (select id, row_number() over (order by id) as n from public.animals where workspace_id = '${wE}') a
|
|
cross join generate_series(1, 10) g where a.n <= 9999 or (a.n = 10000 and g <= 8);
|
|
analyze public.animals; analyze public.animal_client_relations;`)
|
|
const animals = await Promise.all(
|
|
Array.from({ length: 5 }, () => createAnimal(e, wE, { name: 'Over' })),
|
|
)
|
|
expect(animals.map(messageOf).filter((m) => m === 'ok')).toHaveLength(2)
|
|
expect(
|
|
animals.map(messageOf).filter((m) => m === 'limit_reached'),
|
|
).toHaveLength(3)
|
|
const free = (
|
|
await sql(`select id from public.animals a where workspace_id = '${wE}'
|
|
and not exists (select 1 from public.animal_client_relations r where r.animal_id = a.id) limit 5`)
|
|
).split('\n')
|
|
const started = Date.now()
|
|
const links = await Promise.all(free.map((id) => link(e, id, client)))
|
|
const elapsed = Date.now() - started
|
|
expect(links.map(messageOf).filter((m) => m === 'ok')).toHaveLength(2)
|
|
expect(
|
|
links.map(messageOf).filter((m) => m === 'limit_reached'),
|
|
).toHaveLength(3)
|
|
expect(
|
|
await sql(
|
|
`select count(*) from public.animal_client_relations where workspace_id = '${wE}'`,
|
|
),
|
|
).toBe('100000')
|
|
console.log(
|
|
`[measure] 5 concurrent links next to 99 998 relations: ${elapsed} ms for the five (cap counted under the workspace lock)`,
|
|
)
|
|
})
|
|
|
|
it('a mixed burst across clients, animals and relations raises no deadlock', async () => {
|
|
const animals: string[] = []
|
|
const relations: string[] = []
|
|
for (let i = 0; i < 6; i++) {
|
|
const animal = idOf(await createAnimal(a, wA, { name: `Burst ${i}` }))
|
|
animals.push(animal)
|
|
relations.push(idOf(await link(a, animal, clients[i], 'owner')))
|
|
}
|
|
const started = Date.now()
|
|
const results = await Promise.all(
|
|
Array.from({ length: 96 }, (_, i) => {
|
|
const animal = animals[i % 6]
|
|
const client = clients[(i * 7) % 24]
|
|
switch (i % 8) {
|
|
case 0:
|
|
return link(a, animal, client, 'keeper')
|
|
case 1:
|
|
return rpc(
|
|
'update_animal',
|
|
animalUpdate(animal, 1, `B${i}`),
|
|
a.token,
|
|
)
|
|
case 2:
|
|
return rpc(
|
|
'set_animal_archived',
|
|
{ animal_id: animal, archived: i % 16 === 2 },
|
|
a.token,
|
|
)
|
|
case 3:
|
|
return rpc(
|
|
'update_client',
|
|
{
|
|
client_id: client,
|
|
expected_revision: 1,
|
|
kind: 'person',
|
|
display_name: `Race client edit ${i}`,
|
|
email: null,
|
|
phone: null,
|
|
address_line1: null,
|
|
address_line2: null,
|
|
postal_code: null,
|
|
city: null,
|
|
country: null,
|
|
},
|
|
a.token,
|
|
)
|
|
case 4:
|
|
return rpc(
|
|
'set_client_archived',
|
|
{ client_id: client, archived: i % 16 === 4 },
|
|
a.token,
|
|
)
|
|
case 5:
|
|
return rpc(
|
|
'end_animal_client_relation',
|
|
{
|
|
relation_id: relations[i % 6],
|
|
expected_revision: 1,
|
|
ended_on: null,
|
|
},
|
|
a.token,
|
|
)
|
|
case 6:
|
|
return createAnimal(a, wA, {
|
|
name: `Burst new ${i}`,
|
|
client_id: client,
|
|
relation_role: 'contact',
|
|
})
|
|
default:
|
|
return rpc(
|
|
'void_animal_client_relation',
|
|
{ relation_id: relations[i % 6], expected_revision: 1 },
|
|
a.token,
|
|
)
|
|
}
|
|
}),
|
|
)
|
|
const codes = results.map((r) =>
|
|
r.status === 200 ? 'ok' : `${errorCode(r)}:${messageOf(r)}`,
|
|
)
|
|
expect(
|
|
codes.filter((c) => c.startsWith('40P01') || c.startsWith('40001')),
|
|
).toEqual([])
|
|
const allowed = [
|
|
'ok',
|
|
'P0001:conflict',
|
|
'P0001:archived',
|
|
'P0001:duplicate_relation',
|
|
'P0001:already_ended',
|
|
'P0001:invalid_input',
|
|
]
|
|
expect(codes.filter((c) => !allowed.includes(c))).toEqual([])
|
|
console.log(
|
|
`[measure] 96 mixed writes over M2 and M3 in one workspace: ${Date.now() - started} ms, ${codes.filter((c) => c === 'ok').length} applied`,
|
|
)
|
|
})
|
|
})
|
|
|
|
describe('search on 20 000 animals', () => {
|
|
it('records the time of search_animals with owners (measurement, not a gate)', async () => {
|
|
const v = await confirmedAccount('an-volume')
|
|
const ws = await workspaceOf(v.id)
|
|
await sql(`insert into public.clients (workspace_id, kind, display_name, create_request_id, create_request_digest)
|
|
select '${ws}', 'person', 'Owner ' || g, gen_random_uuid(), '\\x00' from generate_series(1, 1000) g;
|
|
insert into public.animals (workspace_id, name, species_id, sex, breed, create_request_id, create_request_digest)
|
|
select '${ws}', 'Animal ' || g, case when g % 3 = 0 then 'canine' else 'equine' end, 'female',
|
|
'Race ' || (g % 40), gen_random_uuid(), '\\x00' from generate_series(1, 20000) g;
|
|
insert into public.animal_client_relations (workspace_id, animal_id, client_id, relation_role, create_request_id, create_request_digest)
|
|
select '${ws}', a.id, c.id, 'owner', gen_random_uuid(), '\\x00'
|
|
from (select id, row_number() over (order by id) as n from public.animals where workspace_id = '${ws}') a
|
|
join (select id, row_number() over (order by id) as n from public.clients where workspace_id = '${ws}') c
|
|
on c.n = 1 + a.n % 1000;
|
|
analyze public.animals; analyze public.animal_client_relations; analyze public.clients;`)
|
|
const owner = await sql(
|
|
`select id from public.clients where workspace_id = '${ws}' limit 1`,
|
|
)
|
|
const calls: [string, Record<string, unknown>][] = [
|
|
['search_animals', { workspace_id: ws, query: 'animal 1999' }],
|
|
['search_animals', { workspace_id: ws, query: 'race 7' }],
|
|
[
|
|
'search_animals',
|
|
{ workspace_id: ws, query: '', species_filter: 'canine' },
|
|
],
|
|
['search_animals', { workspace_id: ws, query: 'zzz-none' }],
|
|
['search_animals', { workspace_id: ws, query: '', page_size: 100 }],
|
|
['search_clients', { workspace_id: ws, query: 'owner', page_size: 100 }],
|
|
['list_client_animals', { client_id: owner }],
|
|
['client_archive_preview', { client_id: owner }],
|
|
]
|
|
const times: number[] = []
|
|
for (let round = 0; round < 3; round++) {
|
|
for (const [fn, args] of calls) {
|
|
const started = performance.now()
|
|
const result = await rpc(fn, args, v.token)
|
|
times.push(performance.now() - started)
|
|
expect([fn, result.status]).toEqual([fn, 200])
|
|
}
|
|
}
|
|
times.sort((x, y) => x - y)
|
|
const p95 = times[Math.ceil(times.length * 0.95) - 1]
|
|
console.log(
|
|
`[measure] reads over 20 000 animals, 20 000 relations, 1 000 clients, ${times.length} HTTP calls: median ${times[times.length >> 1].toFixed(1)} ms, p95 ${p95.toFixed(1)} ms, max ${times[times.length - 1].toFixed(1)} ms`,
|
|
)
|
|
})
|
|
})
|