aboutsummaryrefslogtreecommitdiffhomepage
path: root/Firestore/core/src/firebase/firestore/remote/serializer.cc
blob: fc8b312505fafbdaf29ecb752c4eca61a3b16305 (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
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
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
/*
 * Copyright 2018 Google
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "Firestore/core/src/firebase/firestore/remote/serializer.h"

#include <pb_decode.h>
#include <pb_encode.h>

#include <functional>
#include <map>
#include <string>
#include <utility>

#include "Firestore/Protos/nanopb/google/firestore/v1beta1/document.nanopb.h"
#include "Firestore/Protos/nanopb/google/firestore/v1beta1/firestore.nanopb.h"
#include "Firestore/core/include/firebase/firestore/firestore_errors.h"
#include "Firestore/core/include/firebase/firestore/timestamp.h"
#include "Firestore/core/src/firebase/firestore/model/document.h"
#include "Firestore/core/src/firebase/firestore/model/no_document.h"
#include "Firestore/core/src/firebase/firestore/model/resource_path.h"
#include "Firestore/core/src/firebase/firestore/model/snapshot_version.h"
#include "Firestore/core/src/firebase/firestore/nanopb/reader.h"
#include "Firestore/core/src/firebase/firestore/nanopb/tag.h"
#include "Firestore/core/src/firebase/firestore/nanopb/writer.h"
#include "Firestore/core/src/firebase/firestore/timestamp_internal.h"
#include "Firestore/core/src/firebase/firestore/util/hard_assert.h"
#include "absl/memory/memory.h"

namespace firebase {
namespace firestore {
namespace remote {

using firebase::Timestamp;
using firebase::TimestampInternal;
using firebase::firestore::model::DatabaseId;
using firebase::firestore::model::Document;
using firebase::firestore::model::DocumentKey;
using firebase::firestore::model::FieldValue;
using firebase::firestore::model::MaybeDocument;
using firebase::firestore::model::NoDocument;
using firebase::firestore::model::ObjectValue;
using firebase::firestore::model::ResourcePath;
using firebase::firestore::model::SnapshotVersion;
using firebase::firestore::nanopb::Reader;
using firebase::firestore::nanopb::Tag;
using firebase::firestore::nanopb::Writer;
using firebase::firestore::util::Status;
using firebase::firestore::util::StatusOr;

namespace {

void EncodeMapValue(Writer* writer, const ObjectValue& object_value);
void EncodeObjectMapImpl(Writer* writer,
                         const ObjectValue::Map& object_value_map,
                         uint32_t map_tag,
                         uint32_t key_tag,
                         uint32_t value_tag);

ObjectValue::Map DecodeMapValue(Reader* reader);

void EncodeTimestamp(Writer* writer, const Timestamp& timestamp_value) {
  google_protobuf_Timestamp timestamp_proto =
      google_protobuf_Timestamp_init_zero;
  timestamp_proto.seconds = timestamp_value.seconds();
  timestamp_proto.nanos = timestamp_value.nanoseconds();
  writer->WriteNanopbMessage(google_protobuf_Timestamp_fields,
                             &timestamp_proto);
}

Timestamp DecodeTimestamp(Reader* reader) {
  if (!reader->status().ok()) return {};

  google_protobuf_Timestamp timestamp_proto =
      google_protobuf_Timestamp_init_zero;
  reader->ReadNanopbMessage(google_protobuf_Timestamp_fields, &timestamp_proto);

  // The Timestamp ctor will assert if we provide values outside the valid
  // range. However, since we're decoding, a single corrupt byte could cause
  // this to occur, so we'll verify the ranges before passing them in since we'd
  // rather not abort in these situations.
  if (timestamp_proto.seconds < TimestampInternal::Min().seconds()) {
    reader->set_status(Status(
        FirestoreErrorCode::DataLoss,
        "Invalid message: timestamp beyond the earliest supported date"));
    return {};
  } else if (TimestampInternal::Max().seconds() < timestamp_proto.seconds) {
    reader->set_status(
        Status(FirestoreErrorCode::DataLoss,
               "Invalid message: timestamp behond the latest supported date"));
    return {};
  } else if (timestamp_proto.nanos < 0 || timestamp_proto.nanos > 999999999) {
    reader->set_status(Status(
        FirestoreErrorCode::DataLoss,
        "Invalid message: timestamp nanos must be between 0 and 999999999"));
    return {};
  }
  return Timestamp{timestamp_proto.seconds, timestamp_proto.nanos};
}

// Named '..Impl' so as to not conflict with Serializer::EncodeFieldValue.
// TODO(rsgowman): Refactor to use a helper class that wraps the stream struct.
// This will help with error handling, and should eliminate the issue of two
// 'EncodeFieldValue' methods.
void EncodeFieldValueImpl(Writer* writer, const FieldValue& field_value) {
  // TODO(rsgowman): some refactoring is in order... but will wait until after a
  // non-varint, non-fixed-size (i.e. string) type is present before doing so.
  switch (field_value.type()) {
    case FieldValue::Type::Null:
      writer->WriteTag(
          {PB_WT_VARINT, google_firestore_v1beta1_Value_null_value_tag});
      writer->WriteNull();
      break;

    case FieldValue::Type::Boolean:
      writer->WriteTag(
          {PB_WT_VARINT, google_firestore_v1beta1_Value_boolean_value_tag});
      writer->WriteBool(field_value.boolean_value());
      break;

    case FieldValue::Type::Integer:
      writer->WriteTag(
          {PB_WT_VARINT, google_firestore_v1beta1_Value_integer_value_tag});
      writer->WriteInteger(field_value.integer_value());
      break;

    case FieldValue::Type::String:
      writer->WriteTag(
          {PB_WT_STRING, google_firestore_v1beta1_Value_string_value_tag});
      writer->WriteString(field_value.string_value());
      break;

    case FieldValue::Type::Timestamp:
      writer->WriteTag(
          {PB_WT_STRING, google_firestore_v1beta1_Value_timestamp_value_tag});
      writer->WriteNestedMessage([&field_value](Writer* writer) {
        EncodeTimestamp(writer, field_value.timestamp_value());
      });
      break;

    case FieldValue::Type::Object:
      writer->WriteTag(
          {PB_WT_STRING, google_firestore_v1beta1_Value_map_value_tag});
      writer->WriteNestedMessage([&field_value](Writer* writer) {
        EncodeMapValue(writer, field_value.object_value());
      });
      break;

    default:
      // TODO(rsgowman): implement the other types
      abort();
  }
}

FieldValue DecodeFieldValueImpl(Reader* reader) {
  if (!reader->status().ok()) return FieldValue::NullValue();

  // There needs to be at least one entry in the FieldValue.
  if (reader->bytes_left() == 0) {
    reader->set_status(Status(FirestoreErrorCode::DataLoss,
                              "Input Value proto missing contents"));
    return FieldValue::NullValue();
  }

  FieldValue result = FieldValue::NullValue();

  while (reader->bytes_left()) {
    Tag tag = reader->ReadTag();
    if (!reader->status().ok()) return FieldValue::NullValue();

    // Ensure the tag matches the wire type
    switch (tag.field_number) {
      case google_firestore_v1beta1_Value_null_value_tag:
      case google_firestore_v1beta1_Value_boolean_value_tag:
      case google_firestore_v1beta1_Value_integer_value_tag:
        if (tag.wire_type != PB_WT_VARINT) {
          reader->set_status(
              Status(FirestoreErrorCode::DataLoss,
                     "Input proto bytes cannot be parsed (mismatch between "
                     "the wiretype and the field number (tag))"));
        }
        break;

      case google_firestore_v1beta1_Value_string_value_tag:
      case google_firestore_v1beta1_Value_timestamp_value_tag:
      case google_firestore_v1beta1_Value_map_value_tag:
        if (tag.wire_type != PB_WT_STRING) {
          reader->set_status(
              Status(FirestoreErrorCode::DataLoss,
                     "Input proto bytes cannot be parsed (mismatch between "
                     "the wiretype and the field number (tag))"));
        }
        break;

      case google_firestore_v1beta1_Value_double_value_tag:
      case google_firestore_v1beta1_Value_bytes_value_tag:
      case google_firestore_v1beta1_Value_reference_value_tag:
      case google_firestore_v1beta1_Value_geo_point_value_tag:
      case google_firestore_v1beta1_Value_array_value_tag:
        // TODO(b/74243929): Implement remaining types.
        HARD_FAIL("Unhandled message field number (tag): %i.",
                  tag.field_number);

      default:
        // Unknown tag. According to the proto spec, we need to ignore these. No
        // action required here, though we'll need to skip the relevant bytes
        // below.
        break;
    }

    if (!reader->status().ok()) return FieldValue::NullValue();

    switch (tag.field_number) {
      case google_firestore_v1beta1_Value_null_value_tag:
        reader->ReadNull();
        result = FieldValue::NullValue();
        break;
      case google_firestore_v1beta1_Value_boolean_value_tag:
        result = FieldValue::BooleanValue(reader->ReadBool());
        break;
      case google_firestore_v1beta1_Value_integer_value_tag:
        result = FieldValue::IntegerValue(reader->ReadInteger());
        break;
      case google_firestore_v1beta1_Value_string_value_tag:
        result = FieldValue::StringValue(reader->ReadString());
        break;
      case google_firestore_v1beta1_Value_timestamp_value_tag:
        result = FieldValue::TimestampValue(
            reader->ReadNestedMessage<Timestamp>(DecodeTimestamp));
        break;
      case google_firestore_v1beta1_Value_map_value_tag:
        // TODO(rsgowman): We should merge the existing map (if any) with the
        // newly parsed map.
        result = FieldValue::ObjectValueFromMap(
            reader->ReadNestedMessage<ObjectValue::Map>(DecodeMapValue));
        break;

      case google_firestore_v1beta1_Value_double_value_tag:
      case google_firestore_v1beta1_Value_bytes_value_tag:
      case google_firestore_v1beta1_Value_reference_value_tag:
      case google_firestore_v1beta1_Value_geo_point_value_tag:
      case google_firestore_v1beta1_Value_array_value_tag:
        // TODO(b/74243929): Implement remaining types.
        HARD_FAIL("Unhandled message field number (tag): %i.",
                  tag.field_number);

      default:
        // Unknown tag. According to the proto spec, we need to ignore these.
        reader->SkipField(tag);
    }
  }

  return result;
}

/**
 * Encodes a 'FieldsEntry' object, within a FieldValue's map_value type.
 *
 * In protobuf, maps are implemented as a repeated set of key/values. For
 * instance, this:
 *   message Foo {
 *     map<string, Value> fields = 1;
 *   }
 * would be written (in proto text format) as:
 *   {
 *     fields: {key:"key string 1", value:{<Value message here>}}
 *     fields: {key:"key string 2", value:{<Value message here>}}
 *     ...
 *   }
 *
 * This method writes an individual entry from that list. It is expected that
 * this method will be called once for each entry in the map.
 *
 * @param kv The individual key/value pair to write.
 */
void EncodeFieldsEntry(Writer* writer,
                       const ObjectValue::Map::value_type& kv,
                       uint32_t key_tag,
                       uint32_t value_tag) {
  // Write the key (string)
  writer->WriteTag({PB_WT_STRING, key_tag});
  writer->WriteString(kv.first);

  // Write the value (FieldValue)
  writer->WriteTag({PB_WT_STRING, value_tag});
  writer->WriteNestedMessage(
      [&kv](Writer* writer) { EncodeFieldValueImpl(writer, kv.second); });
}

ObjectValue::Map::value_type DecodeFieldsEntry(Reader* reader,
                                               uint32_t key_tag,
                                               uint32_t value_tag) {
  if (!reader->status().ok()) return {};

  Tag tag = reader->ReadTag();
  if (!reader->status().ok()) return {};

  // TODO(rsgowman): figure out error handling: We can do better than a failed
  // assertion.
  HARD_ASSERT(tag.field_number == key_tag);
  HARD_ASSERT(tag.wire_type == PB_WT_STRING);
  std::string key = reader->ReadString();

  tag = reader->ReadTag();
  if (!reader->status().ok()) return {};
  HARD_ASSERT(tag.field_number == value_tag);
  HARD_ASSERT(tag.wire_type == PB_WT_STRING);

  FieldValue value =
      reader->ReadNestedMessage<FieldValue>(DecodeFieldValueImpl);

  return ObjectValue::Map::value_type{key, value};
}

ObjectValue::Map::value_type DecodeMapValueFieldsEntry(Reader* reader) {
  return DecodeFieldsEntry(
      reader, google_firestore_v1beta1_MapValue_FieldsEntry_key_tag,
      google_firestore_v1beta1_MapValue_FieldsEntry_value_tag);
}

ObjectValue::Map::value_type DecodeDocumentFieldsEntry(Reader* reader) {
  return DecodeFieldsEntry(
      reader, google_firestore_v1beta1_Document_FieldsEntry_key_tag,
      google_firestore_v1beta1_Document_FieldsEntry_value_tag);
}

void EncodeObjectMapImpl(Writer* writer,
                         const ObjectValue::Map& object_value_map,
                         uint32_t map_tag,
                         uint32_t key_tag,
                         uint32_t value_tag) {
  // Write each FieldsEntry (i.e. key-value pair.)
  for (const auto& kv : object_value_map) {
    writer->WriteTag({PB_WT_STRING, map_tag});
    writer->WriteNestedMessage([&kv, &key_tag, &value_tag](Writer* writer) {
      return EncodeFieldsEntry(writer, kv, key_tag, value_tag);
    });
  }
}

void EncodeMapValue(Writer* writer, const ObjectValue& object_value) {
  EncodeObjectMapImpl(writer, object_value.internal_value,
                      google_firestore_v1beta1_MapValue_fields_tag,
                      google_firestore_v1beta1_MapValue_FieldsEntry_key_tag,
                      google_firestore_v1beta1_MapValue_FieldsEntry_value_tag);
}

ObjectValue::Map DecodeMapValue(Reader* reader) {
  ObjectValue::Map result;
  if (!reader->status().ok()) return result;

  while (reader->bytes_left()) {
    Tag tag = reader->ReadTag();
    if (!reader->status().ok()) return result;
    // The MapValue message only has a single valid tag.
    // TODO(rsgowman): figure out error handling: We can do better than a
    // failed assertion.
    HARD_ASSERT(tag.field_number ==
                google_firestore_v1beta1_MapValue_fields_tag);
    HARD_ASSERT(tag.wire_type == PB_WT_STRING);

    ObjectValue::Map::value_type fv =
        reader->ReadNestedMessage<ObjectValue::Map::value_type>(
            DecodeMapValueFieldsEntry);

    if (!reader->status().ok()) return result;

    // Assumption: If we parse two entries for the map that have the same key,
    // then the latter should overwrite the former. This does not appear to be
    // explicitly called out by the docs, but seems to be in the spirit of how
    // things work. (i.e. non-repeated fields explicitly follow this behaviour.)
    // In any case, well behaved proto emitters shouldn't create encodings like
    // this, but well behaved parsers are expected to handle these cases.
    //
    // https://developers.google.com/protocol-buffers/docs/encoding#optional

    // Add this key,fieldvalue to the results map.
    result[fv.first] = fv.second;
  }
  return result;
}

/**
 * Creates the prefix for a fully qualified resource path, without a local path
 * on the end.
 */
ResourcePath EncodeDatabaseId(const DatabaseId& database_id) {
  return ResourcePath{"projects", database_id.project_id(), "databases",
                      database_id.database_id()};
}

/**
 * Encodes a databaseId and resource path into the following form:
 * /projects/$projectId/database/$databaseId/documents/$path
 */
std::string EncodeResourceName(const DatabaseId& database_id,
                               const ResourcePath& path) {
  return EncodeDatabaseId(database_id)
      .Append("documents")
      .Append(path)
      .CanonicalString();
}

/**
 * Validates that a path has a prefix that looks like a valid encoded
 * databaseId.
 */
bool IsValidResourceName(const ResourcePath& path) {
  // Resource names have at least 4 components (project ID, database ID)
  // and commonly the (root) resource type, e.g. documents
  return path.size() >= 4 && path[0] == "projects" && path[2] == "databases";
}

/**
 * Decodes a fully qualified resource name into a resource path and validates
 * that there is a project and database encoded in the path. There are no
 * guarantees that a local path is also encoded in this resource name.
 */
ResourcePath DecodeResourceName(absl::string_view encoded) {
  ResourcePath resource = ResourcePath::FromString(encoded);
  HARD_ASSERT(IsValidResourceName(resource),
              "Tried to deserialize invalid key %s",
              resource.CanonicalString());
  return resource;
}

/**
 * Decodes a fully qualified resource name into a resource path and validates
 * that there is a project and database encoded in the path along with a local
 * path.
 */
ResourcePath ExtractLocalPathFromResourceName(
    const ResourcePath& resource_name) {
  HARD_ASSERT(resource_name.size() > 4 && resource_name[4] == "documents",
              "Tried to deserialize invalid key %s",
              resource_name.CanonicalString());
  return resource_name.PopFirst(5);
}

}  // namespace

Status Serializer::EncodeFieldValue(const FieldValue& field_value,
                                    std::vector<uint8_t>* out_bytes) {
  Writer writer = Writer::Wrap(out_bytes);
  EncodeFieldValueImpl(&writer, field_value);
  return writer.status();
}

StatusOr<FieldValue> Serializer::DecodeFieldValue(const uint8_t* bytes,
                                                  size_t length) {
  Reader reader = Reader::Wrap(bytes, length);
  FieldValue fv = DecodeFieldValueImpl(&reader);
  if (reader.status().ok()) {
    return fv;
  } else {
    return reader.status();
  }
}

std::string Serializer::EncodeKey(const DocumentKey& key) const {
  return EncodeResourceName(database_id_, key.path());
}

DocumentKey Serializer::DecodeKey(absl::string_view name) const {
  ResourcePath resource = DecodeResourceName(name);
  HARD_ASSERT(resource[1] == database_id_.project_id(),
              "Tried to deserialize key from different project.");
  HARD_ASSERT(resource[3] == database_id_.database_id(),
              "Tried to deserialize key from different database.");
  return DocumentKey{ExtractLocalPathFromResourceName(resource)};
}

util::Status Serializer::EncodeDocument(const DocumentKey& key,
                                        const ObjectValue& value,
                                        std::vector<uint8_t>* out_bytes) const {
  Writer writer = Writer::Wrap(out_bytes);
  EncodeDocument(&writer, key, value);
  return writer.status();
}

void Serializer::EncodeDocument(Writer* writer,
                                const DocumentKey& key,
                                const ObjectValue& object_value) const {
  // Encode Document.name
  writer->WriteTag({PB_WT_STRING, google_firestore_v1beta1_Document_name_tag});
  writer->WriteString(EncodeKey(key));

  // Encode Document.fields (unless it's empty)
  if (!object_value.internal_value.empty()) {
    EncodeObjectMapImpl(
        writer, object_value.internal_value,
        google_firestore_v1beta1_Document_fields_tag,
        google_firestore_v1beta1_Document_FieldsEntry_key_tag,
        google_firestore_v1beta1_Document_FieldsEntry_value_tag);
  }

  // Skip Document.create_time and Document.update_time, since they're
  // output-only fields.
}

util::StatusOr<std::unique_ptr<model::MaybeDocument>>
Serializer::DecodeMaybeDocument(const uint8_t* bytes, size_t length) const {
  Reader reader = Reader::Wrap(bytes, length);
  std::unique_ptr<MaybeDocument> maybeDoc =
      DecodeBatchGetDocumentsResponse(&reader);

  if (reader.status().ok()) {
    return std::move(maybeDoc);
  } else {
    return reader.status();
  }
}

std::unique_ptr<MaybeDocument> Serializer::DecodeBatchGetDocumentsResponse(
    Reader* reader) const {
  if (!reader->status().ok()) return nullptr;

  // Initialize BatchGetDocumentsResponse fields to their default values
  std::unique_ptr<MaybeDocument> found;
  std::string missing;
  // We explicitly ignore the 'transaction' field
  SnapshotVersion read_time = SnapshotVersion::None();

  while (reader->bytes_left()) {
    Tag tag = reader->ReadTag();
    if (!reader->status().ok()) return nullptr;

    // Ensure the tag matches the wire type
    switch (tag.field_number) {
      case google_firestore_v1beta1_BatchGetDocumentsResponse_found_tag:
      case google_firestore_v1beta1_BatchGetDocumentsResponse_missing_tag:
      case google_firestore_v1beta1_BatchGetDocumentsResponse_transaction_tag:
      case google_firestore_v1beta1_BatchGetDocumentsResponse_read_time_tag:
        if (tag.wire_type != PB_WT_STRING) {
          reader->set_status(
              Status(FirestoreErrorCode::DataLoss,
                     "Input proto bytes cannot be parsed (mismatch between "
                     "the wiretype and the field number (tag))"));
        }
        break;

      default:
        // Unknown tag. According to the proto spec, we need to ignore these. No
        // action required here, though we'll need to skip the relevant bytes
        // below.
        break;
    }

    if (!reader->status().ok()) return nullptr;

    switch (tag.field_number) {
      case google_firestore_v1beta1_BatchGetDocumentsResponse_found_tag:
        // 'found' and 'missing' are part of a oneof. The proto docs claim that
        // if both are set on the wire, the last one wins.
        missing = "";

        // TODO(rsgowman): If multiple 'found' values are found, we should merge
        // them (rather than using the last one.)
        found = reader->ReadNestedMessage<std::unique_ptr<MaybeDocument>>(
            [this](Reader* reader) -> std::unique_ptr<MaybeDocument> {
              return DecodeDocument(reader);
            });
        break;

      case google_firestore_v1beta1_BatchGetDocumentsResponse_missing_tag:
        // 'found' and 'missing' are part of a oneof. The proto docs claim that
        // if both are set on the wire, the last one wins.
        found = nullptr;

        missing = reader->ReadString();
        break;

      case google_firestore_v1beta1_BatchGetDocumentsResponse_transaction_tag:
        // This field is ignored by the client sdk, but we still need to extract
        // it.
        // TODO(rsgowman) switch this to reader->SkipField() (or whatever we end
        // up calling it) once that exists. Possibly group this with other
        // ignored and/or unknown fields
        reader->ReadString();
        break;

      case google_firestore_v1beta1_BatchGetDocumentsResponse_read_time_tag:
        read_time = SnapshotVersion{
            reader->ReadNestedMessage<Timestamp>(DecodeTimestamp)};
        break;

      default:
        // Unknown tag. According to the proto spec, we need to ignore these.
        reader->SkipField(tag);
    }
  }

  if (found != nullptr) {
    return found;
  } else if (!missing.empty()) {
    return absl::make_unique<NoDocument>(DecodeKey(missing), read_time);
  } else {
    reader->set_status(Status(FirestoreErrorCode::DataLoss,
                              "Invalid BatchGetDocumentsReponse message: "
                              "Neither 'found' nor 'missing' fields set."));
    return nullptr;
  }
}

std::unique_ptr<Document> Serializer::DecodeDocument(Reader* reader) const {
  if (!reader->status().ok()) return nullptr;

  std::string name;
  ObjectValue::Map fields_internal;
  SnapshotVersion version = SnapshotVersion::None();

  while (reader->bytes_left()) {
    Tag tag = reader->ReadTag();
    if (!reader->status().ok()) return nullptr;
    HARD_ASSERT(tag.wire_type == PB_WT_STRING);
    switch (tag.field_number) {
      case google_firestore_v1beta1_Document_name_tag:
        name = reader->ReadString();
        break;
      case google_firestore_v1beta1_Document_fields_tag: {
        ObjectValue::Map::value_type fv =
            reader->ReadNestedMessage<ObjectValue::Map::value_type>(
                DecodeDocumentFieldsEntry);

        if (!reader->status().ok()) return nullptr;

        // Assumption: For duplicates, the latter overrides the former, see
        // comment on writing object map for details (DecodeMapValue).

        // Add fieldvalue to the results map.
        fields_internal[fv.first] = fv.second;
        break;
      }
      case google_firestore_v1beta1_Document_create_time_tag:
        // This field is ignored by the client sdk, but we still need to extract
        // it.
        reader->ReadNestedMessage<Timestamp>(DecodeTimestamp);
        break;
      case google_firestore_v1beta1_Document_update_time_tag:
        // TODO(rsgowman): Rather than overwriting, we should instead merge with
        // the existing SnapshotVersion (if any). Less relevant here, since it's
        // just two numbers which are both expected to be present, but if the
        // proto evolves that might change.
        version = SnapshotVersion{
            reader->ReadNestedMessage<Timestamp>(DecodeTimestamp)};
        break;
      default:
        // TODO(rsgowman): Error handling. (Invalid tags should fail to decode,
        // but shouldn't cause a crash.)
        abort();
    }
  }

  return absl::make_unique<Document>(
      FieldValue::ObjectValueFromMap(fields_internal), DecodeKey(name), version,
      /*has_local_modifications=*/false);
}

void Serializer::EncodeObjectMap(
    nanopb::Writer* writer,
    const model::ObjectValue::Map& object_value_map,
    uint32_t map_tag,
    uint32_t key_tag,
    uint32_t value_tag) {
  // TODO(rsgowman): Move the implementation of EncodeObjectMapImpl here and
  // eliminate that function. The only reason I'm (temporarily) keeping it, is
  // that performing that refactoring now will cause a cascade of things that
  // need to move into the local serializer class (as private functions).
  EncodeObjectMapImpl(writer, object_value_map, map_tag, key_tag, value_tag);
}

void Serializer::EncodeVersion(nanopb::Writer* writer,
                               const model::SnapshotVersion& version) {
  EncodeTimestamp(writer, version.timestamp());
}

}  // namespace remote
}  // namespace firestore
}  // namespace firebase