Skip to content

Commit

Permalink
chore(assemblyscript): PR comments
Browse files Browse the repository at this point in the history
  • Loading branch information
FranklinWaller committed Aug 23, 2023
1 parent 7fe85d5 commit 5cb9a01
Show file tree
Hide file tree
Showing 20 changed files with 120 additions and 509 deletions.
3 changes: 1 addition & 2 deletions .devcontainer/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,4 @@ ARG VARIANT=18
FROM mcr.microsoft.com/vscode/devcontainers/typescript-node:${VARIANT}
RUN apt-get update
RUN apt-get -y install --no-install-recommends zsh
RUN apt-get -y install binaryen
RUN apt-get -y install build-essential cmake
RUN apt-get -y install binaryen build-essential cmake
3 changes: 3 additions & 0 deletions libs/as-sdk-integration-tests/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# AssemblyScript Integration Tests

This project is for testing the SDK together with the VM project. This is used internally to validate if the functions act like they are supposed to
9 changes: 6 additions & 3 deletions libs/as-sdk-integration-tests/assembly/index.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,24 @@
// The entry file of your WebAssembly module.

import { httpFetch, Process } from '../../as-sdk/assembly/index';
import { testInvalidUint8JsonArray, testValidUint8JsonArray } from './json-utils-test';

const args = Process.args()[0];

if (args === 'testHttpRejection') {
testHttpRejection();
} else if (args === 'testHttpSuccess') {
testHttpSuccess();
} else if (args === 'testValidUint8JsonArray') {
testValidUint8JsonArray();
} else if (args === 'testInvalidUint8JsonArray') {
testInvalidUint8JsonArray();
}

export function testHttpRejection(): void {
const response = httpFetch('example.com/');
const rejected = response.rejected;

if (rejected !== null) {
const msg = String.UTF8.encode('ok');
const msg = String.UTF8.encode('rejected');
const buffer = Uint8Array.wrap(msg);

Process.exit_with_result(0, buffer);
Expand Down
26 changes: 26 additions & 0 deletions libs/as-sdk-integration-tests/assembly/json-utils-test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { jsonArrToUint8Array, JSON, testutils } from '../../as-sdk/assembly/index';

export function testValidUint8JsonArray(): void {
const raw: string = "[0, 23, 254, 88]";
const json = <JSON.Arr>JSON.parse(raw);
const result = jsonArrToUint8Array(json);

const expected = new Uint8Array(4);
expected.set([0, 23, 254, 88]);

testutils.assert(result.byteLength === expected.byteLength, "bytelength is not equal");
testutils.assert(
String.UTF8.decode(result.buffer) === String.UTF8.decode(expected.buffer),
'buffers are not equal'
);

testutils.ok();
}

export function testInvalidUint8JsonArray(): void {
const raw: string = '[0, 23, 299, 88]';
const json = <JSON.Arr>JSON.parse(raw);
jsonArrToUint8Array(json);

testutils.error("Test should fail");
}
1 change: 1 addition & 0 deletions libs/as-sdk-integration-tests/project.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
"jestConfig": "libs/as-sdk-integration-tests/jest.config.ts",
"passWithNoTests": true
},
"dependsOn": [{ "target": "build" }],
"configurations": {
"ci": {
"ci": true,
Expand Down
2 changes: 1 addition & 1 deletion libs/as-sdk-integration-tests/src/http.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ describe('Http', () => {
});

expect(result.exitCode).toBe(0);
expect(result.result).toEqual(new TextEncoder().encode("ok"));
expect(result.result).toEqual(new TextEncoder().encode("rejected"));
});

it('Test SDK HTTP Success', async () => {
Expand Down
32 changes: 32 additions & 0 deletions libs/as-sdk-integration-tests/src/jsonutils.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { readFile } from "fs/promises";
import { callVm } from "../../../dist/libs/vm/src";

describe('json-utils', () => {
it('should handle valid u8 json arrays', async () => {
const wasmBinary = await readFile(
'dist/libs/as-sdk-integration-tests/debug.wasm'
);
const result = await callVm({
args: ['testValidUint8JsonArray'],
envs: {},
binary: new Uint8Array(wasmBinary),
});

expect(result.resultAsString).toEqual('ok');
expect(result.exitCode).toBe(0);
});

it('should error on invalid u8 json arrays', async () => {
const wasmBinary = await readFile(
'dist/libs/as-sdk-integration-tests/debug.wasm'
);
const result = await callVm({
args: ['testInvalidUint8JsonArray'],
envs: {},
binary: new Uint8Array(wasmBinary),
});

expect(result.stderr).toContain('abort: Invalid u8 299');
expect(result.exitCode).toBe(255);
});
});
3 changes: 3 additions & 0 deletions libs/as-sdk/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# AssemblyScript SDK

SDK for creating Data Requests on the SEDA chain
1 change: 0 additions & 1 deletion libs/as-sdk/assembly/__test__/as-pect.d.ts

This file was deleted.

15 changes: 0 additions & 15 deletions libs/as-sdk/assembly/__test__/http.spec.ts

This file was deleted.

7 changes: 4 additions & 3 deletions libs/as-sdk/assembly/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
// The entry file of your WebAssembly module.
import Process from './process';
import * as testutils from './test-utils';


export { JSON, JSONDecoder, JSONEncoder, DecoderState, JSONHandler, ThrowingJSONHandler } from '../../../node_modules/assemblyscript-json/assembly/index';
export { httpFetch, HttpFetchMethod, HttpFetchOptions, HttpResponse } from './http';
export { PromiseStatus } from './promise';
export { Process };
export { Process, testutils };
export { jsonArrToUint8Array } from './json-utils';

5 changes: 5 additions & 0 deletions libs/as-sdk/assembly/json-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@ export function jsonArrToUint8Array(array: JSON.Arr): Uint8Array {

for (let i = 0; i < innerArrayValue.length; i++) {
const element = <JSON.Integer>innerArrayValue[i];

if (element.valueOf() > i64(U8.MAX_VALUE) || element.valueOf() < i64(U8.MIN_VALUE)) {
throw new Error(`Invalid u8 ${element.valueOf()}`);
}

bytes.push(u8(element.valueOf()));
}

Expand Down
7 changes: 7 additions & 0 deletions libs/as-sdk/assembly/process.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,13 @@ export default class Process {
return CommandLine.all;
}

static exit_with_message(code: u8, message: string): void {
const msg = String.UTF8.encode(message);
const buffer = Uint8Array.wrap(msg);

Process.exit_with_result(code, buffer);
}

static exit_with_result(code: u8, result: Uint8Array): void {
const buffer = result.buffer;
const bufferPtr = changetype<usize>(buffer);
Expand Down
8 changes: 0 additions & 8 deletions libs/as-sdk/assembly/promise.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,6 @@ export class PromiseStatus<F, R> {
public rejected: R | null
) {}

isFulfilled(): bool {
return this.fulfilled !== null;
}

isRejected(): bool {
return this.rejected !== null;
}

static fromStr<F extends FromBuffer<F>, R extends FromBuffer<R>>(promiseStatus: string, fulfilled: F, rejected: R): PromiseStatus<F, R> {
const value = <JSON.Obj>JSON.parse(promiseStatus);
let fulfilledResult: F | null = null;
Expand Down
18 changes: 18 additions & 0 deletions libs/as-sdk/assembly/test-utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import Process from './process';

@inline
export function assert(expected: bool, message: string): void {
if (!expected) {
Process.exit_with_message(1, message);
}
}

@inline
export function ok(message: string = "ok"): void {
Process.exit_with_message(0, message);
}

@inline
export function error(message: string = "error"): void {
Process.exit_with_message(1, message);
}
3 changes: 3 additions & 0 deletions libs/vm/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# SEDA VM

Virtual Machine used for testing your Data Request using JavaScript
4 changes: 2 additions & 2 deletions libs/vm/src/vm.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ describe("vm", () => {
binary: new Uint8Array(wasmBinary),
});

expect(result).toEqual({ exitCode: 0, stderr: '', stdout: 'hello world\n', result: new Uint8Array() });
expect(result).toEqual({ exitCode: 0, stderr: '', stdout: 'hello world\n', result: new Uint8Array(), resultAsString: '' });
});

it("should exit when an invalid WASM binary is given", async () => {
Expand All @@ -45,7 +45,7 @@ describe("vm", () => {
binary: new Uint8Array([0, 97, 115, 109]),
});

expect(result).toEqual({ exitCode: 1, stderr: 'CompileError: WebAssembly.compile(): expected 4 bytes, fell off end @+4', stdout: '', result: new Uint8Array() });
expect(result).toEqual({ exitCode: 1, stderr: 'CompileError: WebAssembly.compile(): expected 4 bytes, fell off end @+4', stdout: '', result: new Uint8Array(), resultAsString: '' });
});

it('should be able to call the given adapter', async () => {
Expand Down
3 changes: 3 additions & 0 deletions libs/vm/src/vm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export interface VmResult {
stderr: string;
exitCode: number;
result?: Uint8Array;
resultAsString?: string;
}

export async function executeVm(callData: VmCallData, notifierBuffer: SharedArrayBuffer): Promise<VmResult> {
Expand Down Expand Up @@ -40,6 +41,7 @@ export async function executeVm(callData: VmCallData, notifierBuffer: SharedArra
stderr: wasi.getStderrString(),
stdout: wasi.getStdoutString(),
result: vmImports.result,
resultAsString: new TextDecoder().decode(vmImports.result),
}
} catch (err) {
console.error(`
Expand All @@ -56,6 +58,7 @@ export async function executeVm(callData: VmCallData, notifierBuffer: SharedArra
stderr: stderr !== '' ? stderr : (err + ''),
stdout: wasi.getStdoutString(),
result: new Uint8Array(),
resultAsString: '',
};
}
}
5 changes: 5 additions & 0 deletions libs/vm/src/worker-host-communication.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,11 @@ export class HostToWorker {
this.actionResult = PromiseStatus.rejected(new EmptyBuffer);
}

if (typeof this.actionResult === 'undefined') {
console.error('Objects that failed:', this, action);
throw Error(`Result was undefined while reading. Action was: ${action}`);
}

if (this.actionResult.length > MAX_I32_VALUE) {
throw Error(`Value ${this.actionResult.length} exceeds max i32 (${MAX_I32_VALUE})`);
}
Expand Down
Loading

0 comments on commit 5cb9a01

Please sign in to comment.