Debian Codegraph @

docstore/docstore.go

raw
1 // Copyright 2019 The Go Cloud Development Kit Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package docstore
16
17 import (
18 "context"
19 "encoding/base64"
20 "fmt"
21 "log"
22 "reflect"
23 "runtime"
24 "slices"
25 "sort"
26 "strings"
27 "sync"
28 "unicode/utf8"
29
30 "go.opentelemetry.io/otel/trace"
31 "gocloud.dev/docstore/driver"
32 "gocloud.dev/gcerrors"
33 "gocloud.dev/internal/gcerr"
34 gcdkotel "gocloud.dev/internal/otel"
35 )
36
37 // A Document is a set of field-value pairs. One or more fields, called the key
38 // fields, must uniquely identify the document in the collection. You specify the key
39 // fields when you open a collection.
40 // A field name must be a valid UTF-8 string that does not contain a '.'.
41 //
42 // A Document can be represented as a map[string]int or a pointer to a struct. For
43 // structs, the exported fields are the document fields.
44 type Document = any
45
46 // A Collection represents a set of documents. It provides an easy and portable
47 // way to interact with document stores.
48 // To create a Collection, use constructors found in driver subpackages.
49 type Collection struct {
50 driver driver.Collection
51 tracer *gcdkotel.Tracer
52 mu sync.Mutex
53 closed bool
54 }
55
56 const pkgName = "gocloud.dev/docstore"
57
58 var (
59
60 // OpenTelemetryViews are predefined views for OpenTelemetry metrics.
61 // The views include counts and latency distributions for API method calls.
62 // See the explanations at https://opentelemetry.io/docs/specs/otel/metrics/data-model/ for usage.
63 OpenTelemetryViews = gcdkotel.Views(pkgName)
64 )
65
66 // NewCollection is intended for use by drivers only. Do not use in application code.
67 var NewCollection = newCollection
68
69 // newCollection makes a Collection.
70 func newCollection(d driver.Collection) *Collection {
71 providerName := gcdkotel.ProviderName(d)
72 c := &Collection{
73 driver: d,
74 tracer: gcdkotel.NewTracer(pkgName, providerName),
75 }
76 _, file, lineno, ok := runtime.Caller(1)
77 runtime.SetFinalizer(c, func(c *Collection) {
78 c.mu.Lock()
79 closed := c.closed
80 c.mu.Unlock()
81 if !closed {
82 var caller string
83 if ok {
84 caller = fmt.Sprintf(" (%s:%d)", file, lineno)
85 }
86 log.Printf("A docstore.Collection was never closed%s", caller)
87 }
88 })
89 return c
90 }
91
92 // DefaultRevisionField is the default name of the document field used for document revision
93 // information, to implement optimistic locking.
94 // See the Revisions section of the package documentation.
95 const DefaultRevisionField = "DocstoreRevision"
96
97 func (c *Collection) revisionField() string {
98 if r := c.driver.RevisionField(); r != "" {
99 return r
100 }
101 return DefaultRevisionField
102 }
103
104 // A FieldPath is a dot-separated sequence of UTF-8 field names. Examples:
105 //
106 // room
107 // room.size
108 // room.size.width
109 //
110 // A FieldPath can be used select top-level fields or elements of sub-documents.
111 // There is no way to select a single list element.
112 type FieldPath string
113
114 // Actions returns an ActionList that can be used to perform
115 // actions on the collection's documents.
116 func (c *Collection) Actions() *ActionList {
117 return &ActionList{coll: c}
118 }
119
120 // An ActionList is a group of actions that affect a single collection.
121 //
122 // The writes in an action list (Put, Create, Replace, Update and Delete actions)
123 // must refer to distinct documents and are unordered with respect to each other.
124 // Each write happens independently of the others: all actions will be executed, even
125 // if some fail.
126 //
127 // The Gets in an action list must also refer to distinct documents and are unordered
128 // and independent of each other.
129 //
130 // A Get and a write may refer to the same document. Each write may be paired with
131 // only one Get in this way. The Get and write will be executed in the order
132 // specified in the list: a Get before a write will see the old value of the
133 // document; a Get after the write will see the new value if the service is strongly
134 // consistent, but may see the old value if the service is eventually consistent.
135 type ActionList struct {
136 coll *Collection
137 actions []*Action
138 enableAtomicWrites bool
139 beforeDo func(asFunc func(any) bool) error
140 }
141
142 // An Action is a read or write on a single document.
143 // Use the methods of ActionList to create and execute Actions.
144 type Action struct {
145 kind driver.ActionKind
146 doc Document
147 fieldpaths []FieldPath // paths to retrieve, for Get
148 mods Mods // modifications to make, for Update
149 inAtomicWrite bool // if this action is a part of atomic writes
150 }
151
152 func (l *ActionList) add(a *Action) *ActionList {
153 l.actions = append(l.actions, a)
154 return l
155 }
156
157 // Create adds an action that creates a new document to the given ActionList, and
158 // returns the ActionList. The document must not already exist; an error with code
159 // AlreadyExists is returned if it does. (See gocloud.dev/gcerrors for more on error
160 // codes.)
161 //
162 // If the document doesn't have key fields, or the key fields are empty, meaning
163 // 0, a nil interface value, or any empty array or string, key fields with
164 // unique values will be created and doc will be populated with them if there is
165 // a way to assign those keys, see each driver for details on the requirement of
166 // generating keys.
167 //
168 // The revision field of the document must be absent or nil.
169 //
170 // Except for setting the revision field and possibly setting the key fields, the doc
171 // argument is not modified.
172 func (l *ActionList) Create(doc Document) *ActionList {
173 return l.add(&Action{kind: driver.Create, doc: doc, inAtomicWrite: l.enableAtomicWrites})
174 }
175
176 // Replace adds an action that replaces a document to the given ActionList, and
177 // returns the ActionList. The key fields of the doc argument must be set. The
178 // document must already exist; an error with code NotFound is returned if it does
179 // not (or possibly FailedPrecondition, if the doc argument has a non-nil revision).
180 // (See gocloud.dev/gcerrors for more on error codes.)
181 //
182 // See the Revisions section of the package documentation for how revisions are
183 // handled.
184 func (l *ActionList) Replace(doc Document) *ActionList {
185 return l.add(&Action{kind: driver.Replace, doc: doc, inAtomicWrite: l.enableAtomicWrites})
186 }
187
188 // Put adds an action that adds or replaces a document to the given ActionList, and returns the ActionList.
189 // The key fields must be set.
190 //
191 // If the revision field is non-nil, then Put behaves exactly like Replace, returning
192 // an error if the document does not exist. Otherwise, Put will create the document
193 // if it does not exist.
194 //
195 // See the Revisions section of the package documentation for how revisions are
196 // handled.
197 func (l *ActionList) Put(doc Document) *ActionList {
198 return l.add(&Action{kind: driver.Put, doc: doc, inAtomicWrite: l.enableAtomicWrites})
199 }
200
201 // Delete adds an action that deletes a document to the given ActionList, and returns
202 // the ActionList. Only the key and revision fields of doc are used.
203 // See the Revisions section of the package documentation for how revisions are
204 // handled.
205 // If doc has no revision and the document doesn't exist, nothing happens and no
206 // error is returned.
207 func (l *ActionList) Delete(doc Document) *ActionList {
208 // Rationale for not returning an error if the document does not exist:
209 // Returning an error might be informative and could be ignored, but if the
210 // semantics of an action list are to stop at first error, then we might abort a
211 // list of Deletes just because one of the docs was not present, and that seems
212 // wrong, or at least something you'd want to turn off.
213 return l.add(&Action{kind: driver.Delete, doc: doc, inAtomicWrite: l.enableAtomicWrites})
214 }
215
216 // Get adds an action that retrieves a document to the given ActionList, and
217 // returns the ActionList.
218 // Only the key fields of doc are used.
219 // If fps is omitted, doc will contain all the fields of the retrieved document.
220 // If fps is present, only the given field paths are retrieved. It is undefined
221 // whether other fields of doc at the time of the call are removed, unchanged,
222 // or zeroed, so for portable behavior doc should contain only the key fields.
223 // If you plan to write the document back and let Docstore to perform optimistic
224 // locking, include the revision field in fps. See more about revision at
225 // https://godoc.org/gocloud.dev/docstore#hdr-Revisions.
226 func (l *ActionList) Get(doc Document, fps ...FieldPath) *ActionList {
227 return l.add(&Action{
228 kind: driver.Get,
229 doc: doc,
230 fieldpaths: fps,
231 })
232 }
233
234 // Update atomically applies Mods to doc, which must exist.
235 // Only the key and revision fields of doc are used.
236 // It is an error to pass an empty Mods to Update.
237 //
238 // A modification will create a field if it doesn't exist.
239 //
240 // No field path in mods can be a prefix of another. (It makes no sense
241 // to, say, set foo but increment foo.bar.)
242 //
243 // See the Revisions section of the package documentation for how revisions are
244 // handled.
245 //
246 // It is undefined whether updating a sub-field of a non-map field will succeed.
247 // For instance, if the current document is {a: 1} and Update is called with the
248 // mod "a.b": 2, then either Update will fail, or it will succeed with the result
249 // {a: {b: 2}}.
250 //
251 // Update does not modify its doc argument, except to set the new revision. To obtain
252 // the updated document, call Get after calling Update.
253 func (l *ActionList) Update(doc Document, mods Mods) *ActionList {
254 return l.add(&Action{
255 kind: driver.Update,
256 doc: doc,
257 mods: mods,
258 inAtomicWrite: l.enableAtomicWrites,
259 })
260 }
261
262 // Mods is a map from field paths to modifications.
263 // At present, a modification is one of:
264 // - nil, to delete the field
265 // - an Increment value, to add a number to the field
266 // - any other value, to set the field to that value
267 //
268 // See ActionList.Update.
269 type Mods map[FieldPath]any
270
271 // Increment returns a modification that results in a field being incremented. It
272 // should only be used as a value in a Mods map, like so:
273 //
274 // docstore.Mods{"count": docstore.Increment(1)}
275 //
276 // The amount must be an integer or floating-point value.
277 func Increment(amount any) any {
278 return driver.IncOp{amount}
279 }
280
281 // An ActionListError is returned by ActionList.Do. It contains all the errors
282 // encountered while executing the ActionList, and the positions of the corresponding
283 // actions.
284 type ActionListError []struct {
285 Index int
286 Err error
287 }
288
289 // TODO(jba): use xerrors formatting.
290
291 func (e ActionListError) Error() string {
292 var s []string
293 for _, x := range e {
294 s = append(s, fmt.Sprintf("at %d: %v", x.Index, x.Err))
295 }
296 return strings.Join(s, "; ")
297 }
298
299 // Unwrap returns the error in e, if there is exactly one. If there is more than one
300 // error, Unwrap returns nil, since there is no way to determine which should be
301 // returned.
302 func (e ActionListError) Unwrap() error {
303 if len(e) == 1 {
304 return e[0].Err
305 }
306 // Return nil when e is nil, or has more than one error.
307 // When there are multiple errors, it doesn't make sense to return any of them.
308 return nil
309 }
310
311 // BeforeDo takes a callback function that will be called before the ActionList is
312 // executed by the underlying service. It may be invoked multiple times for a single
313 // call to ActionList.Do, because the driver may split the action list into several
314 // service calls. If any callback invocation returns an error, ActionList.Do returns
315 // an error.
316 //
317 // The callback takes a parameter, asFunc, that converts its argument to
318 // driver-specific types. See https://gocloud.dev/concepts/as for background
319 // information.
320 func (l *ActionList) BeforeDo(f func(asFunc func(any) bool) error) *ActionList {
321 l.beforeDo = f
322 return l
323 }
324
325 // Do executes the action list.
326 //
327 // If Do returns a non-nil error, it will be of type ActionListError. If any action
328 // fails, the returned error will contain the position in the ActionList of each
329 // failed action.
330 //
331 // All the actions will be executed. Docstore tries to execute the actions as
332 // efficiently as possible. Sometimes this makes it impossible to attribute failures
333 // to specific actions; in such cases, the returned ActionListError will have entries
334 // whose Index field is negative.
335 func (l *ActionList) Do(ctx context.Context) error {
336 return l.do(ctx, true)
337 }
338
339 // do implements Do with optional OpenTelemetry tracing, so it can be used internally.
340 func (l *ActionList) do(ctx context.Context, withTracing bool) (err error) {
341 if err := l.coll.checkClosed(); err != nil {
342 return ActionListError{{-1, errClosed}}
343 }
344
345 if withTracing {
346 var span trace.Span
347 ctx, span = l.coll.tracer.Start(ctx, "ActionList.Do")
348 defer func() { l.coll.tracer.End(ctx, span, err) }()
349 }
350
351 das, err := l.toDriverActions()
352 if err != nil {
353 return err
354 }
355 dopts := &driver.RunActionsOptions{BeforeDo: l.beforeDo}
356 alerr := ActionListError(l.coll.driver.RunActions(ctx, das, dopts))
357 if len(alerr) == 0 {
358 return nil // Explicitly return nil, because alerr is not of type error.
359 }
360 for i := range alerr {
361 alerr[i].Err = wrapError(l.coll.driver, alerr[i].Err)
362 }
363 return alerr
364 }
365
366 func (l *ActionList) toDriverActions() ([]*driver.Action, error) {
367 var das []*driver.Action
368 var alerr ActionListError
369 // Create a set of (document key, is Get action) pairs for detecting duplicates:
370 // an action list can have at most one get and at most one write for each key.
371 type keyAndKind struct {
372 key any
373 isGet bool
374 }
375 seen := map[keyAndKind]bool{}
376 for i, a := range l.actions {
377 d, err := l.coll.toDriverAction(a)
378 // Check for duplicate key.
379 if err == nil && d.Key != nil {
380 kk := keyAndKind{d.Key, d.Kind == driver.Get}
381 if seen[kk] {
382 err = gcerr.Newf(gcerr.InvalidArgument, nil, "duplicate key in action list: %v", d.Key)
383 } else {
384 seen[kk] = true
385 }
386 }
387 if err != nil {
388 alerr = append(alerr, struct {
389 Index int
390 Err error
391 }{i, wrapError(l.coll.driver, err)})
392 } else {
393 d.Index = i
394 das = append(das, d)
395 }
396 }
397 if len(alerr) > 0 {
398 return nil, alerr
399 }
400 return das, nil
401 }
402
403 func (c *Collection) toDriverAction(a *Action) (*driver.Action, error) {
404 ddoc, err := driver.NewDocument(a.doc)
405 if err != nil {
406 return nil, err
407 }
408 key, err := c.driver.Key(ddoc)
409 if err != nil {
410 if gcerrors.Code(err) != gcerr.InvalidArgument {
411 err = gcerr.Newf(gcerr.InvalidArgument, err, "bad document key")
412 }
413 return nil, err
414 }
415 if key == nil || driver.IsEmptyValue(reflect.ValueOf(key)) {
416 if a.kind != driver.Create {
417 return nil, gcerr.Newf(gcerr.InvalidArgument, nil, "missing document key")
418 }
419 // set the key to nil so that the following code does not need to check for
420 // empty.
421 key = nil
422 }
423 if reflect.ValueOf(key).Kind() == reflect.Pointer {
424 return nil, gcerr.Newf(gcerr.InvalidArgument, nil, "keys cannot be pointers")
425 }
426 rev, _ := ddoc.GetField(c.revisionField())
427 if a.kind == driver.Create && rev != nil {
428 return nil, gcerr.Newf(gcerr.InvalidArgument, nil, "cannot create a document with a revision field")
429 }
430 kind := a.kind
431 if kind == driver.Put && rev != nil {
432 // A Put with a revision field is equivalent to a Replace.
433 kind = driver.Replace
434 }
435 d := &driver.Action{Kind: kind, Doc: ddoc, Key: key, InAtomicWrite: a.inAtomicWrite}
436 if a.fieldpaths != nil {
437 d.FieldPaths, err = parseFieldPaths(a.fieldpaths)
438 if err != nil {
439 return nil, err
440 }
441 }
442 if a.kind == driver.Update {
443 d.Mods, err = toDriverMods(a.mods)
444 if err != nil {
445 return nil, err
446 }
447 }
448 return d, nil
449 }
450
451 func parseFieldPaths(fps []FieldPath) ([][]string, error) {
452 res := make([][]string, len(fps))
453 for i, s := range fps {
454 fp, err := parseFieldPath(s)
455 if err != nil {
456 return nil, err
457 }
458 res[i] = fp
459 }
460 return res, nil
461 }
462
463 func toDriverMods(mods Mods) ([]driver.Mod, error) {
464 // Convert mods from a map to a slice of (fieldPath, value) pairs.
465 // The map is easier for users to write, but the slice is easier
466 // to process.
467 if len(mods) == 0 {
468 return nil, gcerr.Newf(gcerr.InvalidArgument, nil, "no mods passed to Update")
469 }
470
471 // Sort keys so tests are deterministic.
472 // After sorting, a key might not immediately follow its prefix. Consider the
473 // sorted list of keys "a", "a+b", "a.b". "a" is prefix of "a.b", but since '+'
474 // sorts before '.', it is not adjacent to it. All we can assume is that the
475 // prefix is before the key.
476 var keys []string
477 for k := range mods {
478 keys = append(keys, string(k))
479 }
480 sort.Strings(keys)
481
482 var dmods []driver.Mod
483 for _, k := range keys {
484 k := FieldPath(k)
485 v := mods[k]
486 fp, err := parseFieldPath(k)
487 if err != nil {
488 return nil, err
489 }
490 for _, d := range dmods {
491 if fpHasPrefix(fp, d.FieldPath) {
492 return nil, gcerr.Newf(gcerr.InvalidArgument, nil,
493 "field path %q is a prefix of %q", strings.Join(d.FieldPath, "."), k)
494 }
495 }
496 if inc, ok := v.(driver.IncOp); ok && !isIncNumber(inc.Amount) {
497 return nil, gcerr.Newf(gcerr.InvalidArgument, nil,
498 "Increment amount %v of type %[1]T must be an integer or floating-point number", inc.Amount)
499 }
500 dmods = append(dmods, driver.Mod{FieldPath: fp, Value: v})
501 }
502 return dmods, nil
503 }
504
505 // fpHasPrefix reports whether the field path fp begins with prefix.
506 func fpHasPrefix(fp, prefix []string) bool {
507 if len(fp) < len(prefix) {
508 return false
509 }
510 for i, p := range prefix {
511 if fp[i] != p {
512 return false
513 }
514 }
515 return true
516 }
517
518 func isIncNumber(x any) bool {
519 switch reflect.TypeOf(x).Kind() {
520 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
521 return true
522 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
523 return true
524 case reflect.Float32, reflect.Float64:
525 return true
526 default:
527 return false
528 }
529 }
530
531 func (l *ActionList) String() string {
532 var as []string
533 for _, a := range l.actions {
534 as = append(as, a.String())
535 }
536 return "[" + strings.Join(as, ", ") + "]"
537 }
538
539 // AtomicWrites causes all following writes in the list to execute as a single atomic operation.
540 func (l *ActionList) AtomicWrites() *ActionList {
541 l.enableAtomicWrites = true
542 return l
543 }
544
545 func (a *Action) String() string {
546 buf := &strings.Builder{}
547 fmt.Fprintf(buf, "%s(%v", a.kind, a.doc)
548 for _, fp := range a.fieldpaths {
549 fmt.Fprintf(buf, ", %s", fp)
550 }
551 for _, m := range a.mods {
552 fmt.Fprintf(buf, ", %v", m)
553 }
554 fmt.Fprint(buf, ")")
555 return buf.String()
556 }
557
558 // Create is a convenience for building and running a single-element action list.
559 // See ActionList.Create.
560 func (c *Collection) Create(ctx context.Context, doc Document) error {
561 if err := c.Actions().Create(doc).Do(ctx); err != nil {
562 return err.(ActionListError).Unwrap()
563 }
564 return nil
565 }
566
567 // Replace is a convenience for building and running a single-element action list.
568 // See ActionList.Replace.
569 func (c *Collection) Replace(ctx context.Context, doc Document) error {
570 if err := c.Actions().Replace(doc).Do(ctx); err != nil {
571 return err.(ActionListError).Unwrap()
572 }
573 return nil
574 }
575
576 // Put is a convenience for building and running a single-element action list.
577 // See ActionList.Put.
578 func (c *Collection) Put(ctx context.Context, doc Document) error {
579 if err := c.Actions().Put(doc).Do(ctx); err != nil {
580 return err.(ActionListError).Unwrap()
581 }
582 return nil
583 }
584
585 // Delete is a convenience for building and running a single-element action list.
586 // See ActionList.Delete.
587 func (c *Collection) Delete(ctx context.Context, doc Document) error {
588 if err := c.Actions().Delete(doc).Do(ctx); err != nil {
589 return err.(ActionListError).Unwrap()
590 }
591 return nil
592 }
593
594 // Get is a convenience for building and running a single-element action list.
595 // See ActionList.Get.
596 func (c *Collection) Get(ctx context.Context, doc Document, fps ...FieldPath) error {
597 if err := c.Actions().Get(doc, fps...).Do(ctx); err != nil {
598 return err.(ActionListError).Unwrap()
599 }
600 return nil
601 }
602
603 // Update is a convenience for building and running a single-element action list.
604 // See ActionList.Update.
605 func (c *Collection) Update(ctx context.Context, doc Document, mods Mods) error {
606 if err := c.Actions().Update(doc, mods).Do(ctx); err != nil {
607 return err.(ActionListError).Unwrap()
608 }
609 return nil
610 }
611
612 func parseFieldPath(fp FieldPath) ([]string, error) {
613 if len(fp) == 0 {
614 return nil, gcerr.Newf(gcerr.InvalidArgument, nil, "empty field path")
615 }
616 if !utf8.ValidString(string(fp)) {
617 return nil, gcerr.Newf(gcerr.InvalidArgument, nil, "invalid UTF-8 field path %q", fp)
618 }
619 parts := strings.Split(string(fp), ".")
620 if slices.Contains(parts, "") {
621 return nil, gcerr.Newf(gcerr.InvalidArgument, nil, "empty component in field path %q", fp)
622 }
623 return parts, nil
624 }
625
626 // RevisionToString converts a document revision to a string. The returned
627 // string should be treated as opaque; its only use is to provide a serialized
628 // form that can be passed around (e.g., as a hidden field on a web form)
629 // and then turned back into a revision using StringToRevision. The string is safe
630 // for use in URLs and HTTP forms.
631 func (c *Collection) RevisionToString(rev any) (string, error) {
632 if rev == nil {
633 return "", gcerr.Newf(gcerr.InvalidArgument, nil, "RevisionToString: nil revision")
634 }
635 bytes, err := c.driver.RevisionToBytes(rev)
636 if err != nil {
637 return "", wrapError(c.driver, err)
638 }
639 return base64.RawURLEncoding.EncodeToString(bytes), nil
640 }
641
642 // StringToRevision converts a string obtained with RevisionToString
643 // to a revision.
644 func (c *Collection) StringToRevision(s string) (any, error) {
645 if s == "" {
646 return "", gcerr.Newf(gcerr.InvalidArgument, nil, "StringToRevision: empty string")
647 }
648 bytes, err := base64.RawURLEncoding.DecodeString(s)
649 if err != nil {
650 return nil, err
651 }
652 rev, err := c.driver.BytesToRevision(bytes)
653 if err != nil {
654 return "", wrapError(c.driver, err)
655 }
656 return rev, nil
657 }
658
659 // As converts i to driver-specific types.
660 // See https://gocloud.dev/concepts/as/ for background information, the "As"
661 // examples in this package for examples, and the driver package
662 // documentation for the specific types supported for that driver.
663 func (c *Collection) As(i any) bool {
664 if i == nil {
665 return false
666 }
667 return c.driver.As(i)
668 }
669
670 var errClosed = gcerr.Newf(gcerr.FailedPrecondition, nil, "docstore: Collection has been closed")
671
672 // Close releases any resources used for the collection.
673 func (c *Collection) Close() error {
674 c.mu.Lock()
675 prev := c.closed
676 c.closed = true
677 c.mu.Unlock()
678 if prev {
679 return errClosed
680 }
681 return wrapError(c.driver, c.driver.Close())
682 }
683
684 func (c *Collection) checkClosed() error {
685 c.mu.Lock()
686 defer c.mu.Unlock()
687 if c.closed {
688 return errClosed
689 }
690 return nil
691 }
692
693 func wrapError(c driver.Collection, err error) error {
694 if err == nil {
695 return nil
696 }
697 if gcerr.DoNotWrap(err) {
698 return err
699 }
700 if _, ok := err.(*gcerr.Error); ok {
701 return err
702 }
703 return gcerr.New(c.ErrorCode(err), err, 2, "docstore")
704 }
705
706 // ErrorAs converts i to driver-specific types. See
707 // https://gocloud.dev/concepts/as/ for background information and the
708 // driver package documentation for the specific types supported for
709 // that driver.
710 //
711 // When the error is an ActionListError, ErrorAs works on individual errors in
712 // the slice, not the slice itself.
713 //
714 // ErrorAs panics if i is nil or not a pointer.
715 // ErrorAs returns false if err == nil.
716 func (c *Collection) ErrorAs(err error, i any) bool {
717 return gcerr.ErrorAs(err, i, c.driver.ErrorAs)
718 }