This repository has been archived by the owner on Sep 28, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathentity.go
640 lines (560 loc) · 15.2 KB
/
entity.go
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
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
// Copyright 2017 Pilosa Corp.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
// CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
package pdk
import (
"encoding/binary"
"encoding/json"
"math"
"reflect"
"time"
"github.com/pkg/errors"
)
// IRI is either a full IRI, or will map to one when the record in which it is
// contained is processed in relation to a context:
// (https://json-ld.org/spec/latest/json-ld/#the-context)
type IRI string
// Property represents a Predicate, and can be turned into a Predicate IRI by a context
type Property string
type Context map[string]interface{}
// Entity is the "root" node of a graph branching out from a certain resource
// denoted by the Subject. This is a convenience vs just handling a list of
// Triples as we expect to structure indexing around a particular class of thing
// which we ingest many instances of as records.
type Entity struct {
Subject IRI `json:"@id"`
Objects map[Property]Object
}
func (e *Entity) Equal(e2 *Entity) error {
if e.Subject != e2.Subject {
return errors.Errorf("subject '%v' != '%v", e.Subject, e2.Subject)
}
return equal(e, e2)
}
func equal(o, o2 Object) error {
if reflect.TypeOf(o) != reflect.TypeOf(o2) {
return errors.Errorf("objs are different types: %T and %T", o, o2)
}
switch o.(type) {
case *Entity:
e, e2 := o.(*Entity), o2.(*Entity)
if len(e.Objects) != len(e2.Objects) {
return errors.Errorf("entities have different number of objects, %d and %d", len(e.Objects), len(e2.Objects))
}
for pred, obj := range e.Objects {
obj2, ok := e2.Objects[pred]
if !ok {
return errors.Errorf("object 2 has no value at %v", pred)
}
eqErr := equal(obj, obj2)
if eqErr != nil {
return errors.Wrapf(eqErr, "%v", pred)
}
}
case Objects:
os, os2 := o.(Objects), o2.(Objects)
if len(os) != len(os2) {
return errors.Errorf("object slices have different lengths, %d and %d", len(os), len(os2))
}
for i := 0; i < len(os); i++ {
obj1, obj2 := os[i], os2[i]
eqErr := equal(obj1, obj2)
if eqErr != nil {
return errors.Wrapf(eqErr, "index %d", i)
}
}
default:
_, ok := o.(Literal)
_, ok2 := o2.(Literal)
if !(ok && ok2) {
return errors.Errorf("expected two literals, but got '%v' and '%v' of %T and %T", o, o2, o, o2)
}
if o != o2 {
return errors.Errorf("'%v' and '%v' not equal", o, o2)
}
}
return nil
}
var (
ErrPathNotFound = errors.New("path not found in Entity")
ErrNotALiteral = errors.New("value at path is not a Literal")
ErrEmptyPath = errors.New("path is empty")
ErrUnexpectedType = errors.New("unexpected type")
)
// Literal gets the literal at the path in the Entity.
func (e *Entity) Literal(path ...string) (Literal, error) {
var cur = e
var ok bool
var lit Literal
for i, prop := range path {
var val Object
val, ok = cur.Objects[Property(prop)]
if !ok {
return nil, ErrPathNotFound
}
if i == len(path)-1 {
lit, ok = val.(Literal)
if !ok {
return nil, errors.Wrapf(ErrNotALiteral, "%#v", cur)
}
return lit, nil
}
cur, ok = val.(*Entity)
if !ok {
return nil, ErrPathNotFound
}
}
return nil, ErrEmptyPath
}
// F64 tries to get a float64 at the given path in the Entity.
func (e *Entity) F64(path ...string) (F64, error) {
lit, err := e.Literal(path...)
if err != nil {
return 0, errors.Wrap(err, "getting literal")
}
f64, ok := lit.(F64)
if !ok {
return 0, errors.Wrapf(ErrUnexpectedType, "%#v not a float64", lit)
}
return f64, nil
}
// NewEntity returns a newly allocated Entity.
func NewEntity() *Entity {
return &Entity{
Objects: make(map[Property]Object),
}
}
// SetPath ensures that a path exists, creating Entities along the way if
// necessary. If it encounters a non-Entity, it will return an error.
func (e *Entity) SetPath(path ...string) (*Entity, error) {
var cur = e
for i, prop := range path {
val, ok := cur.Objects[Property(prop)]
if !ok {
cur.Objects[Property(prop)] = NewEntity()
cur = cur.Objects[Property(prop)].(*Entity)
continue
}
cur, ok = val.(*Entity)
if !ok {
return nil, errors.Wrapf(ErrPathNotFound, "depth %d property %v, not an entity %#v", i, prop, val)
}
}
return cur, nil
}
// SetString
func (e *Entity) SetString(value string, path ...string) error {
if len(path) == 0 {
return ErrEmptyPath
}
ent, err := e.SetPath(path[:len(path)-1]...)
if err != nil {
return errors.Wrap(err, "setting path")
}
ent.Objects[Property(path[len(path)-1])] = S(value)
return nil
}
// EntityWithContext associates a Context
// (https://json-ld.org/spec/latest/json-ld/#the-context) with an Entity so that
// it can be Marshaled to valid and useful JSON-LD.
type EntityWithContext struct {
Entity
Context Context `json:"@context"`
}
// Object is an interface satisfied by all things which may appear as objects in
// RDF triples. All literals are objects, but not all objects are literals.
type Object interface {
isObj()
}
type Objects []Object
func (o Objects) isObj() {}
func (e *Entity) isObj() {}
// MarshalJSON is a custom JSON marshaler for Entity objects to ensure that they
// serialize to valid JSON-LD (https://json-ld.org/ spec/latest/json-ld/). This
// allows for easy (if not particularly performant) interoperation with other
// variants of RDF linked data.
func (e *Entity) MarshalJSON() ([]byte, error) {
// TODO - this implementation does a lot of in-memory copying for simplicity, can probably be optimized.
ret := make(map[Property]interface{})
if e.Subject != "" {
ret["@id"] = e.Subject
}
for k, v := range e.Objects {
if val, exists := ret[k]; exists {
return nil, errors.Errorf("invalid entity for json: '%v' already exists at '%v', can't add '%v'", val, k, v)
}
ret[k] = v
}
return json.Marshal(ret)
}
// Literal interface is implemented by types which correspond to RDF Literals.
type Literal interface {
literal()
}
type B bool
func (B) literal() {}
func (B B) MarshalJSON() ([]byte, error) {
ret := map[string]interface{}{
"@type": "xsd:boolean",
"@value": bool(B),
}
return json.Marshal(ret)
}
type S string
func (S) literal() {}
// TODO define and specifically support these things
// type Location struct {
// Latitude float64 `json:"latitude"`
// Longitude float64 `json:"longitude"`
// }
// func (l *Location) MarshalJSON() ([]byte, error) {
// ret := make(map[string]interface{})
// ret["@type"] = "http://schema.org/GeoCoordinates"
// ret["latitude"] = l.Latitude
// ret["longitude"] = l.Longitude
// return json.Marshal(ret)
// }
// type IPv4 net.IP
// func (ip IPv4) MarshalJSON() ([]byte, error) {
// ret := map[string]interface{}{
// "@type": "http://schema.pilosa.com/v0.1/ipv4",
// "@value": fmt.Sprintf("%s", ip),
// }
// return json.Marshal(ret)
// }
// type IPv6 net.IP
// func (ip IPv6) MarshalJSON() ([]byte, error) {
// ret := map[string]interface{}{
// "@type": "http://schema.pilosa.com/v0.1/ipv6",
// "@value": fmt.Sprintf("%s", ip),
// }
// return json.Marshal(ret)
// }
type Time time.Time
func (Time) literal() {}
type F32 float32
func (F32) literal() {}
func (F F32) MarshalJSON() ([]byte, error) {
ret := map[string]interface{}{
"@type": "xsd:float",
"@value": float32(F),
}
return json.Marshal(ret)
}
type F64 float64
func (F64) literal() {}
func (F F64) MarshalJSON() ([]byte, error) {
ret := map[string]interface{}{
"@type": "xsd:double",
"@value": float64(F),
}
return json.Marshal(ret)
}
type I int
func (I) literal() {}
func (I I) MarshalJSON() ([]byte, error) {
ret := map[string]interface{}{
"@type": "xsd:long",
"@value": int(I),
}
return json.Marshal(ret)
}
func (i *I) UnmarshalJSON(b []byte) error {
var m map[string]interface{}
if err := json.Unmarshal(b, &m); err != nil {
return err
}
*i = I((m["@value"]).(float64))
return nil
}
type I8 int8
func (I8) literal() {}
func (I I8) MarshalJSON() ([]byte, error) {
ret := map[string]interface{}{
"@type": "xsd:byte",
"@value": int8(I),
}
return json.Marshal(ret)
}
func (i *I8) UnmarshalJSON(b []byte) error {
var m map[string]interface{}
if err := json.Unmarshal(b, &m); err != nil {
return err
}
*i = I8((m["@value"]).(float64))
return nil
}
type I16 int16
func (I16) literal() {}
func (I I16) MarshalJSON() ([]byte, error) {
ret := map[string]interface{}{
"@type": "xsd:short",
"@value": int16(I),
}
return json.Marshal(ret)
}
func (i *I16) UnmarshalJSON(b []byte) error {
var m map[string]interface{}
if err := json.Unmarshal(b, &m); err != nil {
return err
}
*i = I16((m["@value"]).(float64))
return nil
}
type I32 int32
func (I32) literal() {}
func (I I32) MarshalJSON() ([]byte, error) {
ret := map[string]interface{}{
"@type": "xsd:int",
"@value": int32(I),
}
return json.Marshal(ret)
}
func (i *I32) UnmarshalJSON(b []byte) error {
var m map[string]interface{}
if err := json.Unmarshal(b, &m); err != nil {
return err
}
*i = I32((m["@value"]).(float64))
return nil
}
type I64 int64
func (I64) literal() {}
func (I I64) MarshalJSON() ([]byte, error) {
ret := map[string]interface{}{
"@type": "xsd:long",
"@value": int64(I),
}
return json.Marshal(ret)
}
func (i *I64) UnmarshalJSON(b []byte) error {
var m map[string]interface{}
if err := json.Unmarshal(b, &m); err != nil {
return err
}
*i = I64((m["@value"]).(float64))
return nil
}
type U uint
func (U) literal() {}
func (U U) MarshalJSON() ([]byte, error) {
ret := map[string]interface{}{
"@type": "unsignedLong",
"@value": uint(U),
}
return json.Marshal(ret)
}
type U8 uint8
func (U8) literal() {}
func (U U8) MarshalJSON() ([]byte, error) {
ret := map[string]interface{}{
"@type": "unsignedByte",
"@value": uint8(U),
}
return json.Marshal(ret)
}
type U16 uint16
func (U16) literal() {}
func (U U16) MarshalJSON() ([]byte, error) {
ret := map[string]interface{}{
"@type": "unsignedShort",
"@value": uint16(U),
}
return json.Marshal(ret)
}
type U32 uint32
func (U32) literal() {}
func (U U32) MarshalJSON() ([]byte, error) {
ret := map[string]interface{}{
"@type": "unsignedInt",
"@value": uint32(U),
}
return json.Marshal(ret)
}
type U64 uint64
func (U64) literal() {}
func (U U64) MarshalJSON() ([]byte, error) {
ret := map[string]interface{}{
"@type": "unsignedLong",
"@value": uint64(U),
}
return json.Marshal(ret)
}
func (B) isObj() {}
func (S) isObj() {}
func (Time) isObj() {}
func (F32) isObj() {}
func (F64) isObj() {}
func (I) isObj() {}
func (I8) isObj() {}
func (I16) isObj() {}
func (I32) isObj() {}
func (I64) isObj() {}
func (U) isObj() {}
func (U8) isObj() {}
func (U16) isObj() {}
func (U32) isObj() {}
func (U64) isObj() {}
// Note: if we start adding lots more literals, reserve numbers 128 and greater.
// Right now, ToBytes and FromBytes use a single byte at the start of the value
// to denote the type - if we grow to 128, we can use first column as a marker to
// signify that the type is now two bytes.
const (
bID = iota + 1 // reserve 0 for some future use.
sID
f32ID
f64ID
iID
i8ID
i16ID
i32ID
i64ID
uID
u8ID
u16ID
u32ID
u64ID
)
// ToBytes converts a literal into a typed byte slice representation.
func ToBytes(l Literal) []byte {
switch l := l.(type) {
case B:
if l {
return []byte{bID, 1}
}
return []byte{bID, 0}
case S:
return append([]byte{sID}, l[:]...)
case F32:
ret := make([]byte, 5)
ret[0] = f32ID
binary.BigEndian.PutUint32(ret[1:], math.Float32bits(float32(l)))
return ret
case F64:
ret := make([]byte, 9)
ret[0] = f64ID
binary.BigEndian.PutUint64(ret[1:], math.Float64bits(float64(l)))
return ret
case I:
ret := make([]byte, 9)
ret[0] = iID
binary.BigEndian.PutUint64(ret[1:], uint64(l))
return ret
case I8:
return []byte{i8ID, byte(l)}
case I16:
ret := make([]byte, 3)
ret[0] = i16ID
binary.BigEndian.PutUint16(ret[1:], uint16(l))
return ret
case I32:
ret := make([]byte, 5)
ret[0] = i32ID
binary.BigEndian.PutUint32(ret[1:], uint32(l))
return ret
case I64:
ret := make([]byte, 9)
ret[0] = i64ID
binary.BigEndian.PutUint64(ret[1:], uint64(l))
return ret
case U:
ret := make([]byte, 9)
ret[0] = uID
binary.BigEndian.PutUint64(ret[1:], uint64(l))
return ret
case U8:
return []byte{u8ID, byte(l)}
case U16:
ret := make([]byte, 3)
ret[0] = u16ID
binary.BigEndian.PutUint16(ret[1:], uint16(l))
return ret
case U32:
ret := make([]byte, 5)
ret[0] = u32ID
binary.BigEndian.PutUint32(ret[1:], uint32(l))
return ret
case U64:
ret := make([]byte, 9)
ret[0] = u64ID
binary.BigEndian.PutUint64(ret[1:], uint64(l))
return ret
default:
panic("should have covered all literal types in ToBytes switch")
}
}
// ToString converts a Literal into a string with a type byte prepended.
func ToString(l Literal) string {
return string(ToBytes(l))
}
// FromString converts a Literal encoded with ToString back to a Literal.
func FromString(s string) Literal {
return FromBytes([]byte(s))
}
// FromBytes converts an encoded byte slice (from ToBytes) back to a Literal.
// DEV: May add an error and bounds checking.
func FromBytes(bs []byte) Literal {
// if len(bs) < 2 {
// return nil, errors.Errorf("byte slice too short: %x", bs)
// }
switch bs[0] {
case bID:
return B(bs[1] > 0)
case sID:
return S(string(bs[1:]))
case f32ID:
return F32(math.Float32frombits(binary.BigEndian.Uint32(bs[1:])))
case f64ID:
return F64(math.Float64frombits(binary.BigEndian.Uint64(bs[1:])))
case iID:
return I(binary.BigEndian.Uint64(bs[1:]))
case i8ID:
return I8(bs[1])
case i16ID:
return I16(binary.BigEndian.Uint16(bs[1:]))
case i32ID:
return I32(binary.BigEndian.Uint32(bs[1:]))
case i64ID:
return I64(binary.BigEndian.Uint64(bs[1:]))
case uID:
return U(binary.BigEndian.Uint64(bs[1:]))
case u8ID:
return U8(bs[1])
case u16ID:
return U16(binary.BigEndian.Uint16(bs[1:]))
case u32ID:
return U32(binary.BigEndian.Uint32(bs[1:]))
case u64ID:
return U64(binary.BigEndian.Uint64(bs[1:]))
default:
panic("should have covered all literal types in FromBytes switch")
}
}