aboutsummaryrefslogtreecommitdiff
path: root/lib/fragment_graph/rdf_fragment_graph.ml
blob: bc2d99e757958f1e8067c04af0b019220b8e23ed (plain)
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
(*
 * SPDX-FileCopyrightText: 2021 petites singularités <ps-dream@lesoiseaux.io>
 * SPDX-FileCopyrightText: 2021 pukkamustard <pukkamustard@posteo.net>
 *
 * SPDX-License-Identifier: AGPL-3.0-or-later
 *)

module type HASH = sig
  (*** Signature of a hash that is used to compute identifiers. *)

  val hash : string -> Rdf.Iri.t
  (** [hash v] returns the hash of [v] as an iri. *)
end

module type S = sig
  (** RDF Fragment Graph  *)

  (** {1 Predicate and Object} *)

  (** Fragment Graphs can not reuse the {!module:Rdf.Triple.Predicate} and
      {!module:Rdf.Triple.Object} modules as they do not allow Blank Nodes and in
      addition to IRIs, references to fragments are allowed.*)

  module Predicate : sig
    type t =
      | FragmentReference of string
      | Iri of Rdf.Iri.t
      (** Predicate that can appear in a Fragment Graph *)

    val of_iri : ?base_subject:Rdf.Iri.t -> Rdf.Iri.t -> t
    (** [of_iri iri] creates an Iri predicate  *)

    val make_fragment_reference : string -> t
    (** [make_fragment_reference fragment] creates a reference to [fragment] *)

    val pp : t Fmt.t
    [@@ocaml.toplevel_printer]

  end

  module Object : sig
    type t =
      | FragmentReference of string
      | Iri of Rdf.Iri.t
      | Literal of Rdf.Literal.t
      (** Object that can appear in a Fragment Graph  *)

    val of_iri : ?base_subject:Rdf.Iri.t -> Rdf.Iri.t -> t
    (** [of_iri iri] creates an iri object *)

    val of_literal : Rdf.Literal.t -> t
    (** [of_iri iri] creates an literal object *)

    val make_fragment_reference : string -> t
    (** [make_fragment_reference fragment] creates a reference to [fragment] *)

    val pp : t Fmt.t
    [@@ocaml.toplevel_printer]
  end

  type t
  (** Type of a Fragment Graph *)

  (** {1 Constructors} *)

  val empty : t
  (** [empty] is the empty fragment graph *)

  val add_statement : Predicate.t -> Object.t -> t -> t
  (** [add_statement fragment_graph predicate object'] adds a statement to the fragment graph *)

  val add_fragment_statement : string -> Predicate.t -> Object.t -> t -> t
  (** [add_fragment_statement] adds a fragment statement to the fragment graph *)

  val of_triples : Rdf.Triple.t Seq.t -> (Rdf.Iri.t * t) Seq.t
  (** [of_triples triples] returns a sequence of fragment graphs for each base
      subject appearing in [triples]. *)

  (** {1 Accessors}  *)

  val statements : t -> (Predicate.t * Object.t) Seq.t
  (** [statements fragment_graph] returns a list of statements in
      [fragment_graph]. *)

  val fragment_statements : t -> (string * Predicate.t * Object.t) Seq.t
  (** [fragment_statements fragment_graph] returns a list of fragment statements
      in [fragment_graph]. *)

  val to_triples : t -> Rdf.Triple.t Seq.t
  (** [to_triples fragment_graph] returns a list of statements in [fragment_graph] as triples. *)


  (** {1 Content-addressing}  *)

  val base_subject : t -> Rdf.Iri.t
  (** [base_subject fragment_graph] returns the base subject of the fragment graph. *)

  val equal : t -> t -> bool
  (** [equal a b] returns true if [a] is the same Fragment Graph as [b].
      Equality is implemnted by checking the base subject.*)

  val canonical : t -> string
  (** [canonical fragment_graph] returns the canonical serialization of the fragment graph.  *)

  val of_canonical : string -> (t,  string) result
  (** [of_canonical s] attempts to decode the fragment graph from the canonical serialization in [s]*)

  (** {1 (Pretty) Printing}  *)

  val pp : t Fmt.t
  [@@ocaml.toplevel_printer]
  (** [pp ppf t] will output a debug output of the Fragment Graph [t] to the formatter [ppf] *)
end


module Make(H: HASH) = struct

  (* Helper to get the base subject of an IRI *)
  let get_base_subject iri =
    Rdf.Iri.with_fragment iri None

  module Predicate = struct
    type t =
      | FragmentReference of string
      | Iri of Rdf.Iri.t

    let of_iri ?base_subject iri =
      match base_subject with
      | None -> Iri iri
      | Some base_subject ->
        if Rdf.Iri.equal base_subject (get_base_subject iri) then
          Rdf.Iri.fragment iri
          |> Option.value ~default:""
          |> (fun f -> FragmentReference f)
        else
          Iri iri

    let make_fragment_reference id =
      FragmentReference id

    let compare a b =
      match (a, b) with
      | FragmentReference a, FragmentReference b -> String.compare a b
      | Iri a, Iri b -> Rdf.Iri.compare a b
      | FragmentReference _, _ -> -1
      | Iri _, _ -> 1

    let expand base_iri = function
      | FragmentReference fragment ->
        Rdf.Iri.with_fragment base_iri (Some fragment)
        |> Rdf.Triple.Predicate.of_iri
      | Iri iri ->
        iri
        |> Rdf.Triple.Predicate.of_iri

    let pp ppf = function
      | FragmentReference id ->
        Fmt.pf ppf "@[<2><f %s>@]" id
      | Iri iri ->
        Fmt.pf ppf "@[<4><iri %a>@]" Rdf.Iri.pp iri
  end

  module Object = struct
    type t =
      | FragmentReference of string
      | Iri of Rdf.Iri.t
      | Literal of Rdf.Literal.t

    let of_iri ?base_subject iri =
      match base_subject with
      | None -> Iri iri
      | Some base_subject ->
        if Rdf.Iri.equal base_subject (get_base_subject iri) then
          Rdf.Iri.fragment iri
          |> Option.value ~default:""
          |> (fun f -> FragmentReference f)
        else
          Iri iri

    let of_literal literal = Literal literal

    let make_fragment_reference id =
      FragmentReference id

    let compare a b =
      match (a, b) with
      | FragmentReference a, FragmentReference b -> String.compare a b
      | Iri a, Iri b -> Rdf.Iri.compare a b
      | Literal a, Literal b -> Rdf.Literal.compare a b
      | FragmentReference _, _ -> -1
      | Literal _, _ -> -1
      | Iri _, _ -> 1

    let expand base_iri = function
      | FragmentReference fragment ->
        Rdf.Iri.with_fragment base_iri (Some fragment)
        |> Rdf.Triple.Object.of_iri
      | Iri iri ->
        iri
        |> Rdf.Triple.Object.of_iri
      | Literal literal ->
        literal
        |> Rdf.Triple.Object.of_literal

    let pp ppf = function
      | FragmentReference id ->
        Fmt.pf ppf "@[<2><f %s>@]" id
      | Iri iri ->
        Fmt.pf ppf "@[<4><iri %a>@]" Rdf.Iri.pp iri
      | Literal lit ->
        Fmt.pf ppf "@[<4><lit %a>@]" Rdf.Literal.pp lit
  end

  module FragmentMap = Map.Make(String)
  module PredicateMap = Map.Make(Predicate)
  module ObjectSet = Set.Make(Object)


  type t =
    { statements : ObjectSet.t PredicateMap.t;
      fragment_statements : ObjectSet.t PredicateMap.t FragmentMap.t
    }

  let empty =
    { statements = PredicateMap.empty;
      fragment_statements = FragmentMap.empty
    }

  let statements_signleton p o =
    PredicateMap.add
      p (ObjectSet.singleton o)
      PredicateMap.empty

  let statements_union a b =
    PredicateMap.union
      (fun _predicate objects_a objects_b ->
         ObjectSet.union objects_a objects_b
         |> Option.some)
      a b

  let add_statement predicate object' fragment_graph =
    { fragment_graph with
      statements = statements_signleton predicate object'
                   |> statements_union fragment_graph.statements
    }

  let fragment_statements_singleton fragment predicate object' =
    FragmentMap.add
      fragment
      (statements_signleton predicate object')
      FragmentMap.empty

  let fragment_statement_union a b =
    FragmentMap.union
      (fun _fragment statements_a statements_b ->
         Some (statements_union statements_a statements_b)
      )
      a b

  let add_fragment_statement fragment predicate object' fragment_graph =
    { fragment_graph with
      fragment_statements = fragment_statements_singleton fragment predicate object'
                            |> fragment_statement_union fragment_graph.fragment_statements
    }


  (* Constructor from triples *)

  module IriMap = Map.Make(Rdf.Iri)

  let of_triples triples=
    triples
    |> Seq.fold_left
      (fun fgs (triple:Rdf.Triple.t) ->

         (* extract the subject as IRI *)
         let subject_iri =
           Rdf.Triple.Subject.map triple.subject
             (fun iri -> iri)
             (fun _bnode -> failwith "Blank Nodes are not allowed in Fragment Graphs.")
         in

         (* compute the base subject *)
         let base_subject = get_base_subject subject_iri in

         (* extract Predicate as Predicate *)
         let predicate =
           Rdf.Triple.Predicate.map triple.predicate
             (fun iri -> Predicate.of_iri ~base_subject iri)
         in

         (* extract object as Object *)
         let object' =
           Rdf.Triple.Object.map triple.object'
             (fun iri ->  Object.of_iri ~base_subject iri)
             (fun _bnode -> failwith "Blank Nodes are not allowed in Fragment Graphs.")
             Object.of_literal
         in


         match Rdf.Iri.fragment subject_iri with

         (* subject is not a fragment -> add triple as statement *)
         | None ->
           IriMap.update base_subject
             (fun fg_opt ->
                fg_opt
                |> Option.value ~default:empty
                |> add_statement predicate object'
                |> Option.some)
             fgs

         (* subject is a fragment of base_subject -> add as fragment statement *)
         | Some fragment_id ->
           IriMap.update base_subject
             (fun fg_opt ->
                fg_opt
                |> Option.value ~default:empty
                |> add_fragment_statement fragment_id predicate object'
                |> Option.some)
             fgs
      )
      IriMap.empty
    |> IriMap.to_seq

  let statements_to_seq statements =
    PredicateMap.to_seq statements
    |> Seq.flat_map (fun (predicate, os) ->
        ObjectSet.to_seq os
        |> Seq.map (fun o -> predicate,o))

  let statements fg =
    fg.statements
    |> statements_to_seq

  let fragment_statements fg =
    fg.fragment_statements
    |> FragmentMap.to_seq
    |> Seq.flat_map (fun (fragment, statements) ->
        statements_to_seq statements
        |> Seq.map (fun (p,o) -> (fragment, p, o))
      )

  module Serialization = struct

    let cbor_of_predicate = function
      | Predicate.FragmentReference fragment_id ->
        Cbor.Tag (Z.of_int 302, Cbor.TextString fragment_id)
      | Predicate.Iri iri ->
        Rdf_cbor.cbor_of_iri iri

    let cbor_of_object = function
      | Object.FragmentReference fragment_id ->
        Cbor.Tag (Z.of_int 302, Cbor.TextString fragment_id)
      | Object.Iri iri ->
        Rdf_cbor.cbor_of_iri iri
      | Object.Literal literal ->
        Rdf_cbor.cbor_of_literal literal

    let compare a b =
      String.compare
        (Cbor.encode a)
        (Cbor.encode b)

    let cbor_of_statements fg =
      fg
      |> statements
      |> Seq.map
        (fun (predicate, object') ->
           Cbor.Array [
             cbor_of_predicate predicate;
             cbor_of_object object'
           ] )

    let cbor_of_fragment_statements fragment_graph =
      fragment_graph
      |> fragment_statements
      |> Seq.map (fun (f, p, o) ->
          Cbor.Array [
            Cbor.TextString f;
            cbor_of_predicate p;
            cbor_of_object o
          ]
        )

    let cbor_of_fragment_graph fg =
      Seq.append
        (cbor_of_statements fg)
        (cbor_of_fragment_statements fg)
      |> List.of_seq
      |> List.sort_uniq compare
      |> (fun s -> Cbor.Array s)

    let encode fragment_graph =
      cbor_of_fragment_graph fragment_graph
      |> Cbor.encode

    module Parser = struct

      open Angstrom
      open Cbor.Parser

      let predicate =
        any_tag
          (fun z ->
             if Z.(equal z ~$302) then
               any_text_string
               >>| Predicate.make_fragment_reference
             else if Z.(equal z ~$32) then
               any_text_string
               >>| Rdf.Iri.of_string
               >>| Predicate.of_iri
             else
               fail "invalid tag")

      (* Need to redefine this here as required when decoding literals *)
      let iri =
        tag (Z.of_int 32) @@
        any_text_string
        >>| Uri.of_string

      let object' =
        any_tag
          (fun z ->
             if Z.(equal z ~$302) then
               any_text_string
               >>| Object.make_fragment_reference
             else if Z.(equal z ~$32) then
               any_text_string
               >>| Rdf.Iri.of_string
               >>| Object.of_iri
             else if Z.(equal z ~$301) then
               tuple any_text_string iri
               >>| (fun (value, datatype) -> Rdf.Literal.make value datatype)
               >>| Object.of_literal
             else
               fail "invalid tag")

      (* Parser that returns functions that modify a fragment graph.
       * Dunno about performance of this....
       *  *)
      let statement =
        Angstrom.choice
          [
            (fun (predicate, object') -> add_statement predicate object')
            <$> (tuple predicate object');

            (fun (fragment_id, predicate, object') ->
               add_fragment_statement fragment_id predicate object')
            <$> (triple any_text_string predicate object');
          ]

      let fragment_graph =
        Cbor.Parser.array statement
        >>| (fun fs ->
            List.fold_left (fun fragment_graph f  -> f fragment_graph) empty fs
          )

    end

  end

  let canonical fragment_graph =
    Serialization.encode fragment_graph

  let of_canonical s =
    Angstrom.parse_string ~consume:Angstrom.Consume.Prefix
      Serialization.Parser.fragment_graph
      s

  let base_subject fragment_graph =
    fragment_graph
    |> canonical
    |> H.hash


  (* Order of insertion matters so we use *)
  let equal a b =
    Rdf.Iri.equal
      (base_subject a)
      (base_subject b)

  let to_triples fragment_graph =
    let base_subject = base_subject fragment_graph in
    let subject = base_subject |> Rdf.Triple.Subject.of_iri in
    Seq.append
      (fragment_graph
       |> statements
       |> Seq.map
         (fun (p, o) ->
            Rdf.Triple.make
              subject
              (Predicate.expand base_subject p)
              (Object.expand base_subject o)))
      (fragment_graph
       |> fragment_statements
       |> Seq.map
         (fun (f,p,o) ->
            let subject = Rdf.Iri.with_fragment base_subject (Some f)
                          |> Rdf.Triple.Subject.of_iri
            in
            Rdf.Triple.make
              subject
              (Predicate.expand base_subject p)
              (Object.expand base_subject o)))


  let pp_statement ppf (p,o) =
    Fmt.pf ppf "@[<2><s %a %a>@]"
      Predicate.pp p
      Object.pp o

  let pp_fragment_statement ppf (f,p,o) =
    Fmt.pf ppf "@[<3><fs %s %a %a>@]"
      f
      Predicate.pp p
      Object.pp o

  let pp ppf fragment_graph =
    Fmt.pf ppf "@[<v>%a@]@[<v>%a@]"
      Fmt.(seq pp_statement)
      (statements fragment_graph)
      Fmt.(seq pp_fragment_statement)
      (fragment_statements fragment_graph)
end