feat: persist messenger data and sessions in PostgreSQL
This commit is contained in:
@@ -0,0 +1,71 @@
|
||||
import { invalid } from './errors.js';
|
||||
import type { Key, Page } from './models.js';
|
||||
import type { Pagination } from './validation.js';
|
||||
import { uuidPattern } from './validation.js';
|
||||
|
||||
interface Cursor extends Key { v: 1; resource: string }
|
||||
|
||||
export function compareKeys(a: Key, b: Key): number {
|
||||
// Время генерируется только в одном формате ISO UTC с миллисекундами,
|
||||
// UUID — lowercase. Для них лексикографический порядок совпадает с требуемым.
|
||||
return a.created_at < b.created_at ? -1 : a.created_at > b.created_at ? 1
|
||||
: a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
|
||||
}
|
||||
|
||||
export function encode(key: Key, resource: string): string {
|
||||
const cursor: Cursor = { v: 1, resource, created_at: key.created_at, id: key.id };
|
||||
return Buffer.from(JSON.stringify(cursor)).toString('base64url');
|
||||
}
|
||||
|
||||
export function decode(raw: string, resource: string): Key {
|
||||
// Buffer.from сам по себе допускает мусор: сначала проверяем алфавит,
|
||||
// затем обратное кодирование, UTF-8, точный набор полей и их смысл.
|
||||
try {
|
||||
if (raw.length > 1024 || !/^[A-Za-z0-9_-]+$/.test(raw)) invalid('Invalid cursor');
|
||||
const bytes = Buffer.from(raw, 'base64url');
|
||||
if (bytes.toString('base64url') !== raw) invalid('Invalid cursor');
|
||||
const value: unknown = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes));
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) invalid('Invalid cursor');
|
||||
const c = value as Record<string, unknown>;
|
||||
if (Object.keys(c).sort().join(',') !== 'created_at,id,resource,v'
|
||||
|| c.v !== 1 || c.resource !== resource
|
||||
|| typeof c.id !== 'string' || c.id.length !== 36 || !uuidPattern.test(c.id)
|
||||
|| c.id !== c.id.toLowerCase()
|
||||
|| typeof c.created_at !== 'string'
|
||||
|| new Date(c.created_at).toISOString() !== c.created_at) invalid('Invalid cursor');
|
||||
const key = { id: c.id, created_at: c.created_at };
|
||||
// Единая каноническая форма также отвергает дубли JSON-ключей.
|
||||
if (encode(key, resource) !== raw) invalid('Invalid cursor');
|
||||
return key;
|
||||
} catch {
|
||||
return invalid('Invalid cursor');
|
||||
}
|
||||
}
|
||||
|
||||
export function lowerBound(items: readonly Key[], target: Key): number {
|
||||
let lo = 0, hi = items.length;
|
||||
while (lo < hi) {
|
||||
const mid = lo + Math.floor((hi - lo) / 2);
|
||||
if (compareKeys(items[mid]!, target) < 0) lo = mid + 1;
|
||||
else hi = mid;
|
||||
}
|
||||
return lo;
|
||||
}
|
||||
|
||||
export function page<T extends Key>(items: readonly T[], resource: string, query: Pagination, sorted = false): Page<T> {
|
||||
// Baseline для будущего исследования: сортировка на каждом чтении.
|
||||
const ordered = sorted ? items : [...items].sort(compareKeys);
|
||||
let start = 0;
|
||||
if (query.cursor !== undefined) {
|
||||
const key = decode(query.cursor, resource);
|
||||
const anchor = sorted ? lowerBound(ordered, key) : ordered.findIndex(item => compareKeys(item, key) === 0);
|
||||
if (!ordered[anchor] || compareKeys(ordered[anchor]!, key) !== 0) invalid('Invalid cursor');
|
||||
start = anchor + 1;
|
||||
}
|
||||
const selected = ordered.slice(start, start + query.limit);
|
||||
const last = selected.at(-1);
|
||||
return {
|
||||
items: selected,
|
||||
next_cursor: last && start + selected.length < ordered.length ? encode(last, resource) : null,
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user