Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Migrates to json-event-parser #43

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
110 changes: 68 additions & 42 deletions lib/SparqlJsonParser.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
import {DataFactory} from "rdf-data-factory";
import * as RDF from "@rdfjs/types";
import {Transform} from "readable-stream";

// tslint:disable-next-line:no-var-requires
const JsonParser = require('jsonparse');
import {JsonEvent, JsonStreamPathTransformer, JsonEventParser, IQueryResult, JsonValue} from "json-event-parser";

/**
* Parser for the SPARQL 1.1 Query Results JSON format.
Expand Down Expand Up @@ -42,40 +40,57 @@ export class SparqlJsonParser {
*/
public parseJsonResultsStream(sparqlResponseStream: NodeJS.ReadableStream): NodeJS.ReadableStream {
const errorListener = (error: Error) => resultStream.emit('error', error);
sparqlResponseStream.on('error', errorListener);

const jsonParser = new JsonParser();
jsonParser.onError = errorListener;
let variablesFound = false;
let resultsFound = false;
jsonParser.onValue = (value: any) => {
if(jsonParser.key === "vars" && jsonParser.stack.length === 2 && jsonParser.stack[1].key === 'head') {
resultStream.emit('variables', value.map((v: string) => this.dataFactory.variable(v)));
variablesFound = true;
} else if(jsonParser.key === "results" && jsonParser.stack.length === 1) {
resultsFound = true;
} else if(typeof jsonParser.key === 'number' && jsonParser.stack.length === 3 && jsonParser.stack[1].key === 'results' && jsonParser.stack[2].key === 'bindings') {
resultStream.push(this.parseJsonBindings(value))
} else if(jsonParser.key === "metadata" && jsonParser.stack.length === 1) {
resultStream.emit('metadata', value);
}
}

const parser = this;
const resultStream = sparqlResponseStream
.on("end", _ => {
if (!resultsFound && !this.suppressMissingStreamResultsError) {
resultStream.emit("error", new Error("No valid SPARQL query results were found."))
} else if (!variablesFound) {
resultStream.emit('variables', []);
}
})
.pipe(new Transform({
objectMode: true,
transform(chunk: any, encoding: string, callback: (error?: Error | null, data?: any) => void) {
jsonParser.write(chunk);
callback();
}
}));
.on('error', errorListener)
.pipe(new JsonEventParser())
.on('error', errorListener)
.pipe(new JsonStreamPathTransformer([
{id: 'vars', query: ['head', 'vars'], returnContent: true},
{id: 'bindings', query: ['results', 'bindings'], returnContent: false},
{id: 'binding', query: ['results', 'bindings', null], returnContent: true},
{id: 'metadata', query: ['metadata'], returnContent: true},
]))
.on('error', errorListener)
.pipe(
new Transform({
writableObjectMode: true,
readableObjectMode: true,
transform(result: IQueryResult, encoding: string, callback: (error?: Error | null, data?: any) => void): void {
try {
switch (result.query) {
case 'vars':
variablesFound = true;
this.emit('variables', parser.parseVariableList(result.value));
break;
case 'bindings':
resultsFound = true;
break;
case 'binding':
this.push(parser.parseJsonBindings(result.value));
break;
case 'metadata':
this.emit('metadata', result.value);
}
callback();
} catch (e: any) {
callback(e);
}
},
flush(callback: (error?: Error | null, data?: any) => void): void {
if (!resultsFound && !this.suppressMissingStreamResultsError) {
callback(new Error("No valid SPARQL query results were found."));
return;
}
if (!variablesFound) {
this.emit('variables', []);
}
callback();
}
})
);
return resultStream;
}

Expand Down Expand Up @@ -136,20 +151,31 @@ export class SparqlJsonParser {
*/
public parseJsonBooleanStream(sparqlResponseStream: NodeJS.ReadableStream): Promise<boolean> {
return new Promise((resolve, reject) => {
const parser = new JsonParser();
parser.onError = reject;
parser.onValue = (value: any) => {
if(parser.key === "boolean" && typeof value === 'boolean' && parser.stack.length === 1) {
resolve(value);
}
}
sparqlResponseStream
.on('error', reject)
.on('data', d => parser.write(d))
.pipe(new JsonEventParser())
.on('error', reject)
.on('data', (event: JsonEvent) => {
if(event.type === 'value' && event.key === 'boolean' && typeof event.value === 'boolean') {
resolve(event.value);
}
})
.on('end', () => reject(new Error('No valid ASK response was found.')));
});
}

private parseVariableList(variables: JsonValue): RDF.Variable[] {
if(!Array.isArray(variables)) {
throw new Error("The variable list should be an array");
}
return variables.map(v => {
if(typeof v === "string") {
return this.dataFactory.variable(v);
} else {
throw new Error("Variable names should be strings");
}
});
}
}

/**
Expand Down
8 changes: 3 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
"devDependencies": {
"@types/jest": "^28.0.0",
"@types/minimist": "^1.2.0",
"@types/readable-stream": "^2.3.14",
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess this one should be added as non-dev dep to json-event-parser.

Copy link
Contributor Author

@Tpt Tpt Oct 10, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure it's required. json-event-parser works from plain JS projects without needing @types/readable-stream. What do you think about it?

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The convention in TS is that typings packages are included as non-dev deps, so that downstream users don't have to include all of these typing packages manually (which can incur in a lot of overhead for many transitive deps). And since typings packages are usually very small, this is not a problem for non-TS projects.

Copy link
Contributor Author

@Tpt Tpt Oct 11, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"arrayify-stream": "^2.0.0",
"coveralls": "^3.0.0",
"jest": "^28.0.0",
Expand Down Expand Up @@ -82,11 +83,8 @@
},
"dependencies": {
"@rdfjs/types": "*",
"@types/readable-stream": "^2.3.13",
"buffer": "^6.0.3",
"jsonparse": "^1.3.1",
"rdf-data-factory": "^1.1.0",
"readable-stream": "^4.0.0"
"json-event-parser": "1.0.0-beta.2",
"rdf-data-factory": "^1.1.0"
},
"sideEffects": false
}
19 changes: 19 additions & 0 deletions test/SparqlJsonParser-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,17 @@ describe('SparqlJsonParser', () => {
`)))).toEqual([]);
});

it('should convert a slightly invalid empty SPARQL JSON response (common PHP error)', async () => {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is this slightly invalid? (looks valid to me at first glance)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Because the "bindings" key value should be an array and not an object.

return expect(await arrayifyStream(parser.parseJsonResultsStream(streamifyString(`
{
"head": { "vars": [] },
"results": {
"bindings": {}
}
}
`)))).toEqual([]);
});

it('should convert an empty SPARQL JSON response and emit the variables', async () => {
const stream = parser.parseJsonResultsStream(streamifyString(`
{
Expand Down Expand Up @@ -172,6 +183,14 @@ describe('SparqlJsonParser', () => {
return expect(arrayifyStream(parser.parseJsonResultsStream(streamifyString('{')))).rejects.toBeTruthy();
});

it('should reject on an invalid variables', async () => {
return expect(arrayifyStream(parser.parseJsonResultsStream(streamifyString('{"head": {"vars": null}, "results": {"bindings": []}}')))).rejects.toBeTruthy();
});

it('should reject on an invalid variables 2', async () => {
return expect(arrayifyStream(parser.parseJsonResultsStream(streamifyString('{"head": {"vars": [[]]}, "results": {"bindings": []}}')))).rejects.toBeTruthy();
});

it('should emit an error on an erroring stream', async () => {
const errorStream = new PassThrough();
errorStream._read = () => errorStream.emit('error', new Error('Some stream error'));
Expand Down
38 changes: 24 additions & 14 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -695,10 +695,10 @@
resolved "https://registry.yarnpkg.com/@types/prettier/-/prettier-2.6.3.tgz#68ada76827b0010d0db071f739314fa429943d0a"
integrity sha512-ymZk3LEC/fsut+/Q5qejp6R9O1rMxz3XaRHDV6kX8MrGAhOSPqVARbDi+EZvInBpw+BnCX3TD240byVkOfQsHg==

"@types/readable-stream@^2.3.13":
version "2.3.13"
resolved "https://registry.yarnpkg.com/@types/readable-stream/-/readable-stream-2.3.13.tgz#46451c1b87cb61010e420ac02a76cfc1b2c2089a"
integrity sha512-4JSCx8EUzaW9Idevt+9lsRAt1lcSccoQfE+AouM1gk8sFxnnytKNIO3wTl9Dy+4m6jRJ1yXhboLHHT/LXBQiEw==
"@types/readable-stream@^2.3.14":
version "2.3.14"
resolved "https://registry.yarnpkg.com/@types/readable-stream/-/readable-stream-2.3.14.tgz#1282cdc03a1fc9ed52982aa8f0553d7c251070b9"
integrity sha512-8jQ5Mp7bsDJEnW/69i6nAaQMoLwAVJVc7ZRAVTrdh/o6XueQsX38TEvKuYyoQj76/mg7WdlRfMrtl9pDLCJWsg==
dependencies:
"@types/node" "*"
safe-buffer "*"
Expand Down Expand Up @@ -1527,7 +1527,7 @@ event-target-shim@^5.0.0:
resolved "https://registry.yarnpkg.com/event-target-shim/-/event-target-shim-5.0.1.tgz#5d4d3ebdf9583d63a5333ce2deb7480ab2b05789"
integrity sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==

events@^3.2.0:
events@^3.2.0, events@^3.3.0:
version "3.3.0"
resolved "https://registry.yarnpkg.com/events/-/events-3.3.0.tgz#31a95ad0a924e2d2c419a813aeb2c4e878ea7400"
integrity sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==
Expand Down Expand Up @@ -2369,6 +2369,13 @@ jsesc@^2.5.1:
resolved "https://registry.yarnpkg.com/jsesc/-/jsesc-2.5.2.tgz#80564d2e483dacf6e8ef209650a67df3f0c283a4"
integrity sha512-OYu7XEzjkCQ3C5Ps3QIZsQfNpqoJyZZA99wd9aWd05NCtC5pWOkShK2mkL6HXQR6/Cy2lbNdPlZBpuQHXE63gA==

[email protected]:
version "1.0.0-beta.2"
resolved "https://registry.yarnpkg.com/json-event-parser/-/json-event-parser-1.0.0-beta.2.tgz#9a77f624bffeefd21b232b168c7051962db6eb3f"
integrity sha512-ibZRC+dzDmpsJkoHJ5yUONOL3x5i4LPgN7cyGW/iBras3h+KnPnslHNOuZRA1l20/XKXyj6roRasfa6Dx9nFww==
dependencies:
readable-stream "^4.2.0"

json-parse-better-errors@^1.0.1:
version "1.0.2"
resolved "https://registry.yarnpkg.com/json-parse-better-errors/-/json-parse-better-errors-1.0.2.tgz#bb867cfb3450e69107c131d1c514bab3dc8bcaa9"
Expand Down Expand Up @@ -2399,11 +2406,6 @@ json5@^2.2.1:
resolved "https://registry.yarnpkg.com/json5/-/json5-2.2.1.tgz#655d50ed1e6f95ad1a3caababd2b0efda10b395c"
integrity sha512-1hqLFMSrGHRHxav9q9gNjJ5EXznIxGVO09xQRrwplcS8qs28pZ8s8hupZAmqDwZUmVZ2Qb2jnyPOWcDH8m8dlA==

jsonparse@^1.3.1:
version "1.3.1"
resolved "https://registry.yarnpkg.com/jsonparse/-/jsonparse-1.3.1.tgz#3f4dae4a91fac315f71062f8521cc239f1366280"
integrity sha512-POQXvpdL69+CluYsillJ7SUhKvytYjW9vG/GKpnf+xP8UWgYEM/RaMzHHofbALDiKbbP1W8UEYmgGl39WkPZsg==

jsprim@^1.2.2:
version "1.4.2"
resolved "https://registry.yarnpkg.com/jsprim/-/jsprim-1.4.2.tgz#712c65533a15c878ba59e9ed5f0e26d5b77c5feb"
Expand Down Expand Up @@ -2885,6 +2887,11 @@ process-nextick-args@~2.0.0:
resolved "https://registry.yarnpkg.com/process-nextick-args/-/process-nextick-args-2.0.1.tgz#7820d9b16120cc55ca9ae7792680ae7dba6d7fe2"
integrity sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==

process@^0.11.10:
version "0.11.10"
resolved "https://registry.yarnpkg.com/process/-/process-0.11.10.tgz#7332300e840161bda3e69a1d1d91a7d4bc16f182"
integrity sha512-cdGef/drWFoydD1JsMzuFf8100nZl+GT+yacc2bEced5f9Rjk4z+WtFUTBu9PhOi9j/jfmBPu0mMEY4wIdAF8A==

prompts@^2.0.1:
version "2.4.2"
resolved "https://registry.yarnpkg.com/prompts/-/prompts-2.4.2.tgz#7b57e73b3a48029ad10ebd44f74b01722a4cb069"
Expand Down Expand Up @@ -3027,12 +3034,15 @@ readable-stream@^2.2.2, readable-stream@~2.3.6:
string_decoder "~1.1.1"
util-deprecate "~1.0.1"

readable-stream@^4.0.0:
version "4.0.0"
resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-4.0.0.tgz#da7105d03430a28ef4080785a43e6a45d4cdc4d1"
integrity sha512-Mf7ilWBP6AV3tF3MjtBrHMH3roso7wIrpgzCwt9ybvqiJQVWIEBMnp/W+S//yvYSsUUi2cJIwD7q7m57l0AqZw==
readable-stream@^4.2.0:
version "4.2.0"
resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-4.2.0.tgz#a7ef523d3b39e4962b0db1a1af22777b10eeca46"
integrity sha512-gJrBHsaI3lgBoGMW/jHZsQ/o/TIWiu5ENCJG1BB7fuCKzpFM8GaS2UoBVt9NO+oI+3FcrBNbUkl3ilDe09aY4A==
dependencies:
abort-controller "^3.0.0"
buffer "^6.0.3"
events "^3.3.0"
process "^0.11.10"

rechoir@^0.7.0:
version "0.7.1"
Expand Down