-
Notifications
You must be signed in to change notification settings - Fork 2
/
client.ts
526 lines (469 loc) · 13.2 KB
/
client.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
import { Config, intoConfig } from "./config";
import { Member } from "./page";
import rdfDereference, { RdfDereferencer } from "rdf-dereference";
import { FileStateFactory, NoStateFactory, StateFactory } from "./state";
import { CBDShapeExtractor } from "extract-cbd-shape";
import { RdfStore } from "rdf-stores";
import { DataFactory } from "rdf-data-factory";
import { Writer as NWriter } from "n3";
import { Quad_Object, Term } from "@rdfjs/types";
import {
enhanced_fetch,
extractMainNodeShape,
FetchConfig,
getObjects,
ModulatorFactory,
Notifier,
streamToArray,
} from "./utils";
import { LDES, SDS, TREE } from "@treecg/types";
import { FetchedPage, Fetcher, longPromise, resetPromise } from "./pageFetcher";
import { Manager } from "./memberManager";
import { OrderedStrategy, StrategyEvents, UnorderedStrategy } from "./strategy";
import debug from "debug";
import type { Writer } from "@ajuvercr/js-runner";
export { intoConfig } from "./config";
export { retry_fetch, extractMainNodeShape } from "./utils";
export type { Member, Page, Relation } from "./page";
export type { Config, ShapeConfig } from "./config";
const log = debug("client");
const df = new DataFactory();
type Controller = ReadableStreamDefaultController<Member>;
export type Ordered = "ascending" | "descending" | "none";
export function replicateLDES(
config: Partial<Config> & { url: string },
ordered: Ordered = "none",
dereferencer?: RdfDereferencer,
streamId?: Term,
): Client {
return new Client(intoConfig(config), ordered, dereferencer, streamId);
}
export type LDESInfo = {
shape: Term;
extractor: CBDShapeExtractor;
timestampPath?: Term;
isVersionOfPath?: Term;
};
async function getInfo(
ldesId: Term,
store: RdfStore,
dereferencer: RdfDereferencer,
config: Config,
): Promise<LDESInfo> {
const logger = log.extend("getShape");
if (config.shapeFile) {
const shapeId = config.shapeFile.startsWith("http")
? config.shapeFile
: "file://" + config.shapeFile;
const resp = await rdfDereference.dereference(config.shapeFile, {
localFiles: true,
fetch: config.fetch
});
const quads = await streamToArray(resp.data);
config.shape = {
quads: quads,
shapeId: df.namedNode(shapeId),
};
}
let shapeIds = config.noShape
? []
: getObjects(store, ldesId, TREE.terms.shape);
let timestampPaths = getObjects(store, ldesId, LDES.terms.timestampPath);
let isVersionOfPaths = getObjects(store, ldesId, LDES.terms.versionOfPath);
logger(
"Found %d shapes, %d timestampPaths, %d isVersionOfPaths",
shapeIds.length,
timestampPaths.length,
isVersionOfPaths.length,
);
if (
!config.noShape &&
(shapeIds.length === 0 ||
timestampPaths.length === 0 ||
isVersionOfPaths.length === 0)
) {
try {
logger("Maybe find more info at %s", ldesId.value);
const resp = await dereferencer.dereference(ldesId.value, {
localFiles: true,
fetch: config.fetch,
});
store = RdfStore.createDefault();
await new Promise((resolve, reject) => {
store.import(resp.data).on("end", resolve).on("error", reject);
});
shapeIds = getObjects(store, null, TREE.terms.shape);
timestampPaths = getObjects(store, null, LDES.terms.timestampPath);
isVersionOfPaths = getObjects(store, null, LDES.terms.versionOfPath);
logger(
"Found %d shapes, %d timestampPaths, %d isVersionOfPaths",
shapeIds.length,
timestampPaths.length,
isVersionOfPaths.length,
);
} catch (ex: any) { }
}
if (shapeIds.length > 1) {
console.error("Expected at most one shape id, found " + shapeIds.length);
}
if (timestampPaths.length > 1) {
console.error(
"Expected at most one timestamp path, found " + timestampPaths.length,
);
}
if (isVersionOfPaths.length > 1) {
console.error(
"Expected at most one versionOf path, found " + isVersionOfPaths.length,
);
}
const shapeConfigStore = RdfStore.createDefault();
if (config.shape) {
for (const quad of config.shape.quads) {
shapeConfigStore.addQuad(quad);
}
// Make sure the shapeId is as defined in the given shape file
if (config.shape.shapeId.value.startsWith("file://")) {
config.shape.shapeId = extractMainNodeShape(shapeConfigStore);
}
}
return {
extractor: new CBDShapeExtractor(
config.shape ? shapeConfigStore : store,
dereferencer,
{
cbdDefaultGraph: config.onlyDefaultGraph,
fetch: config.fetch,
},
),
shape: config.shape ? config.shape.shapeId : shapeIds[0],
timestampPath: timestampPaths[0],
isVersionOfPath: isVersionOfPaths[0],
};
}
type EventMap = Record<string, any>;
type EventKey<T extends EventMap> = string & keyof T;
type EventReceiver<T> = (params: T) => void;
export type ClientEvents = {
fragment: void;
mutable: void;
poll: void;
error: any;
};
export class Client {
private config: Config;
private dereferencer: RdfDereferencer;
private fetcher!: Fetcher;
private memberManager!: Manager;
private strategy!: OrderedStrategy | UnorderedStrategy;
public streamId?: Term;
private ordered: Ordered;
private modulatorFactory;
private stateFactory: StateFactory;
private listeners: {
[K in keyof ClientEvents]?: Array<(p: ClientEvents[K]) => void>;
} = {};
constructor(
config: Config,
ordered: Ordered = "none",
dereferencer?: RdfDereferencer,
stream?: Term,
) {
this.config = config;
this.dereferencer = dereferencer ?? rdfDereference;
this.streamId = stream;
this.ordered = ordered;
this.stateFactory = config.stateFile
? new FileStateFactory(config.stateFile)
: new NoStateFactory();
this.modulatorFactory = new ModulatorFactory(this.stateFactory);
if (process) {
process.on("SIGINT", () => {
console.log("Caught interrupt signal, saving");
this.stateFactory.write();
process.exit();
});
}
}
on<K extends EventKey<ClientEvents>>(
key: K,
fn: EventReceiver<ClientEvents[K]>,
) {
this.listeners[key] = (
this.listeners[key] || <Array<(p: ClientEvents[K]) => void>>[]
).concat(fn);
}
private emit<K extends EventKey<ClientEvents>>(
key: K,
data: ClientEvents[K],
) {
(this.listeners[key] || []).forEach(function (fn) {
fn(data);
});
}
async init(
emit: (member: Member) => void,
close: () => void,
factory: ModulatorFactory,
): Promise<void> {
const logger = log.extend("init");
// Fetch the url
const root = await fetchPage(
this.config.url,
this.dereferencer,
this.config.fetch,
);
// Try to get a shape
// TODO Choose a view
const viewQuads = root.data.getQuads(null, TREE.terms.view, null, null);
let ldesId: Term = df.namedNode(this.config.url);
if (!this.config.urlIsView) {
if (viewQuads.length === 0) {
console.error(
"Did not find tree:view predicate, this is required to interpret the LDES",
);
} else {
ldesId = viewQuads[0].object;
}
}
const info = await getInfo(
ldesId,
root.data,
this.dereferencer,
this.config,
);
const state = this.stateFactory.build<Set<string>>(
"members",
(set) => {
const arr = [...set.values()];
return JSON.stringify(arr);
},
(inp) => new Set(JSON.parse(inp)),
() => new Set(),
);
this.streamId = this.streamId || viewQuads[0].subject;
this.memberManager = new Manager(
this.streamId || viewQuads[0].subject,
state.item,
info,
);
logger("timestampPath %o", !!info.timestampPath);
if (this.ordered !== "none" && !info.timestampPath) {
throw "Can only emit members in order, if LDES is configured with timestampPath";
}
this.fetcher = new Fetcher(
this.dereferencer,
this.config.loose,
this.config.fetch,
this.config.after,
this.config.before,
);
const notifier: Notifier<StrategyEvents, {}> = {
error: (ex: any) => this.emit("error", ex),
fragment: () => this.emit("fragment", undefined),
member: (m) => {
// Check if member is within date constraints (if any)
if (this.config.before) {
if (
m.timestamp &&
m.timestamp instanceof Date &&
m.timestamp > this.config.before
) {
return;
}
}
if (this.config.after) {
if (
m.timestamp &&
m.timestamp instanceof Date &&
m.timestamp < this.config.after
) {
return;
}
}
emit(m);
},
pollCycle: () => {
this.emit("poll", undefined);
},
mutable: () => {
this.emit("mutable", undefined);
},
close: () => {
this.stateFactory.write();
close();
},
};
this.strategy =
this.ordered !== "none"
? new OrderedStrategy(
this.memberManager,
this.fetcher,
notifier,
factory,
this.ordered,
this.config.polling,
this.config.pollInterval,
)
: new UnorderedStrategy(
this.memberManager,
this.fetcher,
notifier,
factory,
this.config.polling,
this.config.pollInterval,
);
logger("Found %d views, choosing %s", viewQuads.length, ldesId.value);
this.strategy.start(ldesId.value);
}
stream(strategy?: {
highWaterMark?: number;
size?: (chunk: Member) => number;
}): ReadableStream<Member> {
const emitted = longPromise();
const config: UnderlyingDefaultSource = {
//
// Called when starting the stream
//
start: async (controller: Controller) => {
this.on("error", (error) => {
this.stateFactory.write();
this.memberManager.close();
this.fetcher.close();
controller.error(error);
});
this.modulatorFactory.pause();
await this.init(
(member) => {
controller.enqueue(member);
resetPromise(emitted);
},
() => controller.close(),
this.modulatorFactory,
);
},
//
// Called when the internal buffer is not full
//
pull: async () => {
resetPromise(emitted);
this.modulatorFactory.unpause();
await emitted.waiting;
this.modulatorFactory.pause();
return;
},
//
// Called when canceled
//
cancel: async () => {
log("Canceled");
this.stateFactory.write();
this.strategy.cancel();
this.memberManager.close();
this.fetcher.close();
},
};
const out = new ReadableStream(config, strategy);
return out;
}
}
async function fetchPage(
location: string,
dereferencer: RdfDereferencer,
fetch_f?: typeof fetch,
): Promise<FetchedPage> {
const resp = await dereferencer.dereference(location, {
localFiles: true,
fetch: fetch_f,
});
const url = resp.url;
const data = RdfStore.createDefault();
await new Promise((resolve, reject) => {
data.import(resp.data).on("end", resolve).on("error", reject);
});
return <FetchedPage>{ url, data };
}
export async function processor(
writer: Writer<string>,
url: string,
before?: Date,
after?: Date,
ordered?: string,
follow?: boolean,
pollInterval?: number,
shape?: string,
noShape?: boolean,
save?: string,
loose?: boolean,
urlIsView?: boolean,
verbose?: boolean,
fetch_config?: {
auth?: {
type: "basic";
auth: string;
host: string;
};
concurrent?: number;
retry?: {
codes: number[];
maxRetries: number;
};
},
) {
if (fetch_config?.auth) {
fetch_config.auth.host = new URL(url).host;
}
const client = replicateLDES(
{
loose,
noShape,
shapeFile: shape,
polling: follow,
url: url,
after,
before,
stateFile: save,
pollInterval: pollInterval,
urlIsView,
fetch: fetch_config ? enhanced_fetch(fetch_config) : fetch,
},
<Ordered>ordered || "none",
);
if (verbose) {
client.on("fragment", () => console.error("Fragment!"));
}
return async () => {
const reader = client.stream({ highWaterMark: 10 }).getReader();
let el = await reader.read();
const seen = new Set();
while (el) {
if (el.value) {
seen.add(el.value.id);
if (verbose) {
if (seen.size % 100 == 1) {
console.error(
"Got member",
seen.size,
"with",
el.value.quads.length,
"quads",
);
}
}
const blank = df.blankNode();
const quads = el.value.quads.slice();
quads.push(
df.quad(blank, SDS.terms.stream, <Quad_Object>client.streamId!),
df.quad(blank, SDS.terms.payload, <Quad_Object>el.value.id!),
);
await writer.push(new NWriter().quadsToString(quads));
}
if (el.done) {
break;
}
el = await reader.read();
}
if (verbose) {
console.error("Found", seen.size, "members");
}
};
}