aboutsummaryrefslogtreecommitdiffstats
path: root/document/src/main/java/com/yahoo/document/json/DocumentUpdateJsonSerializer.java
blob: a2864d12dd6715fc5f1ecbe8bc5f01457ab2859d (plain) (blame)
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
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.document.json;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonFactoryBuilder;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.StreamReadConstraints;
import com.yahoo.document.DataType;
import com.yahoo.document.Document;
import com.yahoo.document.DocumentUpdate;
import com.yahoo.document.FieldPath;
import com.yahoo.document.WeightedSetDataType;
import com.yahoo.document.annotation.AnnotationReference;
import com.yahoo.document.datatypes.Array;
import com.yahoo.document.datatypes.BoolFieldValue;
import com.yahoo.document.datatypes.ByteFieldValue;
import com.yahoo.document.datatypes.CollectionFieldValue;
import com.yahoo.document.datatypes.DoubleFieldValue;
import com.yahoo.document.datatypes.FieldValue;
import com.yahoo.document.datatypes.FloatFieldValue;
import com.yahoo.document.datatypes.IntegerFieldValue;
import com.yahoo.document.datatypes.LongFieldValue;
import com.yahoo.document.datatypes.MapFieldValue;
import com.yahoo.document.datatypes.PredicateFieldValue;
import com.yahoo.document.datatypes.Raw;
import com.yahoo.document.datatypes.ReferenceFieldValue;
import com.yahoo.document.datatypes.StringFieldValue;
import com.yahoo.document.datatypes.Struct;
import com.yahoo.document.datatypes.StructuredFieldValue;
import com.yahoo.document.datatypes.TensorFieldValue;
import com.yahoo.document.datatypes.WeightedSet;
import com.yahoo.document.fieldpathupdate.AddFieldPathUpdate;
import com.yahoo.document.fieldpathupdate.AssignFieldPathUpdate;
import com.yahoo.document.fieldpathupdate.FieldPathUpdate;
import com.yahoo.document.fieldpathupdate.RemoveFieldPathUpdate;
import com.yahoo.document.json.readers.SingleValueReader;
import com.yahoo.document.serialization.DocumentUpdateWriter;
import com.yahoo.document.serialization.FieldWriter;
import com.yahoo.document.update.AddValueUpdate;
import com.yahoo.document.update.ArithmeticValueUpdate;
import com.yahoo.document.update.AssignValueUpdate;
import com.yahoo.document.update.ClearValueUpdate;
import com.yahoo.document.update.FieldUpdate;
import com.yahoo.document.update.MapValueUpdate;
import com.yahoo.document.update.RemoveValueUpdate;
import com.yahoo.document.update.TensorAddUpdate;
import com.yahoo.document.update.TensorModifyUpdate;
import com.yahoo.document.update.TensorRemoveUpdate;
import com.yahoo.document.update.ValueUpdate;
import com.yahoo.vespa.objects.FieldBase;
import com.yahoo.vespa.objects.Serializer;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.stream.Collectors;

import static com.yahoo.document.json.JsonSerializationHelper.*;

/**
 * The DocumentUpdateJsonSerializer utility class is used to serialize a DocumentUpdate instance using the JSON format described in
 * <a href="https://docs.vespa.ai/en/reference/document-json-format.html#update">Document JSON Format: The Update Structure</a>
 *
 * @see #serialize(com.yahoo.document.DocumentUpdate)
 * @author Vegard Sjonfjell
 */
public class DocumentUpdateJsonSerializer {

    private static final JsonFactory jsonFactory = new JsonFactoryBuilder()
            .streamReadConstraints(StreamReadConstraints.builder().maxStringLength(Integer.MAX_VALUE).build())
            .build();
    private final JsonDocumentUpdateWriter writer = new JsonDocumentUpdateWriter();
    private JsonGenerator generator;

    /**
     * Instantiate a DocumentUpdateJsonSerializer that outputs JSON to an OutputStream
     */
    public DocumentUpdateJsonSerializer(OutputStream outputStream) {
        wrapIOException(() -> generator = jsonFactory.createGenerator(outputStream));
    }

    /**
     * Instantiate a DocumentUpdateJsonSerializer that writes JSON using existing JsonGenerator
     */
    public DocumentUpdateJsonSerializer(JsonGenerator generator) {
        this.generator = generator;
    }

    /**
     * Serialize a DocumentUpdate tree to JSON
     */
    public void serialize(DocumentUpdate update) {
        writer.write(update);
    }

    private class JsonDocumentUpdateWriter implements DocumentUpdateWriter, FieldWriter {
        @Override
        public void write(DocumentUpdate update) {
            wrapIOException(() -> {
                generator.writeStartObject();
                generator.writeStringField("update", update.getId().toString());

                if (update.getCondition().isPresent()) {
                    generator.writeStringField("condition", update.getCondition().getSelection());
                }

                Optional<Boolean> createIfNotExistent = update.getOptionalCreateIfNonExistent();
                if (createIfNotExistent.isPresent() && createIfNotExistent.get()) {
                    generator.writeBooleanField("create", createIfNotExistent.get());
                }

                generator.writeObjectFieldStart("fields");
                for (FieldUpdate up : update.fieldUpdates()) {
                    up.serialize(this);
                }

                update.fieldPathUpdates().stream()
                        .collect(Collectors.groupingBy(FieldPathUpdate::getFieldPath))
                        .forEach((fieldPath, fieldPathUpdates) ->
                                wrapIOException(() -> write(fieldPath, fieldPathUpdates, generator)));
                generator.writeEndObject();

                generator.writeEndObject();
                generator.flush();
            });
        }

        private void write(FieldPath fieldPath, Collection<FieldPathUpdate> fieldPathUpdates, JsonGenerator generator) throws IOException {
            generator.writeObjectFieldStart(fieldPath.toString());

            for (FieldPathUpdate update : fieldPathUpdates) {
                if (writeArithmeticFieldPathUpdate(update, generator)) continue;
                generator.writeFieldName(update.getUpdateType().name().toLowerCase());

                if (update instanceof AssignFieldPathUpdate assignUp) {
                    if (assignUp.getExpression() != null) {
                        throw new RuntimeException("Unable to parse expression: " + assignUp.getExpression());
                    } else {
                        assignUp.getNewValue().serialize(null, this);
                    }
                } else if (update instanceof AddFieldPathUpdate) {
                    ((AddFieldPathUpdate) update).getNewValues().serialize(null, this);
                } else if (update instanceof RemoveFieldPathUpdate) {
                    generator.writeNumber(0);
                } else {
                    throw new RuntimeException("Unsupported fieldpath operation: " + update.getClass().getName());
                }
            }
            generator.writeEndObject();
        }

        // Returns true if fieldpath update was an arithmetic operation after writing it to the generator
        private boolean writeArithmeticFieldPathUpdate(FieldPathUpdate fieldPathUpdate, JsonGenerator generator) throws IOException {
            if (! (fieldPathUpdate instanceof AssignFieldPathUpdate)) return false;
            String expression = ((AssignFieldPathUpdate) fieldPathUpdate).getExpression();
            if (expression == null) return false;

            Matcher matcher = SingleValueReader.matchArithmeticOperation(expression);
            if (matcher.find()) {
                String updateOperation = SingleValueReader.ARITHMETIC_SIGN_TO_UPDATE_OPERATION.get(matcher.group(1));
                double value = Double.valueOf(matcher.group(2));

                generator.writeNumberField(updateOperation, value);
                return true;
            }

            return false;
        }

        @Override
        public void write(FieldUpdate fieldUpdate) {
            wrapIOException(() -> {
                generator.writeObjectFieldStart(fieldUpdate.getField().getName());

                ArrayList<ValueUpdate<?>> removeValueUpdates = new ArrayList<>();
                ArrayList<ValueUpdate<?>> addValueUpdates = new ArrayList<>();

                DataType dataType = fieldUpdate.getField().getDataType();
                for (ValueUpdate<?> valueUpdate : fieldUpdate.getValueUpdates()) {
                    if (valueUpdate instanceof RemoveValueUpdate) {
                        removeValueUpdates.add(valueUpdate);
                    } else if (valueUpdate instanceof AddValueUpdate) {
                        addValueUpdates.add(valueUpdate);
                    } else {
                        valueUpdate.serialize(this, dataType);
                    }
                }

                writeAddOrRemoveValueUpdates("remove", removeValueUpdates, dataType);
                writeAddOrRemoveValueUpdates("add", addValueUpdates, dataType);

                generator.writeEndObject();
            });
        }

        private void writeAddOrRemoveValueUpdates(String operation, ArrayList<ValueUpdate<?>> valueUpdates, DataType dataType) throws IOException {
            if (valueUpdates.isEmpty()) return;

            if (dataType instanceof WeightedSetDataType)
                writeAddOrRemoveValueUpdatesForWeightedSet(operation, valueUpdates, dataType);
            else
                writeAddOrRemoveValueUpdatesForArray(operation, valueUpdates, dataType);
        }

        private void writeAddOrRemoveValueUpdatesForArray(String operation, ArrayList<ValueUpdate<?>> valueUpdates, DataType dataType) throws IOException {
            generator.writeArrayFieldStart(operation);
            for (ValueUpdate<?> valueUpdate : valueUpdates) {
                valueUpdate.serialize(this, dataType);
            }
            generator.writeEndArray();
        }

        private void writeAddOrRemoveValueUpdatesForWeightedSet(String operation, ArrayList<ValueUpdate<?>> valueUpdates, DataType dataType) throws IOException {
            generator.writeObjectFieldStart(operation);
            for (ValueUpdate<?> valueUpdate : valueUpdates) {
                valueUpdate.serialize(this, dataType);
            }
            generator.writeEndObject();
        }

        @Override
        public void write(AddValueUpdate update, DataType superType) {
            if (superType instanceof WeightedSetDataType)
                writeWeightedSet(update);
            else
                update.getValue().serialize(this);
        }

        private void writeWeightedSet(AddValueUpdate update) {
            wrapIOException(() -> {
                generator.writeFieldName(update.getValue().toString());
                generator.writeNumber(update.getWeight());
            });
        }

        /* This is the 'match' operation */
        @Override
        public void write(MapValueUpdate update, DataType superType) {
            wrapIOException(() -> {
                generator.writeObjectFieldStart("match");
                generator.writeFieldName("element");
                update.getValue().serialize(null, this);
                update.getUpdate().serialize(this, superType);
                generator.writeEndObject();
            });
        }

        @Override
        public void write(ArithmeticValueUpdate update) {
            ArithmeticValueUpdate.Operator operator = update.getOperator();
            String operationKey = switch (operator) {
                case ADD -> "increment";
                case DIV -> "divide";
                case MUL -> "multiply";
                case SUB -> "decrement";
            };

            wrapIOException(() -> generator.writeFieldName(operationKey));
            update.getValue().serialize(this);
        }

        @Override
        public void write(AssignValueUpdate update, DataType superType) {
            wrapIOException(() -> generator.writeFieldName("assign"));
            update.getValue().serialize(null, this);
        }

        @Override
        public void write(RemoveValueUpdate update, DataType superType) {
            update.getValue().serialize(null, this);
        }

        @Override
        public void write(ClearValueUpdate clearValueUpdate, DataType superType) {
            wrapIOException(() -> generator.writeNullField("assign"));
        }

        @Override
        public void write(TensorModifyUpdate update) {
            wrapIOException(() -> {
                generator.writeObjectFieldStart("modify");
                generator.writeFieldName("operation");
                generator.writeString(update.getOperation().name);
                if (update.getValue().getTensor().isPresent()) {
                    serializeTensorCells(generator, update.getValue().getTensor().get());
                }
                generator.writeEndObject();
            });
        }

        @Override
        public void write(TensorAddUpdate update) {
            wrapIOException(() -> {
                generator.writeObjectFieldStart("add");
                if (update.getValue().getTensor().isPresent()) {
                    serializeTensorCells(generator, update.getValue().getTensor().get());
                }
                generator.writeEndObject();
            });
        }

        @Override
        public void write(TensorRemoveUpdate update) {
            wrapIOException(() -> {
                generator.writeObjectFieldStart("remove");
                if (update.getValue().getTensor().isPresent()) {
                    serializeTensorAddresses(generator, update.getValue().getTensor().get());
                }
                generator.writeEndObject();
            });
        }

        @Override
        public void write(FieldBase field, FieldValue value) {
            throw new JsonSerializationException(String.format("Serialization of field values of type %s is not supported", value.getClass().getName()));
        }

        @Override
        public void write(FieldBase field, Document value) {
            throw new JsonSerializationException("Serialization of 'Document fields' is not supported");
        }

        @Override
        public <T extends FieldValue> void write(FieldBase field, Array<T> array) {
            serializeArrayField(this, generator, field, array);
        }

        @Override
        public <K extends FieldValue, V extends FieldValue> void write(FieldBase field, MapFieldValue<K, V> map) {
            serializeMapField(this, generator, field, map);
        }

        @Override
        public void write(FieldBase field, ByteFieldValue value) {
            serializeByteField(generator, field, value);
        }

        @Override
        public void write(FieldBase field, BoolFieldValue value) {
            serializeBoolField(generator, field, value);
        }

        @Override
        public <T extends FieldValue> void write(FieldBase field, CollectionFieldValue<T> value) {
            serializeCollectionField(this, generator, field, value);
        }

        @Override
        public void write(FieldBase field, DoubleFieldValue value) {
            serializeDoubleField(generator, field, value);
        }

        @Override
        public void write(FieldBase field, FloatFieldValue value) {
            serializeFloatField(generator, field, value);
        }

        @Override
        public void write(FieldBase field, IntegerFieldValue value) {
            serializeIntField(generator, field, value);
        }

        @Override
        public void write(FieldBase field, LongFieldValue value) {
            serializeLongField(generator, field, value);
        }

        @Override
        public void write(FieldBase field, Raw value) {
            serializeRawField(generator, field, value);
        }

        @Override
        public void write(FieldBase field, PredicateFieldValue value) {
            serializePredicateField(generator, field, value);
        }

        @Override
        public void write(FieldBase field, StringFieldValue value) {
            serializeStringField(generator, field, value);
        }

        @Override
        public void write(FieldBase field, TensorFieldValue value) {
            serializeTensorField(generator, field, value, false, false);
        }

        @Override
        public void write(FieldBase field, ReferenceFieldValue value) {
            serializeReferenceField(generator, field, value);
        }

        @Override
        public void write(FieldBase field, Struct value) {
            serializeStructField(this, generator, field, value);
        }

        @Override
        public void write(FieldBase field, StructuredFieldValue value) {
            serializeStructuredField(this, generator, field, value);
        }

        @Override
        public <T extends FieldValue> void write(FieldBase field, WeightedSet<T> weightedSet) {
            serializeWeightedSet(generator, field, weightedSet);
        }

        @Override
        public void write(FieldBase field, AnnotationReference value) {
            // Serialization of annotations are not implemented
        }

        @Override
        public Serializer putByte(FieldBase field, byte value) {
            serializeByte(generator, field, value);
            return this;
        }

        @Override
        public Serializer putShort(FieldBase field, short value) {
            serializeShort(generator, field, value);
            return this;
        }

        @Override
        public Serializer putInt(FieldBase field, int value) {
            serializeInt(generator, field, value);
            return this;
        }

        @Override
        public Serializer putLong(FieldBase field, long value) {
            serializeLong(generator, field, value);
            return this;
        }

        @Override
        public Serializer putFloat(FieldBase field, float value) {
            serializeFloat(generator, field, value);
            return this;
        }

        @Override
        public Serializer putDouble(FieldBase field, double value) {
            serializeDouble(generator, field, value);
            return this;
        }

        @Override
        public Serializer put(FieldBase field, byte[] value) {
            serializeByteArray(generator, field, value);
            return this;
        }

        @Override
        public Serializer put(FieldBase field, ByteBuffer value) {
            serializeByteBuffer(generator, field, value);
            return this;
        }

        @Override
        public Serializer put(FieldBase field, String value) {
            serializeString(generator, field, value);
            return this;
        }
    }
}