ohos_avroc:基于 OpenHarmony 的数据序列化系统项目

使用napi封装avro的C代码接口,实现序列化和反序列化能力

Branch38Tags112

avro

Introduction

This software is a data serialization system implemented for OpenHarmony by adapting the source code of the open-source project apache avro. It supports rich data structures and converts them into a binary data format that is easy to store or transmit. It is also a container file used to store persistent data.

Demo:

Installation

ohpm install @ohos/avroc

For more information about the OpenHarmony ohpm environment configuration, see How to Install OpenHarmony ohpm Packages.

Building and Running

Building the Dependent jansson, xz (lzma) and avro Libraries

This project depends on the compiled .a files and header files of the jansson, xz (lzma) and avro libraries. They are produced by cross-compiling the corresponding third-party libraries in CPF-ApplicationTPC/tpc_c_cplusplus. You can run the prebuild.sh script to automatically generate the library files and header files and copy them to the referenced directory. Third-party library directory: avro/src/main/cpp/third_party (the script creates this directory automatically).

bash prebuild.sh

Building and Running in the IDE

  1. Download the required SDK through the IDE: File->Settings->SDK (Windows) / DevEco Studio->Preferences->SDK (macOS), download the OpenHarmony SDK, check the native option, API version >= 15.

  2. Select a development phone with API version >= 15.

  3. Download the source code with git clone. Do not download the archive directly from the gitcode web page.

Usage

Example Code

  1. Import avro in a page
import  {OhosAvroC}  from '@ohos/avroc';
  1. Usage
let intStr: string = "{type: 'int'}";
let psInt:OhosAvroC.AvroTypeC = OhosAvroC.parse(intStr)
let intBuf : number =123;
let bufInt: ArrayBuffer = psInt.toBuffer(intBuf); // Serialization
let u8BufInt = new Uint8Array(bufInt);
console.log('testTag toBuffer int =', JSON.stringify(u8BufInt.toString()));// result:"246,1"
let fromInt: number = psInt.fromBuffer(bufInt); // Deserialization
console.log('testTag fromBuffer int =', fromInt);//result:123
console.log('testTag int getName=', psInt.getName());//name:int

console.log('testTag isValid int value:123=', psInt.isValid(intBuf));// result: true

let res:number = psInt.compare(1234, 999);
console.error('testTag aaa compare result:', res); // 1 (greater than)

// string type
let stringStr: string = "{type: 'string'}";
let psString:OhosAvroC.AvroTypeC = OhosAvroC.parse(stringStr);
let stringBuf : string ='sdf234';
let bufString: ArrayBuffer = psString.toBuffer(stringBuf);
let u8BufString = new Uint8Array(bufString);
//result:"12,115,100,102,50,51,52"
console.log('testTag toBuffer string =', JSON.stringify(u8BufString.toString()));
let fromString: object = psString.fromBuffer(bufString);
//result:"sdf234"
console.log('testTag fromBuffer string:'+JSON.stringify(fromString));
//name:string
console.log('testTag string getName=', psString.getName());
//result: true
console.log('testTag isValid string=', psString.isValid(stringBuf));

res = psString.compare("saarfe", "derew");
console.error('testTag aaa compare result:', res); //  1 (greater than)

// fixed type
let fixedStr: string = "{type: 'fixed', name: 'num', aliases: ['stooges1', 'stooges2'], size: 2, namespace: 'a'}";
let psFixed:OhosAvroC.AvroTypeC = OhosAvroC.parse(fixedStr);
let fixedBuf =[0x67, 0xAB];
let buffixed: ArrayBuffer = psFixed.toBuffer(fixedBuf);
let u8BufFixed = new Uint8Array(buffixed);
//result:"103,171"
console.log('testTag toBuffer fixed =', JSON.stringify(u8BufFixed.toString()));
const fromFix:object = psFixed.fromBuffer(buffixed);
//result:"103,171" (hex: [0x67, 0xAB])
console.log('testTag fromBuffer fixed =', JSON.stringify(fromFix.toString()));
//name:num
console.log('testTag fixed getName=', psFixed.getName());
//result:true
console.log('testTag isValid fixed=', psFixed.isValid(fixedBuf));
//Current size of the Fixed type: 2
console.log('testTag getFixedSize=', psFixed.getFixedSize());
let aliasesFixed:Array<string> = psFixed.getAliases();
//result:["stooges1","stooges2"]
console.log('testTag getAliases fixed =', JSON.stringify(aliasesFixed));
let schemaFixed:string = psFixed.getSchema();
//result (in avro format):"{\"type\": \"fixed\", \"name\": \"num\", \"aliases\": [\"stooges1\", \"stooges2\"], \"size\": 2, \"namespace\": \"a\"}"
console.log('testTag getSchema fixed =', JSON.stringify(schemaFixed));

res = psFixed.compare([0x67, 0xAB], [0x67, 0xAB]);
console.error('testTag compare result:', res); // 0 (equal)

// array type
let arrayStr: string = "{type: 'array', items: 'string'}";
let psArray:OhosAvroC.AvroTypeC = OhosAvroC.parse(arrayStr);
let arrayBuf =['3443rtr', 'sfrf', 'eryryyh'];
let bufarray: ArrayBuffer = psArray.toBuffer(arrayBuf);
let u8BufArray = new Uint8Array(bufarray);
//result:"6,14,51,52,52,51,114,116,114,8,115,102,114,102,14,101,114,121,114,121,121,104,0"
console.log('testTag toBuffer array =', JSON.stringify(u8BufArray.toString()));
const fromArray:object = psArray.fromBuffer(bufarray);
//result:["3443rtr","sfrf","eryryyh"]
console.log('testTag fromBuffer array =', JSON.stringify(fromArray));
//name:array
console.log('testTag Array getName=', psArray.getName());
//result:true
console.log('testTag isValid array=', psArray.isValid(arrayBuf));
//The item type of the array: string
console.log('testTag getArrayItemType=', psArray.getArrayItemType());

res = psArray.compare([0x67, 0xAB], [0x67, 0xAB]);
console.error('testTag compare result:', res); // undefined (operation failed, this type is not supported)

// map type
let mapStr: string = "{type: 'map', values: 'long'}";
let psMap:OhosAvroC.AvroTypeC = OhosAvroC.parse(mapStr);
const data = new Map([["key1",12343], ["key2",3445]]);
let bufmap: ArrayBuffer = psMap.toBuffer(data);
let u8Bufmap = new Uint8Array(bufmap);
//result:"4,8,107,101,121,49,238,192,1,8,107,101,121,50,234,53,0"
console.log('testTag toBuffer map =', JSON.stringify(u8Bufmap.toString()));
const decodedData = psMap.fromBuffer(bufmap);
//result:{"key1":12343,"key2":3445}
console.log('testTag fromBuffer map:'+ JSON.stringify(decodedData));
//name:map
console.log('testTag Map getName=', psMap.getName());
//result:true
console.log('testTag isValid map=', psMap.isValid(data));
//The value type of the map: long
console.log('testTag getMapValueType=', psMap.getMapValueType());

// record type

let recordStr: string = "{type: 'record',name: 'Person',aliases: ['Person1'],fields: [{name: 'age', type: 'int'}, {name: 'name', type: 'string'}]}";
let psRecord:OhosAvroC.AvroTypeC = OhosAvroC.parse(recordStr);
class petrecordType {
  "age": number = 0
  "name": string = ''
}
let recordBuf : petrecordType ={"age": 25, "name": "Alice"};
let bufrecord: ArrayBuffer = psRecord.toBuffer(recordBuf);
let u8BufRecord = new Uint8Array(bufrecord);
//result:"50,10,65,108,105,99,101"
console.log('testTag toBuffer record ='+JSON.stringify(u8BufRecord.toString()));
const recFromBuff:object = psRecord.fromBuffer(bufrecord);
//result:{"age":25,"name":"Alice"}
console.log('testTag fromBuffer record ='+JSON.stringify(recFromBuff));
//name:Person
console.log('testTag Record getName=', psRecord.getName());
//result:true
console.log('testTag isValid record=', psRecord.isValid(recordBuf));
let aliasesRec:Array<string> = psRecord.getAliases();
//result:["Person1"]
console.log('testTag getAliases record =', JSON.stringify(aliasesRec));
let schemaRec:string = psRecord.getSchema();
//result (in avro format):"{\"type\": \"record\",\"name\": \"Person\",\"aliases\": [\"Person1\"],\"fields\": [{\"name\": \"age\", \"type\": \"int\"}, {\"name\": \"name\", \"type\": \"string\"}]}"

console.log('testTag getSchema record =', JSON.stringify(schemaRec));

// compareBuffers
const hexArray = [0x67, 0xAB];
const uArray = new Uint8Array(hexArray);
const buffer1 = uArray.buffer;

const hexArray2 = [0x67, 0xAB, 0x11];
const uArray2 = new Uint8Array(hexArray2);
const buffer2 = uArray2.buffer;

console.log("testTag compareBuffers :" + psArray.compareBuffers(buffer1, buffer2));// undefined, comparison of the array type is not supported

// toFile
// Define the callback
let fileSchemaStr3: string = "{type: 'record',name: 'User',namespace: 'comexample',fields: [ {name: 'id', type: 'int'}, {name: 'name', type: 'string'}, {name: 'age', type: ['int', 'null']},{name: 'hobbies',type:{type:'array',items: 'string'}}]}";
const path3 = getContext(this).getApplicationContext().filesDir+"/10.avro";

class petrecordType6 {
  "id": number = 0
  "name": string = ''
  "age": number | null
  "hobbies": Array<string>
}
let recordBuf7 = new petrecordType6();
recordBuf7.id = 1;
recordBuf7.name = "san";
recordBuf7.age = 25;
recordBuf7.hobbies = ["yd", "pb"];

let recordBuf8 = new petrecordType6();
recordBuf8.id = 2;
recordBuf8.name = "si";
recordBuf8.age = null;
recordBuf8.hobbies = ["yy", "lx"];

let recordBuf9 = new petrecordType6();
recordBuf9.id = 3;
recordBuf9.name = "wu";
recordBuf9.age = 30;
recordBuf9.hobbies = ["bc", "yy"];

let fileArrayBuf1 =[recordBuf7, recordBuf8, recordBuf9];
//Compression modes: "deflate" (zlib), "lzma", "null" (no compression)
try {
  OhosAvroC.toFile(path3, fileSchemaStr3, fileArrayBuf1, "null", (error, data) => {
    if (error != undefined) {
      console.log('testTag serialization failed, error:', error);
      this.showAlert('Serialization failed', 'Error message: ' + error);
    }
    if (data === undefined) {
      console.log('testTag invalid data!');
      this.showAlert('Serialization failed', 'Invalid data!');
    } else {
      console.error('ps has been created tofile:' + data);
      this.showAlert('Serialization succeeded', 'Data: ' + data);
    }
  });
} catch (error) {
  console.log('Serialization failed:', error);
}

// fromFile
try {
  OhosAvroC.fromFile(path3, fileSchemaStr3, (error, buffer) => {
    if (error != undefined) {
      console.log('testTag deserialization failed:', error);
      this.showAlert('Deserialization failed', 'Error message: ' + error);
    }
    if (buffer === undefined) {
      console.log('testTag deserialization failed, invalid data!');
      this.showAlert('Deserialization failed', 'Invalid data!');
    } else {
      //[{"id":1,"name":"san","age":25,"hobbies":["yd","pb"]},{"id":2,"name":"si","age":null,"hobbies":["yy","lx"]},{"id":3,"name":"wu","age":30,"hobbies":["bc","yy"]}]
      console.error('testTag deserialization result:', JSON.stringify(buffer));
      this.showAlert('Deserialization succeeded', 'Deserialization result: ' + JSON.stringify(buffer));
    }
  });
} catch (error) {
  console.log('Deserialization failed:', error);
}

APIs

Note: Returning undefined means the operation failed.

Method Parameters Description
parse(schema:string) schema:Avro schema definition Parses the schema and returns the corresponding instance
toBuffer(val:any) val: data object conforming to the schema Encodes and serializes the data object into an ArrayBuffer in Avro binary format
fromBuffer(buf:ArrayBuffer) buffer: Avro-encoded binary data Deserializes an ArrayBuffer in Avro binary format into data of the corresponding type
isValid(val:any) val:data to be validated Checks whether the given value is valid.
compare(val1:any, val2:any) val1:data to be compared
val2:data to be compared
Compares the sizes of two pieces of data before serialization. Return values:
● Negative: val1 < val2
● 0: val1 == val2
● Positive: val1 > val2
Comparison of complex types is not supported (AVRO_ARRAY, AVRO_RECORD, AVRO_UNION, AVRO_MAP)
compareBuffers(buf1:ArrayBuffer, buf2:ArrayBuffer) buf1:buffer to be compared
buf2:buffer to be compared
Compares the sizes of two serialized binary buffers. Return values:
● Negative: buf1 < buf2
● 0: buf1 == buf2
● Positive: buf1 > buf2
Comparison of complex types is not supported (AVRO_ARRAY, AVRO_RECORD, AVRO_UNION, AVRO_MAP)
getName() - Obtains the name of the type.
getArrayItemType() - Obtains the item type of the array.
getFixedSize() - Obtains the size of the Fixed type.
getMapValueType() - Obtains the value type of the Map.
getSchema() - Obtains the schema string, which is returned in Avro format (attributes and string fields are enclosed in double quotes)
getAliases() - Obtains the aliases (only Enum, Fixed and Record have the name attribute and therefore aliases). The result is a string array
toFile(path: string, schema: string, val: any, codec: string, callback:AsyncWriteFileCallback) path: file path
schema: Avro schema definition
val: data to be serialized (the record type supports transferring multiple records; for the record type, pass data as an array)
codec: compression mode
callback: callback invoked when the file is asynchronously written, with parameters err: string, data: string
Serializes record data objects to a file using the specified schema (compression modes: "deflate" (zlib), "lzma", "null" (no compression)). Note: Throwing an exception means the operation failed
fromFile(filePath:string,schema:string,callback:callback) filePath: file path
schema: Avro schema definition
callback: callback invoked when the file is asynchronously read, with parameters err: string, data: ArrayBuffer
Reads a serialized file and converts it into record data (ArrayBuffer) using the specified schema. Note: Throwing an exception means the operation failed

Constraints

Verified in the following versions:

  • DevEco Studio version: DevEco Studio 5.0.5 Release, OpenHarmony SDK: API 15.

Directory Structure

|---- ohos_avroc  
|     |---- entry  # Sample code folder
|     |---- avro  # avro library folder
|			|---- cpp  # Native module
|                  |----- napi # NAPI implementation code directory
|                  |----- third_party    # Third-party libraries referenced by the implementation: jansson, avro, zlib, lzma; generated automatically by prebuild.sh
|                  |----- utils      # Utilities, common code and log API directory
|                  |----- types    # Type declaration directory (.d.ts)
|     |---- README_zh.md  # Chinese installation and usage guide
|     |---- README.md  # English installation and usage guide

Contributing

If you find any problems during use, feel free to submit an Issue to the component. Contributions via PR are also very welcome.

License

This project is based on the Apache License 2.0. You are free to use it and welcome to contribute.

Introduction

使用napi封装avro的C代码接口,实现序列化和反序列化能力

Customize your domain