feat(supabase): animals and relations M3 with RPCs, history and caps
Species rows (8 + other), animals with the D6b birth model, relations with composite workspace keys, current/ended/voided states and a partial unique index; definer RPCs for animals and relations (one lock order, shared write budget, caps), invoker reads (search_animals, list_client_animals, client_archive_preview) and search_clients with current_animal_count. pgTAP 014 (254), parity test, sandbox suite, types from the isolated stack.
This commit is contained in:
1 parent
2dc04bcfba
commit
b54c8e5bd8
8 files changed
+3354
-11
No files matched your search
@@ -239,6 +239,149 @@ export type Database = {
|
||||
},
|
||||
]
|
||||
}
|
||||
animal_client_relations: {
|
||||
Row: {
|
||||
animal_id: string
|
||||
client_id: string
|
||||
create_request_digest: string
|
||||
create_request_id: string
|
||||
created_at: string
|
||||
ended_at: string | null
|
||||
ended_on: string | null
|
||||
id: string
|
||||
relation_role: Database['public']['Enums']['animal_relation_role']
|
||||
revision: number
|
||||
started_on: string | null
|
||||
updated_at: string
|
||||
voided_at: string | null
|
||||
workspace_id: string
|
||||
}
|
||||
ComputedFields: never
|
||||
Insert: {
|
||||
animal_id: string
|
||||
client_id: string
|
||||
create_request_digest: string
|
||||
create_request_id: string
|
||||
created_at?: string
|
||||
ended_at?: string | null
|
||||
ended_on?: string | null
|
||||
id?: string
|
||||
relation_role: Database['public']['Enums']['animal_relation_role']
|
||||
revision?: number
|
||||
started_on?: string | null
|
||||
updated_at?: string
|
||||
voided_at?: string | null
|
||||
workspace_id: string
|
||||
}
|
||||
Update: {
|
||||
animal_id?: string
|
||||
client_id?: string
|
||||
create_request_digest?: string
|
||||
create_request_id?: string
|
||||
created_at?: string
|
||||
ended_at?: string | null
|
||||
ended_on?: string | null
|
||||
id?: string
|
||||
relation_role?: Database['public']['Enums']['animal_relation_role']
|
||||
revision?: number
|
||||
started_on?: string | null
|
||||
updated_at?: string
|
||||
voided_at?: string | null
|
||||
workspace_id?: string
|
||||
}
|
||||
Relationships: [
|
||||
{
|
||||
foreignKeyName: 'animal_client_relations_animal_fk'
|
||||
columns: ['workspace_id', 'animal_id']
|
||||
isOneToOne: false
|
||||
referencedRelation: 'animals'
|
||||
referencedColumns: ['workspace_id', 'id']
|
||||
},
|
||||
{
|
||||
foreignKeyName: 'animal_client_relations_client_fk'
|
||||
columns: ['workspace_id', 'client_id']
|
||||
isOneToOne: false
|
||||
referencedRelation: 'clients'
|
||||
referencedColumns: ['workspace_id', 'id']
|
||||
},
|
||||
]
|
||||
}
|
||||
animals: {
|
||||
Row: {
|
||||
archived_at: string | null
|
||||
birth_date: string | null
|
||||
birth_year: number | null
|
||||
breed: string | null
|
||||
create_request_digest: string
|
||||
create_request_id: string
|
||||
created_at: string
|
||||
id: string
|
||||
name: string
|
||||
name_key: string | null
|
||||
revision: number
|
||||
search_key: string | null
|
||||
sex: Database['public']['Enums']['animal_sex']
|
||||
species_detail: string | null
|
||||
species_id: string
|
||||
updated_at: string
|
||||
workspace_id: string
|
||||
}
|
||||
ComputedFields: never
|
||||
Insert: {
|
||||
archived_at?: string | null
|
||||
birth_date?: string | null
|
||||
birth_year?: number | null
|
||||
breed?: string | null
|
||||
create_request_digest: string
|
||||
create_request_id: string
|
||||
created_at?: string
|
||||
id?: string
|
||||
name: string
|
||||
name_key?: never
|
||||
revision?: number
|
||||
search_key?: never
|
||||
sex: Database['public']['Enums']['animal_sex']
|
||||
species_detail?: string | null
|
||||
species_id: string
|
||||
updated_at?: string
|
||||
workspace_id: string
|
||||
}
|
||||
Update: {
|
||||
archived_at?: string | null
|
||||
birth_date?: string | null
|
||||
birth_year?: number | null
|
||||
breed?: string | null
|
||||
create_request_digest?: string
|
||||
create_request_id?: string
|
||||
created_at?: string
|
||||
id?: string
|
||||
name?: string
|
||||
name_key?: never
|
||||
revision?: number
|
||||
search_key?: never
|
||||
sex?: Database['public']['Enums']['animal_sex']
|
||||
species_detail?: string | null
|
||||
species_id?: string
|
||||
updated_at?: string
|
||||
workspace_id?: string
|
||||
}
|
||||
Relationships: [
|
||||
{
|
||||
foreignKeyName: 'animals_species_id_fkey'
|
||||
columns: ['species_id']
|
||||
isOneToOne: false
|
||||
referencedRelation: 'species'
|
||||
referencedColumns: ['id']
|
||||
},
|
||||
{
|
||||
foreignKeyName: 'animals_workspace_id_fkey'
|
||||
columns: ['workspace_id']
|
||||
isOneToOne: false
|
||||
referencedRelation: 'workspaces'
|
||||
referencedColumns: ['id']
|
||||
},
|
||||
]
|
||||
}
|
||||
assets: {
|
||||
Row: {
|
||||
attempts: number
|
||||
@@ -628,6 +771,7 @@ export type Database = {
|
||||
object_name: string
|
||||
}[]
|
||||
}
|
||||
client_archive_preview: { Args: { client_id: string }; Returns: Json }
|
||||
complete_avatar_job: {
|
||||
Args: {
|
||||
asset_id: string
|
||||
@@ -654,6 +798,33 @@ export type Database = {
|
||||
}
|
||||
Returns: string
|
||||
}
|
||||
create_animal: {
|
||||
Args: {
|
||||
birth_date?: string
|
||||
birth_year?: string
|
||||
breed?: string
|
||||
client_id?: string
|
||||
create_request_id: string
|
||||
name: string
|
||||
relation_role?: string
|
||||
sex: string
|
||||
species_detail?: string
|
||||
species_id: string
|
||||
started_on?: string
|
||||
workspace_id: string
|
||||
}
|
||||
Returns: Json
|
||||
}
|
||||
create_animal_client_relation: {
|
||||
Args: {
|
||||
animal_id: string
|
||||
client_id: string
|
||||
create_request_id: string
|
||||
relation_role: string
|
||||
started_on?: string
|
||||
}
|
||||
Returns: Json
|
||||
}
|
||||
create_client: {
|
||||
Args: {
|
||||
address_line1?: string
|
||||
@@ -685,6 +856,14 @@ export type Database = {
|
||||
Args: { reason?: string; version_id: string }
|
||||
Returns: string
|
||||
}
|
||||
end_animal_client_relation: {
|
||||
Args: {
|
||||
ended_on?: string
|
||||
expected_revision: number
|
||||
relation_id: string
|
||||
}
|
||||
Returns: Json
|
||||
}
|
||||
expire_pending_uploads: {
|
||||
Args: { max_age_seconds: number }
|
||||
Returns: number
|
||||
@@ -705,6 +884,31 @@ export type Database = {
|
||||
}
|
||||
Returns: string
|
||||
}
|
||||
list_client_animals: {
|
||||
Args: {
|
||||
after_id?: string
|
||||
after_sort?: string
|
||||
client_id: string
|
||||
page_size?: number
|
||||
}
|
||||
Returns: {
|
||||
animal_archived_at: string
|
||||
animal_id: string
|
||||
animal_name: string
|
||||
birth_year: number
|
||||
breed: string
|
||||
ended_on: string
|
||||
is_current: boolean
|
||||
relation_id: string
|
||||
relation_revision: number
|
||||
relation_role: Database['public']['Enums']['animal_relation_role']
|
||||
sex: Database['public']['Enums']['animal_sex']
|
||||
sort_key: string
|
||||
species_detail: string
|
||||
species_id: string
|
||||
started_on: string
|
||||
}[]
|
||||
}
|
||||
mark_quarantine_purged: { Args: { asset_id: string }; Returns: undefined }
|
||||
publish_sheet_version: { Args: { version_id: string }; Returns: string }
|
||||
register_sheet_asset: {
|
||||
@@ -730,6 +934,30 @@ export type Database = {
|
||||
}
|
||||
Returns: string
|
||||
}
|
||||
search_animals: {
|
||||
Args: {
|
||||
after_id?: string
|
||||
after_name_key?: string
|
||||
archived?: boolean
|
||||
page_size?: number
|
||||
query?: string
|
||||
species_filter?: string
|
||||
workspace_id: string
|
||||
}
|
||||
Returns: {
|
||||
archived_at: string
|
||||
birth_year: number
|
||||
breed: string
|
||||
current_owner_count: number
|
||||
current_owners: Json
|
||||
id: string
|
||||
name: string
|
||||
name_key: string
|
||||
sex: Database['public']['Enums']['animal_sex']
|
||||
species_detail: string
|
||||
species_id: string
|
||||
}[]
|
||||
}
|
||||
search_clients: {
|
||||
Args: {
|
||||
after_id?: string
|
||||
@@ -742,6 +970,7 @@ export type Database = {
|
||||
Returns: {
|
||||
archived_at: string
|
||||
city: string
|
||||
current_animal_count: number
|
||||
display_name: string
|
||||
email: string
|
||||
id: string
|
||||
@@ -750,6 +979,10 @@ export type Database = {
|
||||
phone: string
|
||||
}[]
|
||||
}
|
||||
set_animal_archived: {
|
||||
Args: { animal_id: string; archived: boolean }
|
||||
Returns: Json
|
||||
}
|
||||
set_client_archived: {
|
||||
Args: { archived: boolean; client_id: string }
|
||||
Returns: Json
|
||||
@@ -761,6 +994,29 @@ export type Database = {
|
||||
}
|
||||
Returns: string
|
||||
}
|
||||
update_animal: {
|
||||
Args: {
|
||||
animal_id: string
|
||||
birth_date: string
|
||||
birth_year: string
|
||||
breed: string
|
||||
expected_revision: number
|
||||
name: string
|
||||
sex: string
|
||||
species_detail: string
|
||||
species_id: string
|
||||
}
|
||||
Returns: Json
|
||||
}
|
||||
update_animal_client_relation: {
|
||||
Args: {
|
||||
ended_on: string
|
||||
expected_revision: number
|
||||
relation_id: string
|
||||
started_on: string
|
||||
}
|
||||
Returns: Json
|
||||
}
|
||||
update_client: {
|
||||
Args: {
|
||||
address_line1: string
|
||||
@@ -777,8 +1033,14 @@ export type Database = {
|
||||
}
|
||||
Returns: Json
|
||||
}
|
||||
void_animal_client_relation: {
|
||||
Args: { expected_revision: number; relation_id: string }
|
||||
Returns: Json
|
||||
}
|
||||
}
|
||||
Enums: {
|
||||
animal_relation_role: 'owner' | 'keeper' | 'contact'
|
||||
animal_sex: 'male' | 'female' | 'unknown'
|
||||
asset_status:
|
||||
| 'pending_upload'
|
||||
| 'uploaded'
|
||||
@@ -919,6 +1181,8 @@ export type CompositeTypes<
|
||||
export const Constants = {
|
||||
public: {
|
||||
Enums: {
|
||||
animal_relation_role: ['owner', 'keeper', 'contact'],
|
||||
animal_sex: ['male', 'female', 'unknown'],
|
||||
asset_status: [
|
||||
'pending_upload',
|
||||
'uploaded',
|
||||
|
||||
@@ -16,6 +16,20 @@ export const CLIENT_FIELD_LIMITS = {
|
||||
city: 80,
|
||||
} as const
|
||||
|
||||
export const ANIMAL_FIELD_LIMITS = {
|
||||
name: 80,
|
||||
breed: 80,
|
||||
speciesDetail: 80,
|
||||
} as const
|
||||
|
||||
/**
|
||||
* Lower bounds of the SQL CHECKs on birth years and on every record date
|
||||
* (birth, relation start and end). The upper bound is "not in the future":
|
||||
* the form checks the device's local date, the RPCs tomorrow's UTC date.
|
||||
*/
|
||||
export const BIRTH_YEAR_MIN = 1900
|
||||
export const RECORD_DATE_MIN = '1900-01-01'
|
||||
|
||||
/** U+0000 to U+001F, U+007F to U+009F, U+2028, U+2029 (the SQL literal starts at U+0001: text cannot hold U+0000). */
|
||||
export const CONTROL_CHARACTERS = /[\u0000-\u001F\u007F-\u009F\u2028\u2029]/u
|
||||
|
||||
|
||||
@@ -1,16 +1,20 @@
|
||||
/**
|
||||
* D-R7 parity: the constants of src/field-limits.ts behave like the SQL CHECK
|
||||
* constraints of public.clients, proven by inserting values at and past each
|
||||
* constraints of public.clients, public.animals and
|
||||
* public.animal_client_relations, proven by inserting values at and past each
|
||||
* bound into the migrated PGlite schema (contract §12.2). The form may refuse
|
||||
* more than SQL (never less): a value the TypeScript rule accepts must be
|
||||
* accepted by SQL, and the listed samples must agree both ways.
|
||||
*/
|
||||
import type { PGlite } from '@electric-sql/pglite'
|
||||
import {
|
||||
ANIMAL_FIELD_LIMITS,
|
||||
BIRTH_YEAR_MIN,
|
||||
CLIENT_FIELD_LIMITS,
|
||||
COUNTRY_CODE_PATTERN,
|
||||
EMAIL_PATTERN,
|
||||
PHONE_E164_PATTERN,
|
||||
RECORD_DATE_MIN,
|
||||
codePointLength,
|
||||
isCleanText,
|
||||
} from '../../src/field-limits'
|
||||
@@ -73,6 +77,52 @@ const textFields: [Column, number][] = [
|
||||
['city', CLIENT_FIELD_LIMITS.city],
|
||||
]
|
||||
|
||||
/** One animal row in a rolled-back transaction: does the schema accept these columns? */
|
||||
async function animalAccepts(
|
||||
columns: Record<string, string>,
|
||||
): Promise<boolean> {
|
||||
const row = { name: 'Parity', species_id: 'equine', ...columns }
|
||||
const names = Object.keys(row)
|
||||
await db.exec('begin')
|
||||
try {
|
||||
await db.query(
|
||||
`insert into public.animals (workspace_id, sex, create_request_id, create_request_digest, ${names.join(', ')})
|
||||
values ($1, 'unknown', gen_random_uuid(), '\\x00', ${names.map((_, i) => `$${i + 2}`).join(', ')})`,
|
||||
[workspaceId, ...Object.values(row)],
|
||||
)
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
} finally {
|
||||
await db.exec('rollback')
|
||||
}
|
||||
}
|
||||
|
||||
/** One relation row (ended, so both dates are allowed) to a fresh animal and client. */
|
||||
async function relationAccepts(
|
||||
column: 'started_on' | 'ended_on',
|
||||
value: string,
|
||||
): Promise<boolean> {
|
||||
await db.exec('begin')
|
||||
try {
|
||||
await db.query(
|
||||
`with a as (insert into public.animals (workspace_id, name, species_id, sex, create_request_id, create_request_digest)
|
||||
values ($1, 'Parity', 'equine', 'unknown', gen_random_uuid(), '\\x00') returning id),
|
||||
c as (insert into public.clients (workspace_id, kind, display_name, create_request_id, create_request_digest)
|
||||
values ($1, 'person', 'Parity', gen_random_uuid(), '\\x00') returning id)
|
||||
insert into public.animal_client_relations (workspace_id, animal_id, client_id, relation_role, ended_at, ${column},
|
||||
create_request_id, create_request_digest)
|
||||
select $1, a.id, c.id, 'owner', now(), $2, gen_random_uuid(), '\\x00' from a, c`,
|
||||
[workspaceId, value],
|
||||
)
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
} finally {
|
||||
await db.exec('rollback')
|
||||
}
|
||||
}
|
||||
|
||||
const tsEmail = (v: string) =>
|
||||
isCleanText(v, CLIENT_FIELD_LIMITS.email) &&
|
||||
v === v.toLowerCase() &&
|
||||
@@ -167,4 +217,64 @@ describe('field limits match the SQL constraints (D-R7)', () => {
|
||||
])
|
||||
}
|
||||
})
|
||||
|
||||
it.each([
|
||||
['name', ANIMAL_FIELD_LIMITS.name],
|
||||
['breed', ANIMAL_FIELD_LIMITS.breed],
|
||||
] as const)(
|
||||
'animals.%s: the text rule and its bound %i agree',
|
||||
async (column, max) => {
|
||||
for (const value of textSamples(max)) {
|
||||
expect([
|
||||
column,
|
||||
JSON.stringify(value).slice(0, 24),
|
||||
await animalAccepts({ [column]: value }),
|
||||
]).toEqual([
|
||||
column,
|
||||
JSON.stringify(value).slice(0, 24),
|
||||
isCleanText(value, max),
|
||||
])
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
it('animals.species_detail: the text rule and its bound agree (with other)', async () => {
|
||||
for (const value of textSamples(ANIMAL_FIELD_LIMITS.speciesDetail)) {
|
||||
expect([
|
||||
JSON.stringify(value).slice(0, 24),
|
||||
await animalAccepts({ species_id: 'other', species_detail: value }),
|
||||
]).toEqual([
|
||||
JSON.stringify(value).slice(0, 24),
|
||||
isCleanText(value, ANIMAL_FIELD_LIMITS.speciesDetail),
|
||||
])
|
||||
}
|
||||
})
|
||||
|
||||
it('birth year: the floor agrees', async () => {
|
||||
for (const year of [BIRTH_YEAR_MIN - 1, BIRTH_YEAR_MIN, 2015]) {
|
||||
expect([year, await animalAccepts({ birth_year: String(year) })]).toEqual(
|
||||
[year, year >= BIRTH_YEAR_MIN],
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
it('record dates: the floor agrees on birth and relation dates', async () => {
|
||||
const before = '1899-12-31'
|
||||
for (const value of [before, RECORD_DATE_MIN, '2015-04-12']) {
|
||||
const expected = value >= RECORD_DATE_MIN
|
||||
const year = value.slice(0, 4)
|
||||
expect([
|
||||
value,
|
||||
await animalAccepts({ birth_year: year, birth_date: value }),
|
||||
]).toEqual([value, expected])
|
||||
expect([value, await relationAccepts('started_on', value)]).toEqual([
|
||||
value,
|
||||
expected,
|
||||
])
|
||||
expect([value, await relationAccepts('ended_on', value)]).toEqual([
|
||||
value,
|
||||
expected,
|
||||
])
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -20,6 +20,41 @@ type ColumnMap = {
|
||||
}
|
||||
|
||||
const expectedColumns = {
|
||||
animal_client_relations: [
|
||||
'animal_id',
|
||||
'client_id',
|
||||
'create_request_digest',
|
||||
'create_request_id',
|
||||
'created_at',
|
||||
'ended_at',
|
||||
'ended_on',
|
||||
'id',
|
||||
'relation_role',
|
||||
'revision',
|
||||
'started_on',
|
||||
'updated_at',
|
||||
'voided_at',
|
||||
'workspace_id',
|
||||
],
|
||||
animals: [
|
||||
'archived_at',
|
||||
'birth_date',
|
||||
'birth_year',
|
||||
'breed',
|
||||
'create_request_digest',
|
||||
'create_request_id',
|
||||
'created_at',
|
||||
'id',
|
||||
'name',
|
||||
'name_key',
|
||||
'revision',
|
||||
'search_key',
|
||||
'sex',
|
||||
'species_detail',
|
||||
'species_id',
|
||||
'updated_at',
|
||||
'workspace_id',
|
||||
],
|
||||
anatomical_sheet_assets: [
|
||||
'byte_size',
|
||||
'content_type',
|
||||
@@ -158,9 +193,40 @@ const expectedFunctionArgs = {
|
||||
claim_avatar_jobs: ['max_jobs'],
|
||||
claim_purges: ['max_items'],
|
||||
claim_quarantine_leftovers: ['max_items', 'older_than_seconds'],
|
||||
client_archive_preview: ['client_id'],
|
||||
complete_avatar_job: ['asset_id', 'byte_size', 'lock_token', 'sha256'],
|
||||
confirm_asset_upload: ['asset_id'],
|
||||
confirm_sheet_asset_upload: ['asset_id'],
|
||||
create_anatomical_sheet: [
|
||||
'description',
|
||||
'document',
|
||||
'name',
|
||||
'official',
|
||||
'slug',
|
||||
'species_id',
|
||||
'visibility',
|
||||
],
|
||||
create_animal: [
|
||||
'birth_date',
|
||||
'birth_year',
|
||||
'breed',
|
||||
'client_id',
|
||||
'create_request_id',
|
||||
'name',
|
||||
'relation_role',
|
||||
'sex',
|
||||
'species_detail',
|
||||
'species_id',
|
||||
'started_on',
|
||||
'workspace_id',
|
||||
],
|
||||
create_animal_client_relation: [
|
||||
'animal_id',
|
||||
'client_id',
|
||||
'create_request_id',
|
||||
'relation_role',
|
||||
'started_on',
|
||||
],
|
||||
create_client: [
|
||||
'address_line1',
|
||||
'address_line2',
|
||||
@@ -174,23 +240,16 @@ const expectedFunctionArgs = {
|
||||
'postal_code',
|
||||
'workspace_id',
|
||||
],
|
||||
create_anatomical_sheet: [
|
||||
'description',
|
||||
'document',
|
||||
'name',
|
||||
'official',
|
||||
'slug',
|
||||
'species_id',
|
||||
'visibility',
|
||||
],
|
||||
create_sheet_draft: ['change_note', 'from_version_id', 'sheet_id'],
|
||||
delete_anatomical_sheet: ['sheet_id'],
|
||||
delete_sheet_asset: ['asset_id'],
|
||||
delete_sheet_version: ['version_id'],
|
||||
deprecate_sheet_version: ['reason', 'version_id'],
|
||||
end_animal_client_relation: ['ended_on', 'expected_revision', 'relation_id'],
|
||||
expire_pending_uploads: ['max_age_seconds'],
|
||||
fork_anatomical_sheet: ['name', 'slug', 'source_version_id', 'visibility'],
|
||||
grant_platform_role: ['role', 'target_user_id'],
|
||||
list_client_animals: ['after_id', 'after_sort', 'client_id', 'page_size'],
|
||||
mark_quarantine_purged: ['asset_id'],
|
||||
publish_sheet_version: ['version_id'],
|
||||
register_sheet_asset: ['byte_size', 'file_name', 'sha256', 'sheet_id'],
|
||||
@@ -198,6 +257,15 @@ const expectedFunctionArgs = {
|
||||
remove_avatar: [],
|
||||
restore_anatomical_sheet: ['sheet_id'],
|
||||
revoke_platform_role: ['reason', 'role', 'target_user_id'],
|
||||
search_animals: [
|
||||
'after_id',
|
||||
'after_name_key',
|
||||
'archived',
|
||||
'page_size',
|
||||
'query',
|
||||
'species_filter',
|
||||
'workspace_id',
|
||||
],
|
||||
search_clients: [
|
||||
'after_id',
|
||||
'after_name_key',
|
||||
@@ -206,8 +274,26 @@ const expectedFunctionArgs = {
|
||||
'query',
|
||||
'workspace_id',
|
||||
],
|
||||
set_animal_archived: ['animal_id', 'archived'],
|
||||
set_client_archived: ['archived', 'client_id'],
|
||||
set_sheet_visibility: ['sheet_id', 'visibility'],
|
||||
update_animal: [
|
||||
'animal_id',
|
||||
'birth_date',
|
||||
'birth_year',
|
||||
'breed',
|
||||
'expected_revision',
|
||||
'name',
|
||||
'sex',
|
||||
'species_detail',
|
||||
'species_id',
|
||||
],
|
||||
update_animal_client_relation: [
|
||||
'ended_on',
|
||||
'expected_revision',
|
||||
'relation_id',
|
||||
'started_on',
|
||||
],
|
||||
update_client: [
|
||||
'address_line1',
|
||||
'address_line2',
|
||||
@@ -221,6 +307,7 @@ const expectedFunctionArgs = {
|
||||
'phone',
|
||||
'postal_code',
|
||||
],
|
||||
void_animal_client_relation: ['expected_revision', 'relation_id'],
|
||||
} as const satisfies FunctionArgs
|
||||
|
||||
// A function without arguments is generated as `Record<PropertyKey, never>`
|
||||
|
||||
@@ -0,0 +1,832 @@
|
||||
/**
|
||||
* 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 holder = sql(`begin;
|
||||
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'),
|
||||
])
|
||||
const elapsed = Date.now() - started
|
||||
await holder
|
||||
expect(results.map(shape)).toEqual([NOT_FOUND, NOT_FOUND, NOT_FOUND])
|
||||
expect(elapsed).toBeLessThan(1000)
|
||||
console.log(
|
||||
`[measure] A's animal and relation locked 2 s: B's three 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('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`,
|
||||
)
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user