@comunica/actor-query-source-identify-hypermedia-sparql 5.4.0 → 5.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -208,8 +208,8 @@
|
|
|
208
208
|
"memberFieldName": "cache"
|
|
209
209
|
},
|
|
210
210
|
{
|
|
211
|
-
"@id": "caqsihs:components/QuerySourceSparql.jsonld#
|
|
212
|
-
"memberFieldName": "
|
|
211
|
+
"@id": "caqsihs:components/QuerySourceSparql.jsonld#QuerySourceSparql__member_httpRequestsByPlanNode",
|
|
212
|
+
"memberFieldName": "httpRequestsByPlanNode"
|
|
213
213
|
},
|
|
214
214
|
{
|
|
215
215
|
"@id": "caqsihs:components/QuerySourceSparql.jsonld#QuerySourceSparql__member_httpQueryMethodRejected",
|
|
@@ -219,6 +219,14 @@
|
|
|
219
219
|
"@id": "caqsihs:components/QuerySourceSparql.jsonld#QuerySourceSparql__member_constructor",
|
|
220
220
|
"memberFieldName": "constructor"
|
|
221
221
|
},
|
|
222
|
+
{
|
|
223
|
+
"@id": "caqsihs:components/QuerySourceSparql.jsonld#QuerySourceSparql__member_getRequestOptions",
|
|
224
|
+
"memberFieldName": "getRequestOptions"
|
|
225
|
+
},
|
|
226
|
+
{
|
|
227
|
+
"@id": "caqsihs:components/QuerySourceSparql.jsonld#QuerySourceSparql__member_fetch",
|
|
228
|
+
"memberFieldName": "fetch"
|
|
229
|
+
},
|
|
222
230
|
{
|
|
223
231
|
"@id": "caqsihs:components/QuerySourceSparql.jsonld#QuerySourceSparql__member_getFilterFactor",
|
|
224
232
|
"memberFieldName": "getFilterFactor"
|
|
@@ -227,6 +235,14 @@
|
|
|
227
235
|
"@id": "caqsihs:components/QuerySourceSparql.jsonld#QuerySourceSparql__member_getSelectorShape",
|
|
228
236
|
"memberFieldName": "getSelectorShape"
|
|
229
237
|
},
|
|
238
|
+
{
|
|
239
|
+
"@id": "caqsihs:components/QuerySourceSparql.jsonld#QuerySourceSparql__member_reportSourceQuery",
|
|
240
|
+
"memberFieldName": "reportSourceQuery"
|
|
241
|
+
},
|
|
242
|
+
{
|
|
243
|
+
"@id": "caqsihs:components/QuerySourceSparql.jsonld#QuerySourceSparql__member_countHttpRequest",
|
|
244
|
+
"memberFieldName": "countHttpRequest"
|
|
245
|
+
},
|
|
230
246
|
{
|
|
231
247
|
"@id": "caqsihs:components/QuerySourceSparql.jsonld#QuerySourceSparql__member_queryBindings",
|
|
232
248
|
"memberFieldName": "queryBindings"
|
|
@@ -275,6 +291,10 @@
|
|
|
275
291
|
"@id": "caqsihs:components/QuerySourceSparql.jsonld#QuerySourceSparql__member_operationToQuery",
|
|
276
292
|
"memberFieldName": "operationToQuery"
|
|
277
293
|
},
|
|
294
|
+
{
|
|
295
|
+
"@id": "caqsihs:components/QuerySourceSparql.jsonld#QuerySourceSparql__member_getQueryStringAsIs",
|
|
296
|
+
"memberFieldName": "getQueryStringAsIs"
|
|
297
|
+
},
|
|
278
298
|
{
|
|
279
299
|
"@id": "caqsihs:components/QuerySourceSparql.jsonld#QuerySourceSparql__member_getOperationUndefs",
|
|
280
300
|
"memberFieldName": "getOperationUndefs"
|
|
@@ -6,6 +6,7 @@ import { Algebra } from '@comunica/utils-algebra';
|
|
|
6
6
|
import type { BindingsFactory } from '@comunica/utils-bindings-factory';
|
|
7
7
|
import type * as RDF from '@rdfjs/types';
|
|
8
8
|
import type { AsyncIterator } from 'asynciterator';
|
|
9
|
+
import type { ISparqlEndpointFetcherRequestOptions } from 'fetch-sparql-endpoint';
|
|
9
10
|
import type { BindMethod } from './ActorQuerySourceIdentifyHypermediaSparql';
|
|
10
11
|
export declare class QuerySourceSparql implements IQuerySource {
|
|
11
12
|
/**
|
|
@@ -32,11 +33,38 @@ export declare class QuerySourceSparql implements IQuerySource {
|
|
|
32
33
|
private readonly bindingsFactory;
|
|
33
34
|
private readonly endpointFetcher;
|
|
34
35
|
private readonly cache;
|
|
35
|
-
|
|
36
|
+
/**
|
|
37
|
+
* The number of HTTP requests made for each physical query plan node.
|
|
38
|
+
*/
|
|
39
|
+
private readonly httpRequestsByPlanNode;
|
|
36
40
|
private httpQueryMethodRejected;
|
|
37
41
|
constructor(url: string, urlBackup: string, context: IActionContext, mediatorHttp: MediatorHttp, mediatorQuerySerialize: MediatorQuerySerialize, bindMethod: BindMethod, dataFactory: ComunicaDataFactory, algebraFactory: AlgebraFactory, bindingsFactory: BindingsFactory, forceHttpGet: boolean, cacheSize: number, countTimeout: number, cardinalityCountQueries: boolean, cardinalityEstimateConstruction: boolean, forceGetIfUrlLengthBelow: number, parseUnsupportedVersions: boolean, metadata: Record<string, any>);
|
|
42
|
+
/**
|
|
43
|
+
* Create the options for requests to the endpoint on behalf of the given context,
|
|
44
|
+
* so that each request is sent with the context of the query that issued it.
|
|
45
|
+
* @param context The context of the query operation for which requests are sent.
|
|
46
|
+
*/
|
|
47
|
+
protected getRequestOptions(context: IActionContext): ISparqlEndpointFetcherRequestOptions;
|
|
48
|
+
/**
|
|
49
|
+
* Send an HTTP request to the endpoint.
|
|
50
|
+
* @param input The request input.
|
|
51
|
+
* @param init The request options.
|
|
52
|
+
* @param context The context of the query operation for which the request is sent.
|
|
53
|
+
*/
|
|
54
|
+
protected fetch(input: Request | string, init: RequestInit | undefined, context: IActionContext): Promise<Response>;
|
|
38
55
|
getFilterFactor(): Promise<number>;
|
|
39
56
|
getSelectorShape(): Promise<FragmentSelectorShape>;
|
|
57
|
+
/**
|
|
58
|
+
* Report the query that is sent to the endpoint to the physical query plan, if one is being logged.
|
|
59
|
+
* @param context The context of the current operation.
|
|
60
|
+
* @param query The query that is sent to the endpoint.
|
|
61
|
+
*/
|
|
62
|
+
protected reportSourceQuery(context: IActionContext, query: string): void;
|
|
63
|
+
/**
|
|
64
|
+
* Count an HTTP request against the physical query plan node of the operation it is made on behalf of.
|
|
65
|
+
* @param context The context of the operation for which the request is sent.
|
|
66
|
+
*/
|
|
67
|
+
protected countHttpRequest(context: IActionContext): void;
|
|
40
68
|
queryBindings(operationIn: Algebra.Operation, context: IActionContext, options?: IQueryBindingsOptions): BindingsStream;
|
|
41
69
|
queryQuads(operation: Algebra.Operation, context: IActionContext): AsyncIterator<RDF.Quad>;
|
|
42
70
|
queryBoolean(operation: Algebra.Ask, context: IActionContext): Promise<boolean>;
|
|
@@ -97,6 +125,13 @@ export declare class QuerySourceSparql implements IQuerySource {
|
|
|
97
125
|
* @return {string} A query string.
|
|
98
126
|
*/
|
|
99
127
|
operationToQuery(operation: Algebra.Operation): Promise<string>;
|
|
128
|
+
/**
|
|
129
|
+
* Obtain the SPARQL query string that may be sent as-is for the given operation.
|
|
130
|
+
* @param operation A query operation.
|
|
131
|
+
* @param context The action context.
|
|
132
|
+
* @return The query string to send as-is, or undefined if the operation must be serialized.
|
|
133
|
+
*/
|
|
134
|
+
static getQueryStringAsIs(operation: Algebra.Operation, context: IActionContext): string | undefined;
|
|
100
135
|
/**
|
|
101
136
|
* Check if the given operation may produce undefined values.
|
|
102
137
|
* @param operation
|
package/lib/QuerySourceSparql.js
CHANGED
|
@@ -35,7 +35,10 @@ class QuerySourceSparql {
|
|
|
35
35
|
bindingsFactory;
|
|
36
36
|
endpointFetcher;
|
|
37
37
|
cache;
|
|
38
|
-
|
|
38
|
+
/**
|
|
39
|
+
* The number of HTTP requests made for each physical query plan node.
|
|
40
|
+
*/
|
|
41
|
+
httpRequestsByPlanNode = new WeakMap();
|
|
39
42
|
httpQueryMethodRejected = false;
|
|
40
43
|
constructor(url, urlBackup, context, mediatorHttp, mediatorQuerySerialize, bindMethod, dataFactory, algebraFactory, bindingsFactory, forceHttpGet, cacheSize, countTimeout, cardinalityCountQueries, cardinalityEstimateConstruction, forceGetIfUrlLengthBelow, parseUnsupportedVersions, metadata) {
|
|
41
44
|
this.referenceValue = urlBackup;
|
|
@@ -59,28 +62,6 @@ class QuerySourceSparql {
|
|
|
59
62
|
}
|
|
60
63
|
this.endpointFetcher = new fetch_sparql_endpoint_1.SparqlEndpointFetcher({
|
|
61
64
|
method,
|
|
62
|
-
fetch: async (input, init) => {
|
|
63
|
-
// The advertisement may be stale, or an intermediary may not know the method,
|
|
64
|
-
// in which case we permanently fall back to a direct POST, which carries an identical body.
|
|
65
|
-
if (this.httpQueryMethodRejected && init?.method === 'QUERY') {
|
|
66
|
-
init = { ...init, method: 'POST' };
|
|
67
|
-
}
|
|
68
|
-
let response = await this.mediatorHttp.mediate({ input, init, context: this.lastSourceContext });
|
|
69
|
-
// If we encounter a 404, try our backup URL.
|
|
70
|
-
// After retrying the request with the new URL, we replace the URL for future requests.
|
|
71
|
-
if (response.status === 404 && this.url !== this.urlBackup) {
|
|
72
|
-
core_1.Actor.getContextLogger(this.context)?.warn(`Encountered a 404 when requesting ${this.url} according to the service description of ${this.urlBackup}. This is a server configuration issue. Retrying the current and modifying future requests to ${this.urlBackup} instead.`);
|
|
73
|
-
input = input.replace(this.url, this.urlBackup);
|
|
74
|
-
this.url = this.urlBackup;
|
|
75
|
-
response = await this.mediatorHttp.mediate({ input, init, context: this.lastSourceContext });
|
|
76
|
-
}
|
|
77
|
-
if (init?.method === 'QUERY' && (response.status === 405 || response.status === 501)) {
|
|
78
|
-
core_1.Actor.getContextLogger(this.context)?.warn(`Encountered a ${response.status} for an HTTP QUERY request to ${this.url}, even though it advertises support for it via the Accept-Query header. Retrying the current and modifying future requests to use POST instead.`);
|
|
79
|
-
this.httpQueryMethodRejected = true;
|
|
80
|
-
response = await this.mediatorHttp.mediate({ input, init: { ...init, method: 'POST' }, context: this.lastSourceContext });
|
|
81
|
-
}
|
|
82
|
-
return response;
|
|
83
|
-
},
|
|
84
65
|
prefixVariableQuestionMark: true,
|
|
85
66
|
dataFactory,
|
|
86
67
|
forceGetIfUrlLengthBelow,
|
|
@@ -99,6 +80,45 @@ class QuerySourceSparql {
|
|
|
99
80
|
this.extensionFunctions = metadata.extensionFunctions;
|
|
100
81
|
this.propertyFeatures = metadata.propertyFeatures ? new Set(metadata.propertyFeatures) : undefined;
|
|
101
82
|
}
|
|
83
|
+
/**
|
|
84
|
+
* Create the options for requests to the endpoint on behalf of the given context,
|
|
85
|
+
* so that each request is sent with the context of the query that issued it.
|
|
86
|
+
* @param context The context of the query operation for which requests are sent.
|
|
87
|
+
*/
|
|
88
|
+
getRequestOptions(context) {
|
|
89
|
+
return { fetch: (input, init) => this.fetch(input, init, context) };
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Send an HTTP request to the endpoint.
|
|
93
|
+
* @param input The request input.
|
|
94
|
+
* @param init The request options.
|
|
95
|
+
* @param context The context of the query operation for which the request is sent.
|
|
96
|
+
*/
|
|
97
|
+
async fetch(input, init, context) {
|
|
98
|
+
// The advertisement may be stale, or an intermediary may not know the method,
|
|
99
|
+
// in which case we permanently fall back to a direct POST, which carries an identical body.
|
|
100
|
+
if (this.httpQueryMethodRejected && init?.method === 'QUERY') {
|
|
101
|
+
init = { ...init, method: 'POST' };
|
|
102
|
+
}
|
|
103
|
+
this.countHttpRequest(context);
|
|
104
|
+
let response = await this.mediatorHttp.mediate({ input, init, context });
|
|
105
|
+
// If we encounter a 404, try our backup URL.
|
|
106
|
+
// After retrying the request with the new URL, we replace the URL for future requests.
|
|
107
|
+
if (response.status === 404 && this.url !== this.urlBackup) {
|
|
108
|
+
core_1.Actor.getContextLogger(this.context)?.warn(`Encountered a 404 when requesting ${this.url} according to the service description of ${this.urlBackup}. This is a server configuration issue. Retrying the current and modifying future requests to ${this.urlBackup} instead.`);
|
|
109
|
+
input = input.replace(this.url, this.urlBackup);
|
|
110
|
+
this.url = this.urlBackup;
|
|
111
|
+
this.countHttpRequest(context);
|
|
112
|
+
response = await this.mediatorHttp.mediate({ input, init, context });
|
|
113
|
+
}
|
|
114
|
+
if (init?.method === 'QUERY' && (response.status === 405 || response.status === 501)) {
|
|
115
|
+
core_1.Actor.getContextLogger(this.context)?.warn(`Encountered a ${response.status} for an HTTP QUERY request to ${this.url}, even though it advertises support for it via the Accept-Query header. Retrying the current and modifying future requests to use POST instead.`);
|
|
116
|
+
this.httpQueryMethodRejected = true;
|
|
117
|
+
this.countHttpRequest(context);
|
|
118
|
+
response = await this.mediatorHttp.mediate({ input, init: { ...init, method: 'POST' }, context });
|
|
119
|
+
}
|
|
120
|
+
return response;
|
|
121
|
+
}
|
|
102
122
|
async getFilterFactor() {
|
|
103
123
|
return 1;
|
|
104
124
|
}
|
|
@@ -152,6 +172,26 @@ class QuerySourceSparql {
|
|
|
152
172
|
],
|
|
153
173
|
};
|
|
154
174
|
}
|
|
175
|
+
/**
|
|
176
|
+
* Report the query that is sent to the endpoint to the physical query plan, if one is being logged.
|
|
177
|
+
* @param context The context of the current operation.
|
|
178
|
+
* @param query The query that is sent to the endpoint.
|
|
179
|
+
*/
|
|
180
|
+
reportSourceQuery(context, query) {
|
|
181
|
+
context.get(context_entries_1.KeysInitQuery.physicalQueryPlanNode)?.appendMetadata({ sourceQuery: query });
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* Count an HTTP request against the physical query plan node of the operation it is made on behalf of.
|
|
185
|
+
* @param context The context of the operation for which the request is sent.
|
|
186
|
+
*/
|
|
187
|
+
countHttpRequest(context) {
|
|
188
|
+
const planNode = context.get(context_entries_1.KeysInitQuery.physicalQueryPlanNode);
|
|
189
|
+
if (planNode) {
|
|
190
|
+
const httpRequests = (this.httpRequestsByPlanNode.get(planNode) ?? 0) + 1;
|
|
191
|
+
this.httpRequestsByPlanNode.set(planNode, httpRequests);
|
|
192
|
+
planNode.appendMetadata({ httpRequests });
|
|
193
|
+
}
|
|
194
|
+
}
|
|
155
195
|
queryBindings(operationIn, context, options) {
|
|
156
196
|
// If bindings are passed, modify the operations
|
|
157
197
|
let operationPromise;
|
|
@@ -165,12 +205,12 @@ class QuerySourceSparql {
|
|
|
165
205
|
// Prepare queries
|
|
166
206
|
const operation = await operationPromise;
|
|
167
207
|
const variables = utils_algebra_1.algebraUtils.inScopeVariables(operation);
|
|
168
|
-
|
|
169
|
-
const
|
|
170
|
-
const selectQuery =
|
|
171
|
-
queryString :
|
|
208
|
+
// Join bindings modify the operation, so it is no longer equivalent to the original query string.
|
|
209
|
+
const queryString = options?.joinBindings ? undefined : QuerySourceSparql.getQueryStringAsIs(operation, context);
|
|
210
|
+
const selectQuery = queryString ??
|
|
172
211
|
await this.operationToSelectQuery(this.algebraFactory, operation, variables);
|
|
173
212
|
const undefVariables = QuerySourceSparql.getOperationUndefs(operation);
|
|
213
|
+
this.reportSourceQuery(context, selectQuery);
|
|
174
214
|
return this.queryBindingsRemote(this.url, selectQuery, variables, context, undefVariables);
|
|
175
215
|
}, { autoStart: false });
|
|
176
216
|
this.attachMetadata(bindings, context, operationPromise);
|
|
@@ -178,9 +218,10 @@ class QuerySourceSparql {
|
|
|
178
218
|
}
|
|
179
219
|
queryQuads(operation, context) {
|
|
180
220
|
const quads = (0, asynciterator_1.wrap)((async () => {
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
221
|
+
const query = QuerySourceSparql.getQueryStringAsIs(operation, context) ??
|
|
222
|
+
await this.operationToQuery(operation);
|
|
223
|
+
this.reportSourceQuery(context, query);
|
|
224
|
+
const rawStream = await this.endpointFetcher.fetchTriples(this.url, query, this.getRequestOptions(context));
|
|
184
225
|
return rawStream;
|
|
185
226
|
})(), { autoStart: false, maxBufferSize: Number.POSITIVE_INFINITY });
|
|
186
227
|
this.attachMetadata(quads, context, Promise.resolve(operation.input));
|
|
@@ -192,15 +233,17 @@ class QuerySourceSparql {
|
|
|
192
233
|
return true;
|
|
193
234
|
}
|
|
194
235
|
// Without propertyFeature overlap, perform the actual ASK query.
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
236
|
+
const query = QuerySourceSparql.getQueryStringAsIs(operation, context) ??
|
|
237
|
+
await this.operationToQuery(operation);
|
|
238
|
+
this.reportSourceQuery(context, query);
|
|
239
|
+
const promise = this.endpointFetcher.fetchAsk(this.url, query, this.getRequestOptions(context));
|
|
198
240
|
return promise;
|
|
199
241
|
}
|
|
200
242
|
async queryVoid(operation, context) {
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
243
|
+
const query = QuerySourceSparql.getQueryStringAsIs(operation, context) ??
|
|
244
|
+
await this.operationToQuery(operation);
|
|
245
|
+
this.reportSourceQuery(context, query);
|
|
246
|
+
const promise = this.endpointFetcher.fetchUpdate(this.url, query, this.getRequestOptions(context));
|
|
204
247
|
return promise;
|
|
205
248
|
}
|
|
206
249
|
attachMetadata(target, context, operationPromise) {
|
|
@@ -234,14 +277,23 @@ class QuerySourceSparql {
|
|
|
234
277
|
if (!this.cardinalityCountQueries) {
|
|
235
278
|
return resolve({ type: 'estimate', value: Number.POSITIVE_INFINITY, dataset: this.url });
|
|
236
279
|
}
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
280
|
+
// Abort the count request on timeout, so that it does not keep occupying the endpoint.
|
|
281
|
+
const abortController = new AbortController();
|
|
282
|
+
const existingAbortSignal = context.get(context_entries_1.KeysHttp.httpAbortSignal);
|
|
283
|
+
const countContext = context.set(context_entries_1.KeysHttp.httpAbortSignal, existingAbortSignal ?
|
|
284
|
+
AbortSignal.any([existingAbortSignal, abortController.signal]) :
|
|
285
|
+
abortController.signal);
|
|
286
|
+
const timeoutHandler = setTimeout(() => {
|
|
287
|
+
resolve({
|
|
288
|
+
type: 'estimate',
|
|
289
|
+
value: Number.POSITIVE_INFINITY,
|
|
290
|
+
dataset: this.url,
|
|
291
|
+
});
|
|
292
|
+
abortController.abort();
|
|
293
|
+
}, this.countTimeout);
|
|
242
294
|
const varCount = this.dataFactory.variable('count');
|
|
243
295
|
const bindingsStream = await this
|
|
244
|
-
.queryBindingsRemote(this.url, countQuery, [varCount],
|
|
296
|
+
.queryBindingsRemote(this.url, countQuery, [varCount], countContext, []);
|
|
245
297
|
bindingsStream
|
|
246
298
|
.on('data', (bindings) => {
|
|
247
299
|
clearTimeout(timeoutHandler);
|
|
@@ -428,6 +480,16 @@ class QuerySourceSparql {
|
|
|
428
480
|
context: this.context,
|
|
429
481
|
})).query;
|
|
430
482
|
}
|
|
483
|
+
/**
|
|
484
|
+
* Obtain the SPARQL query string that may be sent as-is for the given operation.
|
|
485
|
+
* @param operation A query operation.
|
|
486
|
+
* @param context The action context.
|
|
487
|
+
* @return The query string to send as-is, or undefined if the operation must be serialized.
|
|
488
|
+
*/
|
|
489
|
+
static getQueryStringAsIs(operation, context) {
|
|
490
|
+
// TODO: next/major - remove the fallback to the original query string, see KeysInitQuery.queryString.
|
|
491
|
+
return (0, utils_query_operation_1.getOperationEquivalentQueryString)(operation) ?? (0, utils_query_operation_1.getOriginalSparqlQueryString)(context);
|
|
492
|
+
}
|
|
431
493
|
/**
|
|
432
494
|
* Check if the given operation may produce undefined values.
|
|
433
495
|
* @param operation
|
|
@@ -478,8 +540,7 @@ class QuerySourceSparql {
|
|
|
478
540
|
async queryBindingsRemote(endpoint, query, variables, context, undefVariables) {
|
|
479
541
|
// Index undef variables
|
|
480
542
|
const undefVariablesSet = new Set(undefVariables.map(v => v.value));
|
|
481
|
-
|
|
482
|
-
const rawStream = await this.endpointFetcher.fetchBindings(endpoint, query);
|
|
543
|
+
const rawStream = await this.endpointFetcher.fetchBindings(endpoint, query, this.getRequestOptions(context));
|
|
483
544
|
const wrapped = (0, asynciterator_1.wrap)(rawStream, { autoStart: false, maxBufferSize: Number.POSITIVE_INFINITY });
|
|
484
545
|
return wrapped.map((rawData) => {
|
|
485
546
|
const bindings = variables.map((variable) => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"QuerySourceSparql.js","sourceRoot":"","sources":["QuerySourceSparql.ts"],"names":[],"mappings":";;;AAEA,+DAA0D;AAC1D,yCAAuC;AAevC,2DAAkF;AAElF,6DAAmE;AACnE,2EAAsE;AAGtE,iDAAwD;AACxD,iEAA8D;AAC9D,yCAAqC;AACrC,yCAAsC;AAGtC,MAAa,iBAAiB;IAC5B;;OAEG;IACI,MAAM,CAAU,sBAAsB,GAAG,0BAA0B,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IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;QACrD,MAAM,SAAS,GAAG,MAAM,IAAI,CAAC,eAAe,CAAC,aAAa,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC;QAE5E,MAAM,OAAO,GAAG,IAAA,oBAAI,EAAM,SAAS,EAAE,EAAE,SAAS,EAAE,KAAK,EAAE,aAAa,EAAE,MAAM,CAAC,iBAAiB,EAAE,CAAC,CAAC;QACpG,OAAO,OAAO,CAAC,GAAG,CAAe,CAAC,OAAiC,EAAE,EAAE;YACrE,MAAM,QAAQ,GAAG,SAAS,CAAC,GAAG,CAAC,CAAC,QAAQ,EAAE,EAAE;gBAC1C,MAAM,KAAK,GAAG,OAAO,CAAC,IAAI,QAAQ,CAAC,KAAK,EAAE,CAAC,CAAC;gBAC5C,IAAI,CAAC,iBAAiB,CAAC,GAAG,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,EAAE,CAAC;oBACrD,YAAK,CAAC,gBAAgB,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,IAAI,CAAC,gBAAgB,QAAQ,oCAAoC,QAAQ,CAAC,KAAK,GAAG,CAAC,CAAC;gBAC5H,CAAC;gBACD,OAAiC,CAAE,QAAQ,EAAE,KAAK,CAAE,CAAC;YACvD,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAE,CAAC,EAAE,CAAC,CAAE,EAAE,EAAE,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC;YACpC,OAAO,IAAI,CAAC,eAAe,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;QACjD,CAAC,CAAC,CAAC;IACL,CAAC;IAEM,QAAQ;QACb,OAAO,qBAAqB,IAAI,CAAC,GAAG,GAAG,CAAC;IAC1C,CAAC;;AA3lBH,8CA4lBC","sourcesContent":["import type { MediatorHttp } from '@comunica/bus-http';\nimport type { MediatorQuerySerialize } from '@comunica/bus-query-serialize';\nimport { KeysInitQuery } from '@comunica/context-entries';\nimport { Actor } from '@comunica/core';\nimport type {\n Bindings,\n BindingsStream,\n ComunicaDataFactory,\n FragmentSelectorShape,\n IActionContext,\n IDataset,\n IQueryBindingsOptions,\n IQuerySource,\n MetadataBindings,\n MetadataVariable,\n QueryResultCardinality,\n} from '@comunica/types';\nimport type { AlgebraFactory } from '@comunica/utils-algebra';\nimport { Algebra, algebraUtils, isKnownOperation } from '@comunica/utils-algebra';\nimport type { BindingsFactory } from '@comunica/utils-bindings-factory';\nimport { MetadataValidationState } from '@comunica/utils-metadata';\nimport { estimateCardinality } from '@comunica/utils-query-operation';\nimport type * as RDF from '@rdfjs/types';\nimport type { AsyncIterator } from 'asynciterator';\nimport { TransformIterator, wrap } from 'asynciterator';\nimport { SparqlEndpointFetcher } from 'fetch-sparql-endpoint';\nimport { LRUCache } from 'lru-cache';\nimport { uniqTerms } from 'rdf-terms';\nimport type { BindMethod } from './ActorQuerySourceIdentifyHypermediaSparql';\n\nexport class QuerySourceSparql implements IQuerySource {\n /**\n * The query format that endpoints advertise via the `Accept-Query` header when they support HTTP QUERY (RFC 10008).\n */\n public static readonly MEDIATYPE_SPARQL_QUERY = 'application/sparql-query';\n\n public readonly referenceValue: string;\n private url: string;\n private readonly urlBackup: string;\n private readonly context: IActionContext;\n private readonly mediatorHttp: MediatorHttp;\n private readonly mediatorQuerySerialize: MediatorQuerySerialize;\n private readonly bindMethod: BindMethod;\n private readonly countTimeout: number;\n private readonly cardinalityCountQueries: boolean;\n private readonly cardinalityEstimateConstruction: boolean;\n private readonly defaultGraph?: string;\n private readonly unionDefaultGraph: boolean;\n private readonly propertyFeatures?: Set<string>;\n private readonly datasets?: IDataset[];\n public readonly extensionFunctions?: string[];\n private readonly dataFactory: ComunicaDataFactory;\n private readonly algebraFactory: AlgebraFactory;\n private readonly bindingsFactory: BindingsFactory;\n\n private readonly endpointFetcher: SparqlEndpointFetcher;\n private readonly cache: LRUCache<string, QueryResultCardinality> | undefined;\n\n private lastSourceContext: IActionContext | undefined;\n private httpQueryMethodRejected = false;\n\n public constructor(\n url: string,\n urlBackup: string,\n context: IActionContext,\n mediatorHttp: MediatorHttp,\n mediatorQuerySerialize: MediatorQuerySerialize,\n bindMethod: BindMethod,\n dataFactory: ComunicaDataFactory,\n algebraFactory: AlgebraFactory,\n bindingsFactory: BindingsFactory,\n forceHttpGet: boolean,\n cacheSize: number,\n countTimeout: number,\n cardinalityCountQueries: boolean,\n cardinalityEstimateConstruction: boolean,\n forceGetIfUrlLengthBelow: number,\n parseUnsupportedVersions: boolean,\n metadata: Record<string, any>,\n ) {\n this.referenceValue = urlBackup;\n this.url = url;\n this.urlBackup = urlBackup;\n this.context = context;\n this.mediatorHttp = mediatorHttp;\n this.mediatorQuerySerialize = mediatorQuerySerialize;\n this.bindMethod = bindMethod;\n this.dataFactory = dataFactory;\n this.algebraFactory = algebraFactory;\n this.bindingsFactory = bindingsFactory;\n\n // Endpoints advertise support for the HTTP QUERY method (RFC 10008) via the Accept-Query header,\n // which lets us send the query in the request body without the side effects of a POST.\n let method: 'GET' | 'POST' | 'QUERY' = 'POST';\n if (forceHttpGet) {\n method = 'GET';\n } else if (metadata.queryAccepted?.includes(QuerySourceSparql.MEDIATYPE_SPARQL_QUERY)) {\n method = 'QUERY';\n }\n\n this.endpointFetcher = new SparqlEndpointFetcher({\n method,\n fetch: async(input: Request | string, init?: RequestInit) => {\n // The advertisement may be stale, or an intermediary may not know the method,\n // in which case we permanently fall back to a direct POST, which carries an identical body.\n if (this.httpQueryMethodRejected && init?.method === 'QUERY') {\n init = { ...init, method: 'POST' };\n }\n\n let response = await this.mediatorHttp.mediate(\n { input, init, context: this.lastSourceContext! },\n );\n // If we encounter a 404, try our backup URL.\n // After retrying the request with the new URL, we replace the URL for future requests.\n if (response.status === 404 && this.url !== this.urlBackup) {\n Actor.getContextLogger(this.context)?.warn(`Encountered a 404 when requesting ${this.url} according to the service description of ${this.urlBackup}. This is a server configuration issue. Retrying the current and modifying future requests to ${this.urlBackup} instead.`);\n input = (<string> input).replace(this.url, this.urlBackup);\n this.url = this.urlBackup;\n response = await this.mediatorHttp.mediate(\n { input, init, context: this.lastSourceContext! },\n );\n }\n\n if (init?.method === 'QUERY' && (response.status === 405 || response.status === 501)) {\n Actor.getContextLogger(this.context)?.warn(`Encountered a ${response.status} for an HTTP QUERY request to ${this.url}, even though it advertises support for it via the Accept-Query header. Retrying the current and modifying future requests to use POST instead.`);\n this.httpQueryMethodRejected = true;\n response = await this.mediatorHttp.mediate(\n { input, init: { ...init, method: 'POST' }, context: this.lastSourceContext! },\n );\n }\n\n return response;\n },\n prefixVariableQuestionMark: true,\n dataFactory,\n forceGetIfUrlLengthBelow,\n directPost: metadata.postAccepted && !metadata.postAccepted.includes('application/x-www-form-urlencoded'),\n parseUnsupportedVersions,\n });\n this.cache = cacheSize > 0 ?\n new LRUCache<string, QueryResultCardinality>({ max: cacheSize }) :\n undefined;\n this.countTimeout = countTimeout;\n this.cardinalityCountQueries = cardinalityCountQueries;\n this.cardinalityEstimateConstruction = cardinalityEstimateConstruction;\n this.defaultGraph = metadata.defaultGraph;\n this.unionDefaultGraph = metadata.unionDefaultGraph ?? false;\n this.datasets = metadata.datasets;\n this.extensionFunctions = metadata.extensionFunctions;\n this.propertyFeatures = metadata.propertyFeatures ? new Set(metadata.propertyFeatures) : undefined;\n }\n\n public async getFilterFactor(): Promise<number> {\n return 1;\n }\n\n public async getSelectorShape(): Promise<FragmentSelectorShape> {\n const innerDisjunction: FragmentSelectorShape = {\n type: 'disjunction',\n children: [\n {\n type: 'operation',\n operation: { operationType: 'wildcard' },\n joinBindings: true,\n },\n ],\n };\n if (this.extensionFunctions) {\n innerDisjunction.children.push({\n type: 'operation',\n operation: {\n operationType: 'type',\n type: Algebra.Types.EXPRESSION,\n extensionFunctions: this.extensionFunctions,\n },\n joinBindings: true,\n });\n }\n return {\n type: 'conjunction',\n children: [\n innerDisjunction,\n {\n // DISTINCT CONSTRUCT is not allowed in SPARQL 1.1, so we explicitly disallowed it.\n type: 'negation',\n child: {\n type: 'operation',\n operation: { operationType: 'type', type: Algebra.Types.DISTINCT },\n children: [\n {\n type: 'operation',\n operation: { operationType: 'type', type: Algebra.Types.CONSTRUCT },\n children: [\n {\n type: 'operation',\n operation: { operationType: 'wildcard' },\n joinBindings: true,\n },\n ],\n },\n ],\n },\n },\n ],\n };\n }\n\n public queryBindings(\n operationIn: Algebra.Operation,\n context: IActionContext,\n options?: IQueryBindingsOptions,\n ): BindingsStream {\n // If bindings are passed, modify the operations\n let operationPromise: Promise<Algebra.Operation>;\n if (options?.joinBindings) {\n operationPromise = QuerySourceSparql.addBindingsToOperation(\n this.algebraFactory,\n this.bindMethod,\n operationIn,\n options.joinBindings,\n );\n } else {\n operationPromise = Promise.resolve(operationIn);\n }\n\n const bindings: BindingsStream = new TransformIterator(async() => {\n // Prepare queries\n const operation = await operationPromise;\n const variables: RDF.Variable[] = algebraUtils.inScopeVariables(operation);\n const queryString = context.get<string>(KeysInitQuery.queryString);\n const queryFormat: RDF.QueryFormat = context.getSafe(KeysInitQuery.queryFormat);\n const selectQuery: string = !options?.joinBindings && queryString && queryFormat.language === 'sparql' ?\n queryString :\n await this.operationToSelectQuery(this.algebraFactory, operation, variables);\n const undefVariables = QuerySourceSparql.getOperationUndefs(operation);\n\n return this.queryBindingsRemote(this.url, selectQuery, variables, context, undefVariables);\n }, { autoStart: false });\n this.attachMetadata(bindings, context, operationPromise);\n\n return bindings;\n }\n\n public queryQuads(operation: Algebra.Operation, context: IActionContext): AsyncIterator<RDF.Quad> {\n const quads = wrap<any>((async() => {\n this.lastSourceContext = this.context.merge(context);\n const query: string = context.get(KeysInitQuery.queryString) ?? await this.operationToQuery(operation);\n const rawStream = await this.endpointFetcher.fetchTriples(this.url, query);\n return rawStream;\n })(), { autoStart: false, maxBufferSize: Number.POSITIVE_INFINITY });\n this.attachMetadata(quads, context, Promise.resolve((<Algebra.Operation & { input: any }>operation).input));\n return quads;\n }\n\n public async queryBoolean(operation: Algebra.Ask, context: IActionContext): Promise<boolean> {\n // Shortcut the ASK query to return true when supported propertyFeature predicates are used in it.\n if (this.operationUsesPropertyFeatures(operation)) {\n return true;\n }\n // Without propertyFeature overlap, perform the actual ASK query.\n this.lastSourceContext = this.context.merge(context);\n const query: string = context.get(KeysInitQuery.queryString) ?? await this.operationToQuery(operation);\n const promise = this.endpointFetcher.fetchAsk(this.url, query);\n return promise;\n }\n\n public async queryVoid(operation: Algebra.Operation, context: IActionContext): Promise<void> {\n this.lastSourceContext = this.context.merge(context);\n const query: string = context.get(KeysInitQuery.queryString) ?? await this.operationToQuery(operation);\n const promise = this.endpointFetcher.fetchUpdate(this.url, query);\n return promise;\n }\n\n protected attachMetadata(\n target: AsyncIterator<any>,\n context: IActionContext,\n operationPromise: Promise<Algebra.Operation>,\n ): void {\n // Emit metadata containing the estimated count\n let variablesCount: MetadataVariable[] = [];\n // eslint-disable-next-line no-async-promise-executor,ts/no-misused-promises\n new Promise<QueryResultCardinality>(async(resolve, reject) => {\n try {\n const operation = await operationPromise;\n const variablesScoped = algebraUtils.inScopeVariables(operation);\n const countQuery = await this.operationToNormalizedCountQuery(operation);\n\n const undefVariables = QuerySourceSparql.getOperationUndefs(operation);\n variablesCount = variablesScoped.map(variable => ({\n variable,\n canBeUndef: undefVariables.some(undefVariable => undefVariable.equals(variable)),\n }));\n\n const cachedCardinality = this.cache?.get(countQuery);\n if (cachedCardinality) {\n return resolve(cachedCardinality);\n }\n\n // Attempt to estimate locally prior to sending a COUNT request, as this should be much faster.\n // The estimates may be off by varying amounts, so this is set behind a configuration flag.\n if (this.cardinalityEstimateConstruction) {\n const localEstimate = await this.estimateOperationCardinality(operation);\n if (Number.isFinite(localEstimate.value)) {\n this.cache?.set(countQuery, localEstimate);\n return resolve(localEstimate);\n }\n }\n\n // Don't send count queries if disabled.\n if (!this.cardinalityCountQueries) {\n return resolve({ type: 'estimate', value: Number.POSITIVE_INFINITY, dataset: this.url });\n }\n\n const timeoutHandler = setTimeout(() => resolve({\n type: 'estimate',\n value: Number.POSITIVE_INFINITY,\n dataset: this.url,\n }), this.countTimeout);\n const varCount = this.dataFactory.variable('count');\n const bindingsStream: BindingsStream = await this\n .queryBindingsRemote(this.url, countQuery, [ varCount ], context, []);\n bindingsStream\n .on('data', (bindings: Bindings) => {\n clearTimeout(timeoutHandler);\n const count = bindings.get(varCount);\n const cardinality: QueryResultCardinality = {\n type: 'estimate',\n value: Number.POSITIVE_INFINITY,\n dataset: this.url,\n };\n if (count) {\n const cardinalityValue: number = Number.parseInt(count.value, 10);\n if (!Number.isNaN(cardinalityValue)) {\n cardinality.type = 'exact';\n cardinality.value = cardinalityValue;\n this.cache?.set(countQuery, cardinality);\n }\n }\n return resolve(cardinality);\n })\n .on('error', () => {\n clearTimeout(timeoutHandler);\n resolve({ type: 'estimate', value: Number.POSITIVE_INFINITY, dataset: this.url });\n })\n .on('end', () => {\n clearTimeout(timeoutHandler);\n resolve({ type: 'estimate', value: Number.POSITIVE_INFINITY, dataset: this.url });\n });\n } catch (error: unknown) {\n reject(error);\n }\n })\n .then(cardinality => target.setProperty('metadata', {\n state: new MetadataValidationState(),\n cardinality,\n variables: variablesCount,\n }))\n .catch(() => target.setProperty('metadata', {\n state: new MetadataValidationState(),\n cardinality: { type: 'estimate', value: Number.POSITIVE_INFINITY, dataset: this.url },\n variables: variablesCount,\n }));\n }\n\n /**\n * Convert an algebra operation into a query string, and if the operation is a simple triple pattern,\n * then also replace any variables with s, p, and o to increase the chance of cache hits.\n * @param {Algebra.Operation} operation The operation to convert into a query string.\n * @returns {string} Query string for a COUNT query over the operation.\n */\n public async operationToNormalizedCountQuery(operation: Algebra.Operation): Promise<string> {\n const normalizedOperation = isKnownOperation(operation, Algebra.Types.PATTERN) ?\n this.algebraFactory.createPattern(\n operation.subject.termType === 'Variable' ? this.dataFactory.variable('s') : operation.subject,\n operation.predicate.termType === 'Variable' ? this.dataFactory.variable('p') : operation.predicate,\n operation.object.termType === 'Variable' ? this.dataFactory.variable('o') : operation.object,\n ) :\n operation;\n return await this.operationToCountQuery(\n this.dataFactory,\n this.algebraFactory,\n normalizedOperation,\n );\n }\n\n /**\n * Performs local cardinality estimation for the specified SPARQL algebra operation, which should\n * result in better estimation performance at the expense of accuracy.\n * @param {Algebra.Operation} operation A query operation.\n */\n public async estimateOperationCardinality(operation: Algebra.Operation): Promise<QueryResultCardinality> {\n if (this.operationUsesPropertyFeatures(operation)) {\n return { type: 'estimate', value: 1, dataset: this.url };\n }\n\n const dataset: IDataset = {\n getCardinality: async(operation: Algebra.Operation): Promise<QueryResultCardinality | undefined> => {\n const queryString = await this.operationToNormalizedCountQuery(operation);\n\n const cachedCardinality = this.cache?.get(queryString);\n if (cachedCardinality) {\n return cachedCardinality;\n }\n\n if (this.datasets) {\n const cardinalities = await Promise.all(this.datasets\n .filter(ds => this.unionDefaultGraph || (this.defaultGraph && ds.uri.endsWith(this.defaultGraph)))\n .map(ds => estimateCardinality(operation, ds)));\n\n const cardinality: QueryResultCardinality = {\n type: cardinalities.some(card => card.type === 'estimate') ? 'estimate' : 'exact',\n value: cardinalities.length > 0 ? cardinalities.reduce((acc, card) => acc + card.value, 0) : 0,\n dataset: this.url,\n };\n\n return cardinality;\n }\n },\n source: this.url,\n uri: this.url,\n };\n\n return estimateCardinality(operation, dataset);\n }\n\n /**\n * Checks whether the provided operation makes use of this endpoint's property features,\n * if the endpoint has property features detected.\n * @param {Algebra.Operation} operation The operation to check.\n * @returns {boolean} Whether the operation makes use of property features.\n */\n public operationUsesPropertyFeatures(operation: Algebra.Operation): boolean {\n let propertyFeaturesUsed = false;\n if (this.propertyFeatures) {\n algebraUtils.visitOperation(operation, {\n [Algebra.Types.PATTERN]: {\n visitor: (subOp) => {\n if (subOp.predicate.termType === 'NamedNode' && this.propertyFeatures!.has(subOp.predicate.value)) {\n propertyFeaturesUsed = true;\n }\n return false;\n },\n },\n [Algebra.Types.LINK]: {\n visitor: (subOp) => {\n if (this.propertyFeatures!.has(subOp.iri.value)) {\n propertyFeaturesUsed = true;\n }\n return false;\n },\n },\n [Algebra.Types.NPS]: {\n visitor: (subOp) => {\n if (subOp.iris.some(iri => this.propertyFeatures!.has(iri.value))) {\n propertyFeaturesUsed = true;\n }\n return false;\n },\n },\n });\n }\n return propertyFeaturesUsed;\n }\n\n /**\n * Create an operation that includes the bindings from the given bindings stream.\n * @param algebraFactory The algebra factory.\n * @param bindMethod A method for adding bindings to an operation.\n * @param operation The operation to bind to.\n * @param addBindings The bindings to add.\n * @param addBindings.bindings The bindings stream.\n * @param addBindings.metadata The bindings metadata.\n */\n public static async addBindingsToOperation(\n algebraFactory: AlgebraFactory,\n bindMethod: BindMethod,\n operation: Algebra.Operation,\n addBindings: { bindings: BindingsStream; metadata: MetadataBindings },\n ): Promise<Algebra.Operation> {\n const bindings = await addBindings.bindings.toArray();\n\n switch (bindMethod) {\n case 'values':\n return algebraFactory.createJoin([\n algebraFactory.createValues(\n addBindings.metadata.variables.map(v => v.variable),\n bindings.map(binding => Object.fromEntries([ ...binding ]\n .map(([ key, value ]) => [ key.value, <RDF.Literal | RDF.NamedNode> value ]))),\n ),\n operation,\n ], false);\n case 'union': { throw new Error('Not implemented yet: \"union\" case'); }\n case 'filter': { throw new Error('Not implemented yet: \"filter\" case'); }\n }\n }\n\n /**\n * Convert an operation to a select query for this pattern.\n * @param algebraFactory The algebra factory.\n * @param {Algebra.Operation} operation A query operation.\n * @param {RDF.Variable[]} variables The variables in scope for the operation.\n * @return {string} A select query string.\n */\n public operationToSelectQuery(\n algebraFactory: AlgebraFactory,\n operation: Algebra.Operation,\n variables: RDF.Variable[],\n ): Promise<string> {\n return this.operationToQuery(algebraFactory.createProject(operation, variables));\n }\n\n /**\n * Convert an operation to a count query for the number of matching triples for this pattern.\n * @param dataFactory The data factory.\n * @param algebraFactory The algebra factory.\n * @param {Algebra.Operation} operation A query operation.\n * @return {string} A count query string.\n */\n public operationToCountQuery(\n dataFactory: ComunicaDataFactory,\n algebraFactory: AlgebraFactory,\n operation: Algebra.Operation,\n ): Promise<string> {\n return this.operationToQuery(algebraFactory.createProject(\n algebraFactory.createExtend(\n algebraFactory.createGroup(\n operation,\n [],\n [ algebraFactory.createBoundAggregate(\n dataFactory.variable('var0'),\n 'count',\n algebraFactory.createWildcardExpression(),\n false,\n ) ],\n ),\n dataFactory.variable('count'),\n algebraFactory.createTermExpression(dataFactory.variable('var0')),\n ),\n [ dataFactory.variable('count') ],\n ));\n }\n\n /**\n * Convert an operation to a query for this pattern.\n * @param {Algebra.Operation} operation A query operation.\n * @return {string} A query string.\n */\n public async operationToQuery(operation: Algebra.Operation): Promise<string> {\n return (await this.mediatorQuerySerialize.mediate({\n queryFormat: { language: 'sparql', version: '1.2' },\n operation,\n newlines: false,\n indentWidth: 0,\n context: this.context,\n })).query;\n }\n\n /**\n * Check if the given operation may produce undefined values.\n * @param operation\n */\n public static getOperationUndefs(operation: Algebra.Operation): RDF.Variable[] {\n const variables: RDF.Variable[] = [];\n algebraUtils.visitOperation(operation, {\n [Algebra.Types.LEFT_JOIN]: { preVisitor: (subOperation) => {\n const left = algebraUtils.inScopeVariables(subOperation.input[0]);\n const right = algebraUtils.inScopeVariables(subOperation.input[1]);\n for (const varRight of right) {\n if (!left.some(varLeft => varLeft.equals(varRight))) {\n variables.push(varRight);\n }\n }\n return { continue: false };\n } },\n [Algebra.Types.VALUES]: { preVisitor: (values) => {\n for (const variable of values.variables) {\n if (values.bindings.some(bindings => !(variable.value in bindings))) {\n variables.push(variable);\n }\n }\n return { continue: false };\n } },\n [Algebra.Types.UNION]: { preVisitor: (union) => {\n // Determine variables in scope of the union branches that are not occurring in every branch\n const scopedVariables = union.input.map(op => algebraUtils.inScopeVariables(op));\n for (const variable of uniqTerms(scopedVariables.flat())) {\n if (!scopedVariables.every(input => input.some(inputVar => inputVar.equals(variable)))) {\n variables.push(variable);\n }\n }\n return {};\n } },\n });\n return uniqTerms(variables);\n }\n\n /**\n * Send a SPARQL query to a SPARQL endpoint and retrieve its bindings as a stream.\n * @param {string} endpoint A SPARQL endpoint URL.\n * @param {string} query A SPARQL query string.\n * @param {RDF.Variable[]} variables The expected variables.\n * @param {IActionContext} context The source context.\n * @param undefVariables Variables that may have undefs.\n * @return {BindingsStream} A stream of bindings.\n */\n public async queryBindingsRemote(\n endpoint: string,\n query: string,\n variables: RDF.Variable[],\n context: IActionContext,\n undefVariables: RDF.Variable[],\n ): Promise<BindingsStream> {\n // Index undef variables\n const undefVariablesSet = new Set(undefVariables.map(v => v.value));\n\n this.lastSourceContext = this.context.merge(context);\n const rawStream = await this.endpointFetcher.fetchBindings(endpoint, query);\n\n const wrapped = wrap<any>(rawStream, { autoStart: false, maxBufferSize: Number.POSITIVE_INFINITY });\n return wrapped.map<RDF.Bindings>((rawData: Record<string, RDF.Term>) => {\n const bindings = variables.map((variable) => {\n const value = rawData[`?${variable.value}`];\n if (!undefVariablesSet.has(variable.value) && !value) {\n Actor.getContextLogger(this.context)?.warn(`The endpoint ${endpoint} failed to provide a binding for ${variable.value}.`);\n }\n return <[RDF.Variable, RDF.Term]>[ variable, value ];\n }).filter(([ _, v ]) => Boolean(v));\n return this.bindingsFactory.bindings(bindings);\n });\n }\n\n public toString(): string {\n return `QuerySourceSparql(${this.url})`;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"QuerySourceSparql.js","sourceRoot":"","sources":["QuerySourceSparql.ts"],"names":[],"mappings":";;;AAEA,+DAAoE;AACpE,yCAAuC;AAgBvC,2DAAkF;AAElF,6DAAmE;AACnE,2EAIyC;AAGzC,iDAAwD;AAExD,iEAA8D;AAC9D,yCAAqC;AACrC,yCAAsC;AAGtC,MAAa,iBAAiB;IAC5B;;OAEG;IACI,MAAM,CAAU,sBAAsB,GAAG,0BAA0B,CAAC;IAE3D,cAAc,CAAS;IAC/B,GAAG,CAAS;IACH,SAAS,CAAS;IAClB,OAAO,CAAiB;IACxB,YAAY,CAAe;IAC3B,sBAAsB,CAAyB;IAC/C,UAAU,CAAa;IACvB,YAAY,CAAS;IACrB,uBAAuB,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C,CAAC;;AA3pBH,8CA4pBC","sourcesContent":["import type { MediatorHttp } from '@comunica/bus-http';\nimport type { MediatorQuerySerialize } from '@comunica/bus-query-serialize';\nimport { KeysHttp, KeysInitQuery } from '@comunica/context-entries';\nimport { Actor } from '@comunica/core';\nimport type {\n Bindings,\n BindingsStream,\n ComunicaDataFactory,\n FragmentSelectorShape,\n IActionContext,\n IDataset,\n IPhysicalQueryPlanNode,\n IQueryBindingsOptions,\n IQuerySource,\n MetadataBindings,\n MetadataVariable,\n QueryResultCardinality,\n} from '@comunica/types';\nimport type { AlgebraFactory } from '@comunica/utils-algebra';\nimport { Algebra, algebraUtils, isKnownOperation } from '@comunica/utils-algebra';\nimport type { BindingsFactory } from '@comunica/utils-bindings-factory';\nimport { MetadataValidationState } from '@comunica/utils-metadata';\nimport {\n estimateCardinality,\n getOperationEquivalentQueryString,\n getOriginalSparqlQueryString,\n} from '@comunica/utils-query-operation';\nimport type * as RDF from '@rdfjs/types';\nimport type { AsyncIterator } from 'asynciterator';\nimport { TransformIterator, wrap } from 'asynciterator';\nimport type { ISparqlEndpointFetcherRequestOptions } from 'fetch-sparql-endpoint';\nimport { SparqlEndpointFetcher } from 'fetch-sparql-endpoint';\nimport { LRUCache } from 'lru-cache';\nimport { uniqTerms } from 'rdf-terms';\nimport type { BindMethod } from './ActorQuerySourceIdentifyHypermediaSparql';\n\nexport class QuerySourceSparql implements IQuerySource {\n /**\n * The query format that endpoints advertise via the `Accept-Query` header when they support HTTP QUERY (RFC 10008).\n */\n public static readonly MEDIATYPE_SPARQL_QUERY = 'application/sparql-query';\n\n public readonly referenceValue: string;\n private url: string;\n private readonly urlBackup: string;\n private readonly context: IActionContext;\n private readonly mediatorHttp: MediatorHttp;\n private readonly mediatorQuerySerialize: MediatorQuerySerialize;\n private readonly bindMethod: BindMethod;\n private readonly countTimeout: number;\n private readonly cardinalityCountQueries: boolean;\n private readonly cardinalityEstimateConstruction: boolean;\n private readonly defaultGraph?: string;\n private readonly unionDefaultGraph: boolean;\n private readonly propertyFeatures?: Set<string>;\n private readonly datasets?: IDataset[];\n public readonly extensionFunctions?: string[];\n private readonly dataFactory: ComunicaDataFactory;\n private readonly algebraFactory: AlgebraFactory;\n private readonly bindingsFactory: BindingsFactory;\n\n private readonly endpointFetcher: SparqlEndpointFetcher;\n private readonly cache: LRUCache<string, QueryResultCardinality> | undefined;\n\n /**\n * The number of HTTP requests made for each physical query plan node.\n */\n private readonly httpRequestsByPlanNode = new WeakMap<IPhysicalQueryPlanNode, number>();\n private httpQueryMethodRejected = false;\n\n public constructor(\n url: string,\n urlBackup: string,\n context: IActionContext,\n mediatorHttp: MediatorHttp,\n mediatorQuerySerialize: MediatorQuerySerialize,\n bindMethod: BindMethod,\n dataFactory: ComunicaDataFactory,\n algebraFactory: AlgebraFactory,\n bindingsFactory: BindingsFactory,\n forceHttpGet: boolean,\n cacheSize: number,\n countTimeout: number,\n cardinalityCountQueries: boolean,\n cardinalityEstimateConstruction: boolean,\n forceGetIfUrlLengthBelow: number,\n parseUnsupportedVersions: boolean,\n metadata: Record<string, any>,\n ) {\n this.referenceValue = urlBackup;\n this.url = url;\n this.urlBackup = urlBackup;\n this.context = context;\n this.mediatorHttp = mediatorHttp;\n this.mediatorQuerySerialize = mediatorQuerySerialize;\n this.bindMethod = bindMethod;\n this.dataFactory = dataFactory;\n this.algebraFactory = algebraFactory;\n this.bindingsFactory = bindingsFactory;\n\n // Endpoints advertise support for the HTTP QUERY method (RFC 10008) via the Accept-Query header,\n // which lets us send the query in the request body without the side effects of a POST.\n let method: 'GET' | 'POST' | 'QUERY' = 'POST';\n if (forceHttpGet) {\n method = 'GET';\n } else if (metadata.queryAccepted?.includes(QuerySourceSparql.MEDIATYPE_SPARQL_QUERY)) {\n method = 'QUERY';\n }\n\n this.endpointFetcher = new SparqlEndpointFetcher({\n method,\n prefixVariableQuestionMark: true,\n dataFactory,\n forceGetIfUrlLengthBelow,\n directPost: metadata.postAccepted && !metadata.postAccepted.includes('application/x-www-form-urlencoded'),\n parseUnsupportedVersions,\n });\n this.cache = cacheSize > 0 ?\n new LRUCache<string, QueryResultCardinality>({ max: cacheSize }) :\n undefined;\n this.countTimeout = countTimeout;\n this.cardinalityCountQueries = cardinalityCountQueries;\n this.cardinalityEstimateConstruction = cardinalityEstimateConstruction;\n this.defaultGraph = metadata.defaultGraph;\n this.unionDefaultGraph = metadata.unionDefaultGraph ?? false;\n this.datasets = metadata.datasets;\n this.extensionFunctions = metadata.extensionFunctions;\n this.propertyFeatures = metadata.propertyFeatures ? new Set(metadata.propertyFeatures) : undefined;\n }\n\n /**\n * Create the options for requests to the endpoint on behalf of the given context,\n * so that each request is sent with the context of the query that issued it.\n * @param context The context of the query operation for which requests are sent.\n */\n protected getRequestOptions(context: IActionContext): ISparqlEndpointFetcherRequestOptions {\n return { fetch: (input: Request | string, init?: RequestInit) => this.fetch(input, init, context) };\n }\n\n /**\n * Send an HTTP request to the endpoint.\n * @param input The request input.\n * @param init The request options.\n * @param context The context of the query operation for which the request is sent.\n */\n protected async fetch(input: Request | string, init: RequestInit | undefined, context: IActionContext):\n Promise<Response> {\n // The advertisement may be stale, or an intermediary may not know the method,\n // in which case we permanently fall back to a direct POST, which carries an identical body.\n if (this.httpQueryMethodRejected && init?.method === 'QUERY') {\n init = { ...init, method: 'POST' };\n }\n\n this.countHttpRequest(context);\n let response = await this.mediatorHttp.mediate({ input, init, context });\n // If we encounter a 404, try our backup URL.\n // After retrying the request with the new URL, we replace the URL for future requests.\n if (response.status === 404 && this.url !== this.urlBackup) {\n Actor.getContextLogger(this.context)?.warn(`Encountered a 404 when requesting ${this.url} according to the service description of ${this.urlBackup}. This is a server configuration issue. Retrying the current and modifying future requests to ${this.urlBackup} instead.`);\n input = (<string> input).replace(this.url, this.urlBackup);\n this.url = this.urlBackup;\n this.countHttpRequest(context);\n response = await this.mediatorHttp.mediate({ input, init, context });\n }\n\n if (init?.method === 'QUERY' && (response.status === 405 || response.status === 501)) {\n Actor.getContextLogger(this.context)?.warn(`Encountered a ${response.status} for an HTTP QUERY request to ${this.url}, even though it advertises support for it via the Accept-Query header. Retrying the current and modifying future requests to use POST instead.`);\n this.httpQueryMethodRejected = true;\n this.countHttpRequest(context);\n response = await this.mediatorHttp.mediate({ input, init: { ...init, method: 'POST' }, context });\n }\n\n return response;\n }\n\n public async getFilterFactor(): Promise<number> {\n return 1;\n }\n\n public async getSelectorShape(): Promise<FragmentSelectorShape> {\n const innerDisjunction: FragmentSelectorShape = {\n type: 'disjunction',\n children: [\n {\n type: 'operation',\n operation: { operationType: 'wildcard' },\n joinBindings: true,\n },\n ],\n };\n if (this.extensionFunctions) {\n innerDisjunction.children.push({\n type: 'operation',\n operation: {\n operationType: 'type',\n type: Algebra.Types.EXPRESSION,\n extensionFunctions: this.extensionFunctions,\n },\n joinBindings: true,\n });\n }\n return {\n type: 'conjunction',\n children: [\n innerDisjunction,\n {\n // DISTINCT CONSTRUCT is not allowed in SPARQL 1.1, so we explicitly disallowed it.\n type: 'negation',\n child: {\n type: 'operation',\n operation: { operationType: 'type', type: Algebra.Types.DISTINCT },\n children: [\n {\n type: 'operation',\n operation: { operationType: 'type', type: Algebra.Types.CONSTRUCT },\n children: [\n {\n type: 'operation',\n operation: { operationType: 'wildcard' },\n joinBindings: true,\n },\n ],\n },\n ],\n },\n },\n ],\n };\n }\n\n /**\n * Report the query that is sent to the endpoint to the physical query plan, if one is being logged.\n * @param context The context of the current operation.\n * @param query The query that is sent to the endpoint.\n */\n protected reportSourceQuery(context: IActionContext, query: string): void {\n context.get(KeysInitQuery.physicalQueryPlanNode)?.appendMetadata({ sourceQuery: query });\n }\n\n /**\n * Count an HTTP request against the physical query plan node of the operation it is made on behalf of.\n * @param context The context of the operation for which the request is sent.\n */\n protected countHttpRequest(context: IActionContext): void {\n const planNode = context.get(KeysInitQuery.physicalQueryPlanNode);\n if (planNode) {\n const httpRequests = (this.httpRequestsByPlanNode.get(planNode) ?? 0) + 1;\n this.httpRequestsByPlanNode.set(planNode, httpRequests);\n planNode.appendMetadata({ httpRequests });\n }\n }\n\n public queryBindings(\n operationIn: Algebra.Operation,\n context: IActionContext,\n options?: IQueryBindingsOptions,\n ): BindingsStream {\n // If bindings are passed, modify the operations\n let operationPromise: Promise<Algebra.Operation>;\n if (options?.joinBindings) {\n operationPromise = QuerySourceSparql.addBindingsToOperation(\n this.algebraFactory,\n this.bindMethod,\n operationIn,\n options.joinBindings,\n );\n } else {\n operationPromise = Promise.resolve(operationIn);\n }\n\n const bindings: BindingsStream = new TransformIterator(async() => {\n // Prepare queries\n const operation = await operationPromise;\n const variables: RDF.Variable[] = algebraUtils.inScopeVariables(operation);\n // Join bindings modify the operation, so it is no longer equivalent to the original query string.\n const queryString = options?.joinBindings ? undefined : QuerySourceSparql.getQueryStringAsIs(operation, context);\n const selectQuery: string = queryString ??\n await this.operationToSelectQuery(this.algebraFactory, operation, variables);\n const undefVariables = QuerySourceSparql.getOperationUndefs(operation);\n\n this.reportSourceQuery(context, selectQuery);\n return this.queryBindingsRemote(this.url, selectQuery, variables, context, undefVariables);\n }, { autoStart: false });\n this.attachMetadata(bindings, context, operationPromise);\n\n return bindings;\n }\n\n public queryQuads(operation: Algebra.Operation, context: IActionContext): AsyncIterator<RDF.Quad> {\n const quads = wrap<any>((async() => {\n const query: string = QuerySourceSparql.getQueryStringAsIs(operation, context) ??\n await this.operationToQuery(operation);\n this.reportSourceQuery(context, query);\n const rawStream = await this.endpointFetcher.fetchTriples(this.url, query, this.getRequestOptions(context));\n return rawStream;\n })(), { autoStart: false, maxBufferSize: Number.POSITIVE_INFINITY });\n this.attachMetadata(quads, context, Promise.resolve((<Algebra.Operation & { input: any }>operation).input));\n return quads;\n }\n\n public async queryBoolean(operation: Algebra.Ask, context: IActionContext): Promise<boolean> {\n // Shortcut the ASK query to return true when supported propertyFeature predicates are used in it.\n if (this.operationUsesPropertyFeatures(operation)) {\n return true;\n }\n // Without propertyFeature overlap, perform the actual ASK query.\n const query: string = QuerySourceSparql.getQueryStringAsIs(operation, context) ??\n await this.operationToQuery(operation);\n this.reportSourceQuery(context, query);\n const promise = this.endpointFetcher.fetchAsk(this.url, query, this.getRequestOptions(context));\n return promise;\n }\n\n public async queryVoid(operation: Algebra.Operation, context: IActionContext): Promise<void> {\n const query: string = QuerySourceSparql.getQueryStringAsIs(operation, context) ??\n await this.operationToQuery(operation);\n this.reportSourceQuery(context, query);\n const promise = this.endpointFetcher.fetchUpdate(this.url, query, this.getRequestOptions(context));\n return promise;\n }\n\n protected attachMetadata(\n target: AsyncIterator<any>,\n context: IActionContext,\n operationPromise: Promise<Algebra.Operation>,\n ): void {\n // Emit metadata containing the estimated count\n let variablesCount: MetadataVariable[] = [];\n // eslint-disable-next-line no-async-promise-executor,ts/no-misused-promises\n new Promise<QueryResultCardinality>(async(resolve, reject) => {\n try {\n const operation = await operationPromise;\n const variablesScoped = algebraUtils.inScopeVariables(operation);\n const countQuery = await this.operationToNormalizedCountQuery(operation);\n\n const undefVariables = QuerySourceSparql.getOperationUndefs(operation);\n variablesCount = variablesScoped.map(variable => ({\n variable,\n canBeUndef: undefVariables.some(undefVariable => undefVariable.equals(variable)),\n }));\n\n const cachedCardinality = this.cache?.get(countQuery);\n if (cachedCardinality) {\n return resolve(cachedCardinality);\n }\n\n // Attempt to estimate locally prior to sending a COUNT request, as this should be much faster.\n // The estimates may be off by varying amounts, so this is set behind a configuration flag.\n if (this.cardinalityEstimateConstruction) {\n const localEstimate = await this.estimateOperationCardinality(operation);\n if (Number.isFinite(localEstimate.value)) {\n this.cache?.set(countQuery, localEstimate);\n return resolve(localEstimate);\n }\n }\n\n // Don't send count queries if disabled.\n if (!this.cardinalityCountQueries) {\n return resolve({ type: 'estimate', value: Number.POSITIVE_INFINITY, dataset: this.url });\n }\n\n // Abort the count request on timeout, so that it does not keep occupying the endpoint.\n const abortController = new AbortController();\n const existingAbortSignal = context.get(KeysHttp.httpAbortSignal);\n const countContext = context.set(\n KeysHttp.httpAbortSignal,\n existingAbortSignal ?\n AbortSignal.any([ existingAbortSignal, abortController.signal ]) :\n abortController.signal,\n );\n const timeoutHandler = setTimeout(() => {\n resolve({\n type: 'estimate',\n value: Number.POSITIVE_INFINITY,\n dataset: this.url,\n });\n abortController.abort();\n }, this.countTimeout);\n const varCount = this.dataFactory.variable('count');\n const bindingsStream: BindingsStream = await this\n .queryBindingsRemote(this.url, countQuery, [ varCount ], countContext, []);\n bindingsStream\n .on('data', (bindings: Bindings) => {\n clearTimeout(timeoutHandler);\n const count = bindings.get(varCount);\n const cardinality: QueryResultCardinality = {\n type: 'estimate',\n value: Number.POSITIVE_INFINITY,\n dataset: this.url,\n };\n if (count) {\n const cardinalityValue: number = Number.parseInt(count.value, 10);\n if (!Number.isNaN(cardinalityValue)) {\n cardinality.type = 'exact';\n cardinality.value = cardinalityValue;\n this.cache?.set(countQuery, cardinality);\n }\n }\n return resolve(cardinality);\n })\n .on('error', () => {\n clearTimeout(timeoutHandler);\n resolve({ type: 'estimate', value: Number.POSITIVE_INFINITY, dataset: this.url });\n })\n .on('end', () => {\n clearTimeout(timeoutHandler);\n resolve({ type: 'estimate', value: Number.POSITIVE_INFINITY, dataset: this.url });\n });\n } catch (error: unknown) {\n reject(error);\n }\n })\n .then(cardinality => target.setProperty('metadata', {\n state: new MetadataValidationState(),\n cardinality,\n variables: variablesCount,\n }))\n .catch(() => target.setProperty('metadata', {\n state: new MetadataValidationState(),\n cardinality: { type: 'estimate', value: Number.POSITIVE_INFINITY, dataset: this.url },\n variables: variablesCount,\n }));\n }\n\n /**\n * Convert an algebra operation into a query string, and if the operation is a simple triple pattern,\n * then also replace any variables with s, p, and o to increase the chance of cache hits.\n * @param {Algebra.Operation} operation The operation to convert into a query string.\n * @returns {string} Query string for a COUNT query over the operation.\n */\n public async operationToNormalizedCountQuery(operation: Algebra.Operation): Promise<string> {\n const normalizedOperation = isKnownOperation(operation, Algebra.Types.PATTERN) ?\n this.algebraFactory.createPattern(\n operation.subject.termType === 'Variable' ? this.dataFactory.variable('s') : operation.subject,\n operation.predicate.termType === 'Variable' ? this.dataFactory.variable('p') : operation.predicate,\n operation.object.termType === 'Variable' ? this.dataFactory.variable('o') : operation.object,\n ) :\n operation;\n return await this.operationToCountQuery(\n this.dataFactory,\n this.algebraFactory,\n normalizedOperation,\n );\n }\n\n /**\n * Performs local cardinality estimation for the specified SPARQL algebra operation, which should\n * result in better estimation performance at the expense of accuracy.\n * @param {Algebra.Operation} operation A query operation.\n */\n public async estimateOperationCardinality(operation: Algebra.Operation): Promise<QueryResultCardinality> {\n if (this.operationUsesPropertyFeatures(operation)) {\n return { type: 'estimate', value: 1, dataset: this.url };\n }\n\n const dataset: IDataset = {\n getCardinality: async(operation: Algebra.Operation): Promise<QueryResultCardinality | undefined> => {\n const queryString = await this.operationToNormalizedCountQuery(operation);\n\n const cachedCardinality = this.cache?.get(queryString);\n if (cachedCardinality) {\n return cachedCardinality;\n }\n\n if (this.datasets) {\n const cardinalities = await Promise.all(this.datasets\n .filter(ds => this.unionDefaultGraph || (this.defaultGraph && ds.uri.endsWith(this.defaultGraph)))\n .map(ds => estimateCardinality(operation, ds)));\n\n const cardinality: QueryResultCardinality = {\n type: cardinalities.some(card => card.type === 'estimate') ? 'estimate' : 'exact',\n value: cardinalities.length > 0 ? cardinalities.reduce((acc, card) => acc + card.value, 0) : 0,\n dataset: this.url,\n };\n\n return cardinality;\n }\n },\n source: this.url,\n uri: this.url,\n };\n\n return estimateCardinality(operation, dataset);\n }\n\n /**\n * Checks whether the provided operation makes use of this endpoint's property features,\n * if the endpoint has property features detected.\n * @param {Algebra.Operation} operation The operation to check.\n * @returns {boolean} Whether the operation makes use of property features.\n */\n public operationUsesPropertyFeatures(operation: Algebra.Operation): boolean {\n let propertyFeaturesUsed = false;\n if (this.propertyFeatures) {\n algebraUtils.visitOperation(operation, {\n [Algebra.Types.PATTERN]: {\n visitor: (subOp) => {\n if (subOp.predicate.termType === 'NamedNode' && this.propertyFeatures!.has(subOp.predicate.value)) {\n propertyFeaturesUsed = true;\n }\n return false;\n },\n },\n [Algebra.Types.LINK]: {\n visitor: (subOp) => {\n if (this.propertyFeatures!.has(subOp.iri.value)) {\n propertyFeaturesUsed = true;\n }\n return false;\n },\n },\n [Algebra.Types.NPS]: {\n visitor: (subOp) => {\n if (subOp.iris.some(iri => this.propertyFeatures!.has(iri.value))) {\n propertyFeaturesUsed = true;\n }\n return false;\n },\n },\n });\n }\n return propertyFeaturesUsed;\n }\n\n /**\n * Create an operation that includes the bindings from the given bindings stream.\n * @param algebraFactory The algebra factory.\n * @param bindMethod A method for adding bindings to an operation.\n * @param operation The operation to bind to.\n * @param addBindings The bindings to add.\n * @param addBindings.bindings The bindings stream.\n * @param addBindings.metadata The bindings metadata.\n */\n public static async addBindingsToOperation(\n algebraFactory: AlgebraFactory,\n bindMethod: BindMethod,\n operation: Algebra.Operation,\n addBindings: { bindings: BindingsStream; metadata: MetadataBindings },\n ): Promise<Algebra.Operation> {\n const bindings = await addBindings.bindings.toArray();\n\n switch (bindMethod) {\n case 'values':\n return algebraFactory.createJoin([\n algebraFactory.createValues(\n addBindings.metadata.variables.map(v => v.variable),\n bindings.map(binding => Object.fromEntries([ ...binding ]\n .map(([ key, value ]) => [ key.value, <RDF.Literal | RDF.NamedNode> value ]))),\n ),\n operation,\n ], false);\n case 'union': { throw new Error('Not implemented yet: \"union\" case'); }\n case 'filter': { throw new Error('Not implemented yet: \"filter\" case'); }\n }\n }\n\n /**\n * Convert an operation to a select query for this pattern.\n * @param algebraFactory The algebra factory.\n * @param {Algebra.Operation} operation A query operation.\n * @param {RDF.Variable[]} variables The variables in scope for the operation.\n * @return {string} A select query string.\n */\n public operationToSelectQuery(\n algebraFactory: AlgebraFactory,\n operation: Algebra.Operation,\n variables: RDF.Variable[],\n ): Promise<string> {\n return this.operationToQuery(algebraFactory.createProject(operation, variables));\n }\n\n /**\n * Convert an operation to a count query for the number of matching triples for this pattern.\n * @param dataFactory The data factory.\n * @param algebraFactory The algebra factory.\n * @param {Algebra.Operation} operation A query operation.\n * @return {string} A count query string.\n */\n public operationToCountQuery(\n dataFactory: ComunicaDataFactory,\n algebraFactory: AlgebraFactory,\n operation: Algebra.Operation,\n ): Promise<string> {\n return this.operationToQuery(algebraFactory.createProject(\n algebraFactory.createExtend(\n algebraFactory.createGroup(\n operation,\n [],\n [ algebraFactory.createBoundAggregate(\n dataFactory.variable('var0'),\n 'count',\n algebraFactory.createWildcardExpression(),\n false,\n ) ],\n ),\n dataFactory.variable('count'),\n algebraFactory.createTermExpression(dataFactory.variable('var0')),\n ),\n [ dataFactory.variable('count') ],\n ));\n }\n\n /**\n * Convert an operation to a query for this pattern.\n * @param {Algebra.Operation} operation A query operation.\n * @return {string} A query string.\n */\n public async operationToQuery(operation: Algebra.Operation): Promise<string> {\n return (await this.mediatorQuerySerialize.mediate({\n queryFormat: { language: 'sparql', version: '1.2' },\n operation,\n newlines: false,\n indentWidth: 0,\n context: this.context,\n })).query;\n }\n\n /**\n * Obtain the SPARQL query string that may be sent as-is for the given operation.\n * @param operation A query operation.\n * @param context The action context.\n * @return The query string to send as-is, or undefined if the operation must be serialized.\n */\n public static getQueryStringAsIs(operation: Algebra.Operation, context: IActionContext): string | undefined {\n // TODO: next/major - remove the fallback to the original query string, see KeysInitQuery.queryString.\n return getOperationEquivalentQueryString(operation) ?? getOriginalSparqlQueryString(context);\n }\n\n /**\n * Check if the given operation may produce undefined values.\n * @param operation\n */\n public static getOperationUndefs(operation: Algebra.Operation): RDF.Variable[] {\n const variables: RDF.Variable[] = [];\n algebraUtils.visitOperation(operation, {\n [Algebra.Types.LEFT_JOIN]: { preVisitor: (subOperation) => {\n const left = algebraUtils.inScopeVariables(subOperation.input[0]);\n const right = algebraUtils.inScopeVariables(subOperation.input[1]);\n for (const varRight of right) {\n if (!left.some(varLeft => varLeft.equals(varRight))) {\n variables.push(varRight);\n }\n }\n return { continue: false };\n } },\n [Algebra.Types.VALUES]: { preVisitor: (values) => {\n for (const variable of values.variables) {\n if (values.bindings.some(bindings => !(variable.value in bindings))) {\n variables.push(variable);\n }\n }\n return { continue: false };\n } },\n [Algebra.Types.UNION]: { preVisitor: (union) => {\n // Determine variables in scope of the union branches that are not occurring in every branch\n const scopedVariables = union.input.map(op => algebraUtils.inScopeVariables(op));\n for (const variable of uniqTerms(scopedVariables.flat())) {\n if (!scopedVariables.every(input => input.some(inputVar => inputVar.equals(variable)))) {\n variables.push(variable);\n }\n }\n return {};\n } },\n });\n return uniqTerms(variables);\n }\n\n /**\n * Send a SPARQL query to a SPARQL endpoint and retrieve its bindings as a stream.\n * @param {string} endpoint A SPARQL endpoint URL.\n * @param {string} query A SPARQL query string.\n * @param {RDF.Variable[]} variables The expected variables.\n * @param {IActionContext} context The source context.\n * @param undefVariables Variables that may have undefs.\n * @return {BindingsStream} A stream of bindings.\n */\n public async queryBindingsRemote(\n endpoint: string,\n query: string,\n variables: RDF.Variable[],\n context: IActionContext,\n undefVariables: RDF.Variable[],\n ): Promise<BindingsStream> {\n // Index undef variables\n const undefVariablesSet = new Set(undefVariables.map(v => v.value));\n\n const rawStream = await this.endpointFetcher.fetchBindings(endpoint, query, this.getRequestOptions(context));\n\n const wrapped = wrap<any>(rawStream, { autoStart: false, maxBufferSize: Number.POSITIVE_INFINITY });\n return wrapped.map<RDF.Bindings>((rawData: Record<string, RDF.Term>) => {\n const bindings = variables.map((variable) => {\n const value = rawData[`?${variable.value}`];\n if (!undefVariablesSet.has(variable.value) && !value) {\n Actor.getContextLogger(this.context)?.warn(`The endpoint ${endpoint} failed to provide a binding for ${variable.value}.`);\n }\n return <[RDF.Variable, RDF.Term]>[ variable, value ];\n }).filter(([ _, v ]) => Boolean(v));\n return this.bindingsFactory.bindings(bindings);\n });\n }\n\n public toString(): string {\n return `QuerySourceSparql(${this.url})`;\n }\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@comunica/actor-query-source-identify-hypermedia-sparql",
|
|
3
|
-
"version": "5.
|
|
3
|
+
"version": "5.5.0",
|
|
4
4
|
"description": "A sparql query-source-identify-hypermedia actor",
|
|
5
5
|
"lsd:module": true,
|
|
6
6
|
"license": "MIT",
|
|
@@ -41,22 +41,22 @@
|
|
|
41
41
|
"build:components": "componentsjs-generator"
|
|
42
42
|
},
|
|
43
43
|
"dependencies": {
|
|
44
|
-
"@comunica/bus-http": "^5.
|
|
45
|
-
"@comunica/bus-merge-bindings-context": "^5.
|
|
46
|
-
"@comunica/bus-query-serialize": "^5.
|
|
47
|
-
"@comunica/bus-query-source-identify-hypermedia": "^5.
|
|
48
|
-
"@comunica/context-entries": "^5.
|
|
49
|
-
"@comunica/core": "^5.
|
|
50
|
-
"@comunica/types": "^5.
|
|
51
|
-
"@comunica/utils-algebra": "^5.
|
|
52
|
-
"@comunica/utils-bindings-factory": "^5.
|
|
53
|
-
"@comunica/utils-metadata": "^5.
|
|
54
|
-
"@comunica/utils-query-operation": "^5.
|
|
44
|
+
"@comunica/bus-http": "^5.5.0",
|
|
45
|
+
"@comunica/bus-merge-bindings-context": "^5.5.0",
|
|
46
|
+
"@comunica/bus-query-serialize": "^5.5.0",
|
|
47
|
+
"@comunica/bus-query-source-identify-hypermedia": "^5.5.0",
|
|
48
|
+
"@comunica/context-entries": "^5.5.0",
|
|
49
|
+
"@comunica/core": "^5.5.0",
|
|
50
|
+
"@comunica/types": "^5.5.0",
|
|
51
|
+
"@comunica/utils-algebra": "^5.5.0",
|
|
52
|
+
"@comunica/utils-bindings-factory": "^5.5.0",
|
|
53
|
+
"@comunica/utils-metadata": "^5.5.0",
|
|
54
|
+
"@comunica/utils-query-operation": "^5.5.0",
|
|
55
55
|
"@rdfjs/types": "*",
|
|
56
56
|
"asynciterator": "^3.10.0",
|
|
57
|
-
"fetch-sparql-endpoint": "^7.
|
|
57
|
+
"fetch-sparql-endpoint": "^7.3.0",
|
|
58
58
|
"lru-cache": "^11.2.2",
|
|
59
59
|
"rdf-terms": "^2.0.0"
|
|
60
60
|
},
|
|
61
|
-
"gitHead": "
|
|
61
|
+
"gitHead": "3a258e018a9c5f0b03f531b30ee1cdc659b5b7c9"
|
|
62
62
|
}
|