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

offset.ts

18 lines946 Bytes

1import { StreamError } from './errors.js'
2​
3export const ZERO_OFFSET = '0000000000000000_0000000000000000'
4export const MAX_OFFSET_COMPONENT = 9_999_999_999_999_999n
5const PATTERN = /^\d{16}_\d{16}$/
6​
7export function parseOffset(value: string): { epoch: bigint; position: bigint } {
8 if (!PATTERN.test(value)) throw new StreamError(400, 'INVALID_OFFSET', 'Invalid offset')
9 return { epoch: BigInt(value.slice(0, 16)), position: BigInt(value.slice(17)) }
11​
12export function advanceOffset(offset: string, storedBytes: number): string {
13 if (!Number.isSafeInteger(storedBytes) || storedBytes < 0) throw new RangeError('Invalid stored length')
14 const { epoch, position } = parseOffset(offset)
15 const next = position + BigInt(storedBytes) + 5n
16 if (next > MAX_OFFSET_COMPONENT) throw new StreamError(413, 'OFFSET_CAPACITY', 'Stream offset capacity reached')
17 return `${epoch.toString().padStart(16, '0')}_${next.toString().padStart(16, '0')}`