Skip to content
Source
Sign inSign up
samwillis/neon-durable-streams
Open History to see the last commit

offset.ts

24 lines1.4 KB

1import { StreamError } from './errors.js'
2​
3/** Fixed-width append ordinal followed by the identity of its committed history. */
4export const ZERO_OFFSET = '0000000000000000_0000000000000000'
5export const MAX_OFFSET_COMPONENT = 9_999_999_999_999_999n
6const PATTERN = /^\d{16}_[0-9a-f]{32}$/
7export function parseOffset(value: string): { ordinal: bigint; history: string } {
8 if (value === ZERO_OFFSET) return { ordinal: 0n, history: '0'.repeat(32) }
9 if (!PATTERN.test(value) || value.startsWith('0000000000000000_')) throw new StreamError(400, 'INVALID_OFFSET', 'Invalid offset')
10 return { ordinal: BigInt(value.slice(0, 16)), history: value.slice(17) }
12export function ordinalOffset(ordinal: bigint, history: string): string {
13 if (ordinal < 0n || ordinal > MAX_OFFSET_COMPONENT) throw new StreamError(413, 'OFFSET_CAPACITY', 'Stream offset capacity reached')
14 if (ordinal === 0n) return ZERO_OFFSET
15 if (!/^[0-9a-f]{32}$/.test(history)) throw new RangeError('Invalid history identity')
16 return `${ordinal.toString().padStart(16, '0')}_${history}`
18export function advanceOffset(offset: string, history = parseOffset(offset).history): string {
19 return ordinalOffset(parseOffset(offset).ordinal + 1n, history)
21/** Payload size never changes the ordinal. A transition may enter a new history. */
22export function isSuccessor(start: string, end: string): boolean {
23 return parseOffset(end).ordinal === parseOffset(start).ordinal + 1n