Files @ 17b268d2b7f3
Branch filter:

Location: light9/light9/web/graph.ts

drewp@bigasterisk.com
ws fix
  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
526
527
528
529
530
531
import * as d3 from "d3";
import debug from "debug";
import * as N3 from "n3";
import { Quad, Quad_Subject, Quad_Predicate, Quad_Object, Quad_Graph } from "n3";
import { filter, sortBy, unique } from "underscore";
import { allPatchSubjs, Patch } from "./patch";
import { RdfDbClient } from "./rdfdbclient";
const log = debug("graph");

const RDF = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";

interface QuadPattern {
  subject: Quad_Subject | null;
  predicate: Quad_Predicate | null;
  object: Quad_Object | null;
  graph: Quad_Graph | null;
}

class Handler {
  patterns: QuadPattern[];
  innerHandlers: Handler[];
  // a function and the quad patterns it cared about
  constructor(public func: ((p: Patch) => void) | null, public label: string) {
    this.patterns = []; // s,p,o,g quads that should trigger the next run
    this.innerHandlers = []; // Handlers requested while this one was running
  }
}

class AutoDependencies {
  handlers: Handler;
  handlerStack: Handler[];
  constructor() {
    // tree of all known Handlers (at least those with non-empty
    // patterns). Top node is not a handler.
    this.handlers = new Handler(null, "root");
    this.handlerStack = [this.handlers]; // currently running
  }

  runHandler(func: any, label: any) {
    // what if we have this func already? duplicate is safe?

    if (label == null) {
      throw new Error("missing label");
    }

    const h = new Handler(func, label);
    const tailChildren = this.handlerStack[this.handlerStack.length - 1].innerHandlers;
    const matchingLabel = filter(tailChildren, (c: { label: any }) => c.label === label).length;
    // ohno, something depends on some handlers getting run twice :(
    if (matchingLabel < 2) {
      tailChildren.push(h);
    }
    //console.time("handler #{label}")
    return this._rerunHandler(h, null);
  }
  //console.timeEnd("handler #{label}")
  //@_logHandlerTree()

  _rerunHandler(handler: Handler, patch: any) {
    handler.patterns = [];
    this.handlerStack.push(handler);
    try {
      if (handler.func === null) {
        throw new Error("tried to rerun root");
      }
      return handler.func(patch);
    } catch (e) {
      return log("error running handler: ", e);
    } finally {
      // assuming here it didn't get to do all its queries, we could
      // add a *,*,*,* handler to call for sure the next time?
      //log('done. got: ', handler.patterns)
      this.handlerStack.pop();
    }
  }
  // handler might have no watches, in which case we could forget about it

  _logHandlerTree() {
    log("handler tree:");
    var prn = function (h: Handler, depth: number) {
      let indent = "";
      for (let i = 0, end = depth, asc = 0 <= end; asc ? i < end : i > end; asc ? i++ : i--) {
        indent += "  ";
      }
      log(`${indent} \"${h.label}\" ${h.patterns.length} pats`);
      return Array.from(h.innerHandlers).map((c: any) => prn(c, depth + 1));
    };
    return prn(this.handlers, 0);
  }

  _handlerIsAffected(child: Handler, patchSubjs: Set<string>) {
    if (patchSubjs === null) {
      return true;
    }
    if (!child.patterns.length) {
      return false;
    }

    for (let stmt of Array.from(child.patterns)) {
      if (stmt.subject === null) {
        // wildcard on subject
        return true;
      }
      if (patchSubjs.has(stmt.subject.value)) {
        return true;
      }
    }

    return false;
  }

  graphChanged(patch: Patch) {
    // SyncedGraph is telling us this patch just got applied to the graph.

    const subjs = allPatchSubjs(patch);

    var rerunInners = (cur: Handler) => {
      const toRun = cur.innerHandlers.slice();
      for (let child of Array.from(toRun)) {
        //match = @_handlerIsAffected(child, subjs)
        //continue if not match
        //log('match', child.label, match)
        //child.innerHandlers = [] # let all children get called again

        this._rerunHandler(child, patch);
        rerunInners(child);
      }
    };
    return rerunInners(this.handlers);
  }

  askedFor(s: Quad_Subject | null, p: Quad_Predicate | null, o: Quad_Object | null, g: Quad_Graph | null) {
    // SyncedGraph is telling us someone did a query that depended on
    // quads in the given pattern.
    const current = this.handlerStack[this.handlerStack.length - 1];
    if (current != null && current !== this.handlers) {
      return current.patterns.push({ subject: s, predicate: p, object: o, graph: g } as QuadPattern);
    }
  }
}

export class SyncedGraph {
  _autoDeps: AutoDependencies;
  _client: any;
  graph: N3.Store;
  cachedFloatValues: any;
  cachedUriValues: any;
  prefixFuncs: (x: string) => string = (x) => x;
  serial: any;
  _nextNumber: any;
  // Main graph object for a browser to use. Syncs both ways with
  // rdfdb. Meant to hide the choice of RDF lib, so we can change it
  // later.
  //
  // Note that _applyPatch is the only method to write to the graph, so
  // it can fire subscriptions.

  constructor(
    // patchSenderUrl is the /syncedGraph path of an rdfdb server.
    public patchSenderUrl: any,
    // prefixes can be used in Uri(curie) calls.
    public prefixes: { [short: string]: string },
    private setStatus: any,
    // called if we clear the graph
    private clearCb: any
  ) {
    this.graph = new N3.Store();
    this._autoDeps = new AutoDependencies(); // replaces GraphWatchers
    this.clearGraph();

    if (this.patchSenderUrl) {
      this._client = new RdfDbClient(this.patchSenderUrl, this._clearGraphOnNewConnection.bind(this), this._applyPatch.bind(this), this.setStatus);
    }
  }

  clearGraph() {
    // just deletes the statements; watchers are unaffected.
    if (this.graph != null) {
      this._applyPatch({ adds: [], dels: this.graph.getQuads(null, null, null, null) });
    }

    // if we had a Store already, this lets N3.Store free all its indices/etc
    this.graph = new N3.Store();
    this._addPrefixes(this.prefixes);
    this.cachedFloatValues = new Map(); // s + '|' + p -> number
    return (this.cachedUriValues = new Map()); // s + '|' + p -> Uri
  }

  _clearGraphOnNewConnection() {
    // must not send a patch to the server!
    log("graph: clearGraphOnNewConnection");
    this.clearGraph();
    log("graph: clearGraphOnNewConnection done");
    if (this.clearCb != null) {
      return this.clearCb();
    }
  }

  _addPrefixes(prefixes: { [x: string]: string }) {
    for (let k of Array.from(prefixes || {})) {
      this.prefixes[k] = prefixes[k];
    }
    this.prefixFuncs = N3.Util.prefixes(this.prefixes);
  }

  Uri(curie: string) {
    if (curie == null) {
      throw new Error("no uri");
    }
    if (curie.match(/^http/)) {
      return N3.DataFactory.namedNode(curie);
    }
    const part = curie.split(":");
    return this.prefixFuncs(part[0])(part[1]);
  }

  Literal(jsValue: any) {
    return N3.DataFactory.literal(jsValue);
  }

  LiteralRoundedFloat(f: number) {
    return N3.DataFactory.literal(d3.format(".3f")(f), this.Uri("http://www.w3.org/2001/XMLSchema#double"));
  }

  Quad(s: any, p: any, o: any, g: any) {
    return N3.DataFactory.quad(s, p, o, g);
  }

  toJs(literal: { value: any }) {
    // incomplete
    return parseFloat(literal.value);
  }

  loadTrig(trig: any, cb: () => any) {
    // for debugging
    const patch: Patch = { dels: [], adds: [] };
    const parser = new N3.Parser();
    return parser.parse(trig, (error: any, quad: any, prefixes: any) => {
      if (error) {
        throw new Error(error);
      }
      if (quad) {
        return patch.adds.push(quad);
      } else {
        this._applyPatch(patch);
        this._addPrefixes(prefixes);
        if (cb) {
          return cb();
        }
      }
    });
  }

  quads(): any {
    // for debugging
    return Array.from(this.graph.getQuads(null, null, null, null)).map((q: Quad) => [q.subject, q.predicate, q.object, q.graph]);
  }

  applyAndSendPatch(patch: Patch) {
    console.time("applyAndSendPatch");
    if (!this._client) {
      log("not connected-- dropping patch");
      return;
    }
    if (!Array.isArray(patch.adds) || !Array.isArray(patch.dels)) {
      console.timeEnd("applyAndSendPatch");
      log("corrupt patch");
      throw new Error(`corrupt patch: ${JSON.stringify(patch)}`);
    }

    this._validatePatch(patch);

    this._applyPatch(patch);
    if (this._client) {
      this._client.sendPatch(patch);
    }
    return console.timeEnd("applyAndSendPatch");
  }

  _validatePatch(patch: Patch) {
    return [patch.adds, patch.dels].map((qs: Quad[]) =>
      (() => {
        const result = [];
        for (let q of Array.from(qs)) {
          if (!q.equals) {
            throw new Error("doesn't look like a proper Quad");
          }
          if (!q.subject.id || q.graph.id == null || q.predicate.id == null) {
            throw new Error(`corrupt patch: ${JSON.stringify(q)}`);
          } else {
            result.push(undefined);
          }
        }
        return result;
      })()
    );
  }

  _applyPatch(patch: Patch) {
    // In most cases you want applyAndSendPatch.
    //
    // This is the only method that writes to @graph!
    let quad: any;
    this.cachedFloatValues.clear();
    this.cachedUriValues.clear();
    for (quad of Array.from(patch.dels)) {
      //log("remove #{JSON.stringify(quad)}")
      const did = this.graph.removeQuad(quad);
    }
    //log("removed: #{did}")
    for (quad of Array.from(patch.adds)) {
      this.graph.addQuad(quad);
    }
    //log('applied patch locally', patchSizeSummary(patch))
    return this._autoDeps.graphChanged(patch);
  }

  getObjectPatch(s: N3.NamedNode, p: N3.NamedNode, newObject: N3.Quad_Object, g: N3.NamedNode): Patch {
    // make a patch which removes existing values for (s,p,*,c) and
    // adds (s,p,newObject,c). Values in other graphs are not affected.
    const existing = this.graph.getQuads(s, p, null, g);
    return {
      dels: existing,
      adds: [this.Quad(s, p, newObject, g)],
    };
  }

  patchObject(s: N3.NamedNode, p: N3.NamedNode, newObject: N3.Quad_Object, g: N3.NamedNode) {
    return this.applyAndSendPatch(this.getObjectPatch(s, p, newObject, g));
  }

  clearObjects(s: N3.NamedNode, p: N3.NamedNode, g: N3.NamedNode) {
    return this.applyAndSendPatch({
      dels: this.graph.getQuads(s, p, null, g),
      adds: [],
    });
  }

  runHandler(func: any, label: any) {
    // runs your func once, tracking graph calls. if a future patch
    // matches what you queried, we runHandler your func again (and
    // forget your queries from the first time).

    // helps with memleak? not sure yet. The point was if two matching
    // labels get puushed on, we should run only one. So maybe
    // appending a serial number is backwards.
    if (!this.serial) {
      this.serial = 1;
    }
    this.serial += 1;
    //label = label + @serial

    return this._autoDeps.runHandler(func, label);
  }

  _singleValue(s: Quad_Subject, p: Quad_Predicate) {
    this._autoDeps.askedFor(s, p, null, null);
    const quads = this.graph.getQuads(s, p, null, null);
    const objs = new Set(Array.from(quads).map((q: Quad) => q.object));

    switch (objs.size) {
      case 0:
        throw new Error("no value for " + s.value + " " + p.value);
      case 1:
        var obj = objs.values().next().value;
        return obj;
      default:
        throw new Error("too many different values: " + JSON.stringify(quads));
    }
  }

  floatValue(s: Quad_Subject, p: Quad_Predicate) {
    const key = s.value + "|" + p.value;
    const hit = this.cachedFloatValues.get(key);
    if (hit !== undefined) {
      return hit;
    }
    //log('float miss', s, p)

    const v = this._singleValue(s, p).value;
    const ret = parseFloat(v);
    if (isNaN(ret)) {
      throw new Error(`${s.value} ${p.value} -> ${v} not a float`);
    }
    this.cachedFloatValues.set(key, ret);
    return ret;
  }

  stringValue(s: any, p: any) {
    return this._singleValue(s, p).value;
  }

  uriValue(s: Quad_Subject, p: Quad_Predicate) {
    const key = s.value + "|" + p.value;
    const hit = this.cachedUriValues.get(key);
    if (hit !== undefined) {
      return hit;
    }

    const ret = this._singleValue(s, p);
    this.cachedUriValues.set(key, ret);
    return ret;
  }

  labelOrTail(uri: { value: { split: (arg0: string) => any } }) {
    let ret: any;
    try {
      ret = this.stringValue(uri, this.Uri("rdfs:label"));
    } catch (error) {
      const words = uri.value.split("/");
      ret = words[words.length - 1];
    }
    if (!ret) {
      ret = uri.value;
    }
    return ret;
  }

  objects(s: any, p: any) {
    this._autoDeps.askedFor(s, p, null, null);
    const quads = this.graph.getQuads(s, p, null, null);
    return Array.from(quads).map((q: { object: any }) => q.object);
  }

  subjects(p: any, o: any) {
    this._autoDeps.askedFor(null, p, o, null);
    const quads = this.graph.getQuads(null, p, o, null);
    return Array.from(quads).map((q: { subject: any }) => q.subject);
  }

  items(list: any) {
    const out = [];
    let current = list;
    while (true) {
      if (current === RDF + "nil") {
        break;
      }

      this._autoDeps.askedFor(current, null, null, null); // a little loose

      const firsts = this.graph.getQuads(current, RDF + "first", null, null);
      const rests = this.graph.getQuads(current, RDF + "rest", null, null);
      if (firsts.length !== 1) {
        throw new Error(`list node ${current} has ${firsts.length} rdf:first edges`);
      }
      out.push(firsts[0].object);

      if (rests.length !== 1) {
        throw new Error(`list node ${current} has ${rests.length} rdf:rest edges`);
      }
      current = rests[0].object;
    }

    return out;
  }

  contains(s: any, p: any, o: any) {
    this._autoDeps.askedFor(s, p, o, null);
    log("contains calling getQuads when graph has ", this.graph.size);
    return this.graph.getQuads(s, p, o, null).length > 0;
  }

  nextNumberedResources(base: { id: any }, howMany: number) {
    // base is NamedNode or string
    // Note this is unsafe before we're synced with the graph. It'll
    // always return 'name0'.
    if (base.id) {
      base = base.id;
    }
    const results = [];

    // @contains is really slow.
    if (this._nextNumber == null) {
      this._nextNumber = new Map();
    }
    let start = this._nextNumber.get(base);
    if (start === undefined) {
      start = 0;
    }

    for (let serial = start, asc = start <= 1000; asc ? serial <= 1000 : serial >= 1000; asc ? serial++ : serial--) {
      const uri = this.Uri(`${base}${serial}`);
      if (!this.contains(uri, null, null)) {
        results.push(uri);
        log("nextNumberedResources", `picked ${uri}`);
        this._nextNumber.set(base, serial + 1);
        if (results.length >= howMany) {
          return results;
        }
      }
    }
    throw new Error(`can't make sequential uri with base ${base}`);
  }

  nextNumberedResource(base: any) {
    return this.nextNumberedResources(base, 1)[0];
  }

  contextsWithPattern(s: any, p: any, o: any) {
    this._autoDeps.askedFor(s, p, o, null);
    const ctxs = [];
    for (let q of Array.from(this.graph.getQuads(s, p, o, null))) {
      ctxs.push(q.graph);
    }
    return unique(ctxs);
  }

  sortKey(uri: N3.NamedNode) {
    const parts = uri.value.split(/([0-9]+)/);
    const expanded = parts.map(function (p: string) {
      const f = parseInt(p);
      if (isNaN(f)) {
        return p;
      }
      return p.padStart(8, "0");
    });
    return expanded.join("");
  }

  sortedUris(uris: any) {
    return sortBy(uris, this.sortKey);
  }

  prettyLiteral(x: any) {
    if (typeof x === "number") {
      return this.LiteralRoundedFloat(x);
    } else {
      return this.Literal(x);
    }
  }
}