All files / json-pack/src/avro AvroSchemaEncoder.ts

87.24% Statements 171/196
73.03% Branches 65/89
92.59% Functions 25/27
86.91% Lines 166/191

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466  2x 2x                                   2x     66x   66x 66x 66x             64x 64x     64x 1x       63x 13x     50x   50x 2x   48x     49x             2x 1x             2x 1x             4x 3x 1x   2x             1x 1x             1x 1x             1x 1x                                             14x       14x 14x       14x 38x 38x 38x 37x 1x 1x                     4x       4x 4x       4x 4x       4x             10x       10x 10x         10x     10x 10x 21x       10x             7x       7x 7x       7x     7x     7x 7x 10x 10x 10x       7x             11x       11x 11x   17x 9x         11x 1x       10x     10x             2x       2x 2x       2x       2x             5x   5x           5x   1x 1x   1x 1x   1x 1x   1x 1x   1x               127x   127x 81x   6x 6x   4x 4x   26x 26x   6x 6x   3x 3x   3x 3x   3x 3x   30x 30x       81x     46x 9x 9x     37x   14x 14x   4x 4x   10x 10x   7x 7x   2x 2x             11x   11x           11x 3x         180x 97x 97x   83x       101x 68x     33x 33x   12x 12x 12x 36x 12x     4x 4x 4x 4x     2x 2x 2x 2x     8x 8x   7x 7x           18x             34x 34x 34x       34x             14x 14x 14x       14x             14x      
import type {IWriter, IWriterGrowable} from '@jsonjoy.com/buffers/lib';
import {AvroEncoder} from './AvroEncoder';
import {AvroSchemaValidator} from './AvroSchemaValidator';
import type {
  AvroSchema,
  AvroRecordSchema,
  AvroEnumSchema,
  AvroArraySchema,
  AvroMapSchema,
  AvroUnionSchema,
  AvroFixedSchema,
  AvroNamedSchema,
  AvroNullSchema,
} from './types';
 
/**
 * Apache Avro binary encoder with schema validation and encoding.
 * Encodes values according to provided Avro schemas with proper validation.
 * Based on https://avro.apache.org/docs/1.12.0/specification/
 */
export class AvroSchemaEncoder {
  private encoder: AvroEncoder;
  private validator: AvroSchemaValidator;
  private namedSchemas = new Map<string, AvroNamedSchema>();
 
  constructor(public readonly writer: IWriter & IWriterGrowable) {
    this.encoder = new AvroEncoder(writer);
    this.validator = new AvroSchemaValidator();
  }
 
  /**
   * Encodes a value according to the provided schema.
   */
  public encode(value: unknown, schema: AvroSchema, selectedIndex?: number): Uint8Array {
    this.writer.reset();
    this.namedSchemas.clear();
 
    // Validate schema first
    if (!this.validator.validateSchema(schema)) {
      throw new Error('Invalid Avro schema');
    }
 
    // Validate value against schema
    if (!this.validator.validateValue(value, schema)) {
      throw new Error('Value does not conform to schema');
    }
 
    this.collectNamedSchemas(schema);
 
    if (Array.isArray(schema) && selectedIndex !== undefined) {
      this.writeUnion(value, schema, selectedIndex);
    } else {
      this.writeValue(value, schema);
    }
 
    return this.writer.flush();
  }
 
  /**
   * Writes a null value with schema validation.
   */
  public writeNull(schema: AvroNullSchema | AvroSchema): void {
    this.validateSchemaType(schema, 'null');
    this.encoder.writeNull();
  }
 
  /**
   * Writes a boolean value with schema validation.
   */
  public writeBoolean(value: boolean, schema: AvroSchema): void {
    this.validateSchemaType(schema, 'boolean');
    this.encoder.writeBoolean(value);
  }
 
  /**
   * Writes an int value with schema validation.
   */
  public writeInt(value: number, schema: AvroSchema): void {
    this.validateSchemaType(schema, 'int');
    if (!Number.isInteger(value) || value < -2147483648 || value > 2147483647) {
      throw new Error('Value is not a valid 32-bit integer');
    }
    this.encoder.writeInt(value);
  }
 
  /**
   * Writes a long value with schema validation.
   */
  public writeLong(value: number | bigint, schema: AvroSchema): void {
    this.validateSchemaType(schema, 'long');
    this.encoder.writeLong(value);
  }
 
  /**
   * Writes a float value with schema validation.
   */
  public writeFloat(value: number, schema: AvroSchema): void {
    this.validateSchemaType(schema, 'float');
    this.encoder.writeFloat(value);
  }
 
  /**
   * Writes a double value with schema validation.
   */
  public writeDouble(value: number, schema: AvroSchema): void {
    this.validateSchemaType(schema, 'double');
    this.encoder.writeDouble(value);
  }
 
  /**
   * Writes a bytes value with schema validation.
   */
  public writeBytes(value: Uint8Array, schema: AvroSchema): void {
    this.validateSchemaType(schema, 'bytes');
    this.encoder.writeBin(value);
  }
 
  /**
   * Writes a string value with schema validation.
   */
  public writeString(value: string, schema: AvroSchema): void {
    this.validateSchemaType(schema, 'string');
    this.encoder.writeStr(value);
  }
 
  /**
   * Writes a record value with schema validation.
   */
  public writeRecord(value: Record<string, unknown>, schema: AvroRecordSchema): void {
    Iif (typeof schema === 'object' && schema.type !== 'record') {
      throw new Error('Schema is not a record schema');
    }
 
    const recordSchema = this.resolveSchema(schema) as AvroRecordSchema;
    Iif (recordSchema.type !== 'record') {
      throw new Error('Schema is not a record schema');
    }
 
    for (let i = 0; i < recordSchema.fields.length; i++) {
      const field = recordSchema.fields[i];
      const fieldValue = value[field.name];
      if (fieldValue !== undefined) {
        this.writeValue(fieldValue, field.type);
      } else if (field.default !== undefined) {
        this.writeValue(field.default, field.type);
      } else E{
        throw new Error(`Missing required field: ${field.name}`);
      }
    }
  }
 
  /**
   * Writes an enum value with schema validation.
   */
  public writeEnum(value: string, schema: AvroEnumSchema): void {
    Iif (typeof schema === 'object' && schema.type !== 'enum') {
      throw new Error('Schema is not an enum schema');
    }
 
    const enumSchema = this.resolveSchema(schema) as AvroEnumSchema;
    Iif (enumSchema.type !== 'enum') {
      throw new Error('Schema is not an enum schema');
    }
 
    const index = enumSchema.symbols.indexOf(value);
    Iif (index === -1) {
      throw new Error(`Invalid enum value: ${value}`);
    }
 
    this.writeVarIntSigned(this.encodeZigZag32(index));
  }
 
  /**
   * Writes an array value with schema validation.
   */
  public writeArray(value: unknown[], schema: AvroArraySchema): void {
    Iif (typeof schema === 'object' && schema.type !== 'array') {
      throw new Error('Schema is not an array schema');
    }
 
    const arraySchema = this.resolveSchema(schema) as AvroArraySchema;
    Iif (arraySchema.type !== 'array') {
      throw new Error('Schema is not an array schema');
    }
 
    // Write array length
    this.writeVarIntUnsigned(value.length);
 
    // Write array items
    const length = value.length;
    for (let i = 0; i < length; i++) {
      this.writeValue(value[i], arraySchema.items);
    }
 
    // Write end-of-array marker
    this.writeVarIntUnsigned(0);
  }
 
  /**
   * Writes a map value with schema validation.
   */
  public writeMap(value: Record<string, unknown>, schema: AvroMapSchema): void {
    Iif (typeof schema === 'object' && schema.type !== 'map') {
      throw new Error('Schema is not a map schema');
    }
 
    const mapSchema = this.resolveSchema(schema) as AvroMapSchema;
    Iif (mapSchema.type !== 'map') {
      throw new Error('Schema is not a map schema');
    }
 
    const entries = Object.entries(value);
 
    // Write map length
    this.writeVarIntUnsigned(entries.length);
 
    // Write map entries
    const length = entries.length;
    for (let i = 0; i < length; i++) {
      const entry = entries[i];
      this.encoder.writeStr(entry[0]);
      this.writeValue(entry[1], mapSchema.values);
    }
 
    // Write end-of-map marker
    this.writeVarIntUnsigned(0);
  }
 
  /**
   * Writes a union value with schema validation.
   */
  public writeUnion(value: unknown, schema: AvroUnionSchema, selectedIndex?: number): void {
    Iif (!Array.isArray(schema)) {
      throw new Error('Schema is not a union schema');
    }
 
    let index = selectedIndex;
    if (index === undefined) {
      // Find the first matching schema in the union
      index = schema.findIndex((subSchema) => this.validator.validateValue(value, subSchema));
      Iif (index === -1) {
        throw new Error('Value does not match any schema in the union');
      }
    }
 
    if (index < 0 || index >= schema.length) {
      throw new Error('Invalid union index');
    }
 
    // Write union index
    this.writeVarIntSigned(this.encodeZigZag32(index));
 
    // Write the value according to the selected schema
    this.writeValue(value, schema[index]);
  }
 
  /**
   * Writes a fixed value with schema validation.
   */
  public writeFixed(value: Uint8Array, schema: AvroFixedSchema): void {
    Iif (typeof schema === 'object' && schema.type !== 'fixed') {
      throw new Error('Schema is not a fixed schema');
    }
 
    const fixedSchema = this.resolveSchema(schema) as AvroFixedSchema;
    Iif (fixedSchema.type !== 'fixed') {
      throw new Error('Schema is not a fixed schema');
    }
 
    Iif (value.length !== fixedSchema.size) {
      throw new Error(`Fixed value length ${value.length} does not match schema size ${fixedSchema.size}`);
    }
 
    this.writer.buf(value, value.length);
  }
 
  /**
   * Generic number writing with schema validation.
   */
  public writeNumber(value: number, schema: AvroSchema): void {
    const resolvedSchema = this.resolveSchema(schema);
    const schemaType =
      typeof resolvedSchema === 'string'
        ? resolvedSchema
        : Array.isArray(resolvedSchema)
          ? 'union'
          : resolvedSchema.type;
 
    switch (schemaType) {
      case 'int':
        this.writeInt(value, schema);
        break;
      case 'long':
        this.writeLong(value, schema);
        break;
      case 'float':
        this.writeFloat(value, schema);
        break;
      case 'double':
        this.writeDouble(value, schema);
        break;
      default:
        throw new Error(`Schema type ${schemaType} is not a numeric type`);
    }
  }
 
  /**
   * Writes a value according to its schema.
   */
  private writeValue(value: unknown, schema: AvroSchema): void {
    const resolvedSchema = this.resolveSchema(schema);
 
    if (typeof resolvedSchema === 'string') {
      switch (resolvedSchema) {
        case 'null':
          this.encoder.writeNull();
          break;
        case 'boolean':
          this.encoder.writeBoolean(value as boolean);
          break;
        case 'int':
          this.encoder.writeInt(value as number);
          break;
        case 'long':
          this.encoder.writeLong(value as number | bigint);
          break;
        case 'float':
          this.encoder.writeFloat(value as number);
          break;
        case 'double':
          this.encoder.writeDouble(value as number);
          break;
        case 'bytes':
          this.encoder.writeBin(value as Uint8Array);
          break;
        case 'string':
          this.encoder.writeStr(value as string);
          break;
        default:
          throw new Error(`Unknown primitive type: ${resolvedSchema}`);
      }
      return;
    }
 
    if (Array.isArray(resolvedSchema)) {
      this.writeUnion(value, resolvedSchema);
      return;
    }
 
    switch (resolvedSchema.type) {
      case 'record':
        this.writeRecord(value as Record<string, unknown>, resolvedSchema);
        break;
      case 'enum':
        this.writeEnum(value as string, resolvedSchema);
        break;
      case 'array':
        this.writeArray(value as unknown[], resolvedSchema);
        break;
      case 'map':
        this.writeMap(value as Record<string, unknown>, resolvedSchema);
        break;
      case 'fixed':
        this.writeFixed(value as Uint8Array, resolvedSchema);
        break;
      default:
        throw new Error(`Unknown schema type: ${(resolvedSchema as any).type}`);
    }
  }
 
  private validateSchemaType(schema: AvroSchema, expectedType: string): void {
    const resolvedSchema = this.resolveSchema(schema);
    const actualType =
      typeof resolvedSchema === 'string'
        ? resolvedSchema
        : Array.isArray(resolvedSchema)
          ? 'union'
          : resolvedSchema.type;
 
    if (actualType !== expectedType) {
      throw new Error(`Expected schema type ${expectedType}, got ${actualType}`);
    }
  }
 
  private resolveSchema(schema: AvroSchema): AvroSchema {
    if (typeof schema === 'string') {
      const namedSchema = this.namedSchemas.get(schema);
      return namedSchema || schema;
    }
    return schema;
  }
 
  private collectNamedSchemas(schema: AvroSchema): void {
    if (typeof schema === 'string' || Array.isArray(schema)) {
      return;
    }
 
    if (typeof schema === 'object' && schema !== null) {
      switch (schema.type) {
        case 'record': {
          const recordSchema = schema as AvroRecordSchema;
          const recordFullName = this.getFullName(recordSchema.name, recordSchema.namespace);
          this.namedSchemas.set(recordFullName, recordSchema);
          recordSchema.fields.forEach((field) => this.collectNamedSchemas(field.type));
          break;
        }
        case 'enum': {
          const enumSchema = schema as AvroEnumSchema;
          const enumFullName = this.getFullName(enumSchema.name, enumSchema.namespace);
          this.namedSchemas.set(enumFullName, enumSchema);
          break;
        }
        case 'fixed': {
          const fixedSchema = schema as AvroFixedSchema;
          const fixedFullName = this.getFullName(fixedSchema.name, fixedSchema.namespace);
          this.namedSchemas.set(fixedFullName, fixedSchema);
          break;
        }
        case 'array':
          this.collectNamedSchemas((schema as AvroArraySchema).items);
          break;
        case 'map':
          this.collectNamedSchemas((schema as AvroMapSchema).values);
          break;
      }
    }
  }
 
  private getFullName(name: string, namespace?: string): string {
    return namespace ? `${namespace}.${name}` : name;
  }
 
  /**
   * Writes a variable-length integer using Avro's encoding (for lengths)
   */
  private writeVarIntUnsigned(value: number): void {
    const writer = this.writer;
    let n = value >>> 0; // Convert to unsigned 32-bit
    while (n >= 0x80) {
      writer.u8((n & 0x7f) | 0x80);
      n >>>= 7;
    }
    writer.u8(n & 0x7f);
  }
 
  /**
   * Writes a variable-length integer using Avro's encoding (for signed values with zigzag)
   */
  private writeVarIntSigned(value: number): void {
    const writer = this.writer;
    let n = value >>> 0; // Convert to unsigned 32-bit
    while (n >= 0x80) {
      writer.u8((n & 0x7f) | 0x80);
      n >>>= 7;
    }
    writer.u8(n & 0x7f);
  }
 
  /**
   * Encodes a 32-bit integer using zigzag encoding
   */
  private encodeZigZag32(value: number): number {
    return (value << 1) ^ (value >> 31);
  }
}