diff --git a/src/index.test.ts b/src/index.test.ts index 26c8764..9202dd7 100644 --- a/src/index.test.ts +++ b/src/index.test.ts @@ -7,10 +7,14 @@ import { test } from 'node:test' import type { TestContext } from 'node:test' import assert from 'node:assert' +import { Buffer as NodeBuffer } from 'node:buffer' +import { spawnSync } from 'node:child_process' +import { fileURLToPath } from 'node:url' import { gunzipSync } from 'zlib' import * as fs from 'fs' import proto from '../testing/proto/profile.js' +import { ProfilesDictionary } from './otel.js' const {decode, toObject} = proto.perftools.profiles.Profile @@ -466,6 +470,71 @@ test('StringTable', async (t) => { table.dedup('hello') assert.strictEqual(bufToHex(table.encode()), encodings[''] + encodings['hello']) }) + + await t.test('encodes non-ASCII strings as TextEncoder does', async () => { + const strings = ['é', '日本語', '😀 emoji', 'lone \uD800 high', 'lone \uDC00 low', 'x'.repeat(200) + 'ü'] + const table = new StringTable() + for (const value of strings) { + table.dedup(value) + } + const encoded = table.encode() + assert.strictEqual(encoded.length, table.encodedLength) + assert.strictEqual(bufToHex(encoded), encodeStringTable(table)) + }) + + await t.test('re-encodes decoded strings byte for byte', async () => { + // 0xff is not valid UTF-8, so the decoded string alone can't reproduce it + const raw = hexToBuf('3200' + '3203' + '61ff62') + const decoded = Profile.decode(raw).stringTable + assert.strictEqual(bufToHex(decoded.encode()), bufToHex(raw)) + }) + + await t.test('owns decoded string bytes after the input changes', () => { + for (const ArrayType of [Uint8Array, NodeBuffer]) { + for (const length of [0, 1, 64, 65]) { + const bytes = new Uint8Array(length).fill(0xff) + const expected = Uint8Array.of(0x32, 0, 0x32, length, ...bytes) + for (const [MessageType, field] of [[Profile, 0x32], [ProfilesDictionary, 0x2a]] as const) { + const input = ArrayType.from([0xaa, field, 0, field, length, ...bytes, 0xaa]) + const decoded = MessageType.decode(input.subarray(1, -1)) + input.fill(0) + assert.deepStrictEqual(decoded.stringTable.encode(), expected, `${ArrayType.name}, ${length} bytes`) + } + } + } + }) + + await t.test('checks the capacity of supplied buffers', () => { + for (const value of ['', 'hello', 'é日本😀\uD800', 'x'.repeat(127), 'x'.repeat(128)]) { + const table = new StringTable() + table.dedup(value) + const expected = encodeStringTable(table) + for (const ArrayType of [Uint8Array, NodeBuffer]) { + for (const length of [0, table.encodedLength - 1]) { + assert.throws(() => table.encode(new ArrayType(length)), { name: 'RangeError' }) + } + for (const extra of [0, 1]) { + const backing = new ArrayType(table.encodedLength + extra + 2).fill(0xaa) + const target = backing.subarray(1, -1) + assert.strictEqual(table.encode(target), target) + assert.strictEqual(bufToHex(target.subarray(0, table.encodedLength)), expected) + assert.strictEqual(backing[0], 0xaa) + assert.strictEqual(backing[backing.length - 1], 0xaa) + if (extra) { + assert.strictEqual(target[table.encodedLength], 0xaa) + } + } + } + } + }) + + await t.test('works without the Buffer global', { skip: typeof globalThis.Buffer === 'undefined' }, () => { + const result = spawnSync(process.execPath, [ + '--import', 'data:text/javascript,globalThis.Buffer=undefined', + '--test', '--test-name-pattern=StringTable', fileURLToPath(import.meta.url), + ], { encoding: 'utf8', env: { ...process.env, NODE_TEST_CONTEXT: undefined } }) + assert.strictEqual(result.status, 0, result.stderr || result.stdout) + }) }) function profileToObject(profile: any): object { diff --git a/src/otel.test.ts b/src/otel.test.ts index a0e5790..8ef243b 100644 --- a/src/otel.test.ts +++ b/src/otel.test.ts @@ -332,7 +332,11 @@ test('ProfilesDictionary', async (t) => { }) test('string fields are encoded as UTF-8', () => { - for (const key of ['plain', 'café', '✓', '😀', 'lone \ud800 surrogate']) { + for (const key of [ + 'plain', 'café', '✓', '😀', 'lone \ud800 surrogate', + '\u007f', '\u0080', '\u07ff', '\u0800', '\ud7ff', '\ud800', '\udbff', '\udc00', '\udfff', '\ue000', '\uffff', + '\ud800\udc00', '\udbff\udfff', '\ud800\ud800', '\ud800\ue000', '\udc00\ud800', + ]) { const utf8 = Buffer.from(key, 'utf8') const encoded = new KeyValue({ key }).encode() assert.strictEqual(hex(encoded), '0a' + utf8.length.toString(16).padStart(2, '0') + utf8.toString('hex'), key) diff --git a/src/protobuf.ts b/src/protobuf.ts index 6207ac0..fd44957 100644 --- a/src/protobuf.ts +++ b/src/protobuf.ts @@ -446,19 +446,20 @@ export function encodeBytesField(buffer: Uint8Array, offset: number, field: numb /** UTF-8 byte length; lone surrogates become U+FFFD (3 bytes), as in TextEncoder. */ export function utf8Length(string: string): number { - let length = 0 + let length = string.length for (let i = 0; i < string.length; i++) { const code = string.charCodeAt(i) if (code < 0x80) { + continue + } + if (code < 0x800) { length += 1 - } else if (code < 0x800) { + } else if (code >= 0xd800 && code <= 0xdbff && i + 1 < string.length && + (string.charCodeAt(i + 1) & 0xfc00) === 0xdc00) { length += 2 - } else if ((code & 0xfc00) === 0xd800 && (string.charCodeAt(i + 1) & 0xfc00) === 0xdc00) { - // A surrogate pair encodes one code point in 4 bytes - length += 4 i++ } else { - length += 3 + length += 2 } } return length diff --git a/src/string-table.ts b/src/string-table.ts index d099c5b..14a495c 100644 --- a/src/string-table.ts +++ b/src/string-table.ts @@ -10,7 +10,9 @@ import { encodeTag, kTypeLengthDelim, measureTag, + prepareBuffer, toUtf8, + utf8Length, varintLength, } from './protobuf.js' @@ -29,14 +31,31 @@ function encodeLengthDelimited(utf8: Uint8Array | Buffer): Uint8Array { return buffer } +const utf8ByteLength = typeof Buffer === 'undefined' + ? utf8Length + : (value: string) => Buffer.byteLength(value, 'utf8') + +// Writes a string's UTF-8 bytes into `buffer` at `offset` +function utf8Writer(buffer: Uint8Array): (value: string, offset: number) => void { + if (typeof Buffer === 'undefined') { + const encoder = new TextEncoder() + return (value, offset) => { encoder.encodeInto(value, buffer.subarray(offset)) } + } + const view = Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength) + return (value, offset) => { view.write(value, offset, 'utf8') } +} + /** - * The strings of a profile, each encoded once as it is added. The enclosing - * message supplies the field number when it encodes the table, so one table - * type serves both pprof and OTel. + * The strings of a profile. A string's UTF-8 bytes are written straight into + * the output when the table is encoded, so adding a string allocates no + * buffer. The enclosing message supplies the field number when it encodes the + * table, so one table type serves both pprof and OTel. */ export class StringTable { strings = new Array() - #encodings = new Array() + #byteLengths = new Array() + // The bytes of strings read from a profile, which re-encoding reproduces exactly + #decoded = new Array() #positions = new Map() #encodedLength = 0 @@ -54,21 +73,30 @@ export class StringTable { /** Measures the strings as the repeated string field `field`. */ _measure(field: number): number { - return this.#encodings.length * measureTag(field) + this.#encodedLength + return this.#byteLengths.length * measureTag(field) + this.#encodedLength } /** Encodes the strings as the repeated string field `field`. */ _encodeToBuffer(buffer: Uint8Array, offset: number, field: number): number { - for (const encoded of this.#encodings) { + const writeUtf8 = utf8Writer(buffer) + for (let i = 0; i < this.#byteLengths.length; i++) { + const byteLength = this.#byteLengths[i] offset = encodeTag(buffer, offset, field, kTypeLengthDelim) - buffer.set(encoded, offset) - offset += encoded.length + offset = encodeNumber(buffer, offset, byteLength) + const decoded = this.#decoded[i] + if (decoded !== undefined) { + buffer.set(decoded, offset) + } else if (byteLength > 0) { + writeUtf8(this.strings[i], offset) + } + offset += byteLength } return offset } /** Encodes the strings as pprof's string_table. */ - encode(buffer = new Uint8Array(this.encodedLength)): Uint8Array { + encode(buffer?: Uint8Array): Uint8Array { + buffer = prepareBuffer(buffer, this.encodedLength) this._encodeToBuffer(buffer, 0, pprofStringTableField) return buffer } @@ -89,22 +117,23 @@ export class StringTable { if (typeof value === 'number') return value let position = this.#positions.get(value) if (position === undefined) { - position = this.strings.push(value) - 1 - this.#positions.set(value, position) - - // Encode strings on insertion - const encoded = encodeLengthDelimited(toUtf8(value)) - this.#encodings.push(encoded) - this.#encodedLength += encoded.length + position = this.#add(value, utf8ByteLength(value)) } return position } _decodeString(buffer: Uint8Array) { - const value = decodeString(buffer) - this.#positions.set(value, this.strings.push(value) - 1) - const encoded = encodeLengthDelimited(buffer) - this.#encodings.push(encoded) - this.#encodedLength += encoded.length + const position = this.#add(decodeString(buffer), buffer.length) + this.#decoded[position] = buffer.length <= 64 || typeof Buffer === 'undefined' + ? new Uint8Array(buffer) + : Buffer.from(buffer) + } + + #add(value: string, byteLength: number): number { + const position = this.strings.push(value) - 1 + this.#positions.set(value, position) + this.#byteLengths.push(byteLength) + this.#encodedLength += varintLength(byteLength) + byteLength + return position } }