| 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 memdocstore provides an in-process in-memory implementation of the docstore |
| 16 |
// API. It is suitable for local development and testing. |
| 17 |
// |
| 18 |
// Every document in a memdocstore collection has a unique primary key. The primary |
| 19 |
// key values need not be strings; they may be any comparable Go value. |
| 20 |
// |
| 21 |
// # Action Lists |
| 22 |
// |
| 23 |
// Action lists are executed concurrently. Each action in an action list is executed |
| 24 |
// in a separate goroutine. |
| 25 |
// |
| 26 |
// memdocstore supports atomic writes. When using AtomicWrites(), all write actions |
| 27 |
// in the action list are executed atomically - either all succeed or all fail together. |
| 28 |
// |
| 29 |
// memdocstore calls the BeforeDo function of an ActionList once before executing the |
| 30 |
// actions. Its As function never returns true. |
| 31 |
// |
| 32 |
// # URLs |
| 33 |
// |
| 34 |
// For docstore.OpenCollection, memdocstore registers for the scheme |
| 35 |
// "mem". |
| 36 |
// To customize the URL opener, or for more details on the URL format, |
| 37 |
// see URLOpener. |
| 38 |
// See https://gocloud.dev/concepts/urls/ for background information. |
| 39 |
package memdocstore // import "gocloud.dev/docstore/memdocstore" |
| 40 |
|
| 41 |
import ( |
| 42 |
"context" |
| 43 |
"encoding/gob" |
| 44 |
"fmt" |
| 45 |
"os" |
| 46 |
"reflect" |
| 47 |
"sort" |
| 48 |
"strconv" |
| 49 |
"strings" |
| 50 |
"sync" |
| 51 |
|
| 52 |
"gocloud.dev/docstore" |
| 53 |
"gocloud.dev/docstore/driver" |
| 54 |
"gocloud.dev/gcerrors" |
| 55 |
"gocloud.dev/internal/gcerr" |
| 56 |
) |
| 57 |
|
| 58 |
// Options are optional arguments to the OpenCollection functions. |
| 59 |
type Options struct { |
| 60 |
// The name of the field holding the document revision. |
| 61 |
// Defaults to docstore.DefaultRevisionField. |
| 62 |
RevisionField string |
| 63 |
|
| 64 |
// The maximum number of concurrent goroutines started for a single call to |
| 65 |
// ActionList.Do. If less than 1, there is no limit. |
| 66 |
MaxOutstandingActions int |
| 67 |
|
| 68 |
// The filename associated with this collection. |
| 69 |
// When a collection is opened with a non-nil filename, the collection |
| 70 |
// is loaded from the file if it exists. Otherwise, an empty collection is created. |
| 71 |
// When the collection is closed, its contents are saved to the file. |
| 72 |
Filename string |
| 73 |
|
| 74 |
// AllowNestedSliceQueries allows querying into nested slices. |
| 75 |
// If true queries for a field path which points to a slice will return |
| 76 |
// true if any element of the slice has a value that validates with the operator. |
| 77 |
// This makes the memdocstore more compatible with MongoDB, |
| 78 |
// but other providers may not support this feature. |
| 79 |
AllowNestedSliceQueries bool |
| 80 |
|
| 81 |
// Call this function when the collection is closed. |
| 82 |
// For internal use only. |
| 83 |
onClose func() |
| 84 |
} |
| 85 |
|
| 86 |
// TODO(jba): make this package thread-safe. |
| 87 |
|
| 88 |
// OpenCollection creates a *docstore.Collection backed by memory. keyField is the |
| 89 |
// document field holding the primary key of the collection. |
| 90 |
func OpenCollection(keyField string, opts *Options) (*docstore.Collection, error) { |
| 91 |
c, err := newCollection(keyField, nil, opts) |
| 92 |
if err != nil { |
| 93 |
return nil, err |
| 94 |
} |
| 95 |
return docstore.NewCollection(c), nil |
| 96 |
} |
| 97 |
|
| 98 |
// OpenCollectionWithKeyFunc creates a *docstore.Collection backed by memory. keyFunc takes |
| 99 |
// a document and returns the document's primary key. It should return nil if the |
| 100 |
// document is missing the information to construct a key. This will cause all |
| 101 |
// actions, even Create, to fail. |
| 102 |
// |
| 103 |
// For the collection to be usable with Query.Delete and Query.Update, |
| 104 |
// keyFunc must work with map[string]interface{} as well as whatever |
| 105 |
// struct type the collection normally uses (if any). |
| 106 |
func OpenCollectionWithKeyFunc(keyFunc func(docstore.Document) any, opts *Options) (*docstore.Collection, error) { |
| 107 |
c, err := newCollection("", keyFunc, opts) |
| 108 |
if err != nil { |
| 109 |
return nil, err |
| 110 |
} |
| 111 |
return docstore.NewCollection(c), nil |
| 112 |
} |
| 113 |
|
| 114 |
func newCollection(keyField string, keyFunc func(docstore.Document) any, opts *Options) (driver.Collection, error) { |
| 115 |
if keyField == "" && keyFunc == nil { |
| 116 |
return nil, gcerr.Newf(gcerr.InvalidArgument, nil, "must provide either keyField or keyFunc") |
| 117 |
} |
| 118 |
if opts == nil { |
| 119 |
opts = &Options{} |
| 120 |
} |
| 121 |
if opts.RevisionField == "" { |
| 122 |
opts.RevisionField = docstore.DefaultRevisionField |
| 123 |
} |
| 124 |
docs, err := loadDocs(opts.Filename) |
| 125 |
if err != nil { |
| 126 |
return nil, err |
| 127 |
} |
| 128 |
return &collection{ |
| 129 |
keyField: keyField, |
| 130 |
keyFunc: keyFunc, |
| 131 |
docs: docs, |
| 132 |
opts: opts, |
| 133 |
curRevision: 0, |
| 134 |
}, nil |
| 135 |
} |
| 136 |
|
| 137 |
// A storedDoc is a document that is stored in a collection. |
| 138 |
// |
| 139 |
// We store documents as maps from keys to values. Even if the user is using |
| 140 |
// map[string]interface{}, we make our own copy. |
| 141 |
// |
| 142 |
// Using a separate helps distinguish documents coming from a user (those "on |
| 143 |
// the client," in a more typical driver that acts as a network client) from |
| 144 |
// those stored in a collection (those "on the server"). |
| 145 |
type storedDoc map[string]any |
| 146 |
|
| 147 |
type collection struct { |
| 148 |
keyField string |
| 149 |
keyFunc func(docstore.Document) any |
| 150 |
opts *Options |
| 151 |
mu sync.Mutex |
| 152 |
docs map[any]storedDoc |
| 153 |
curRevision int64 // incremented on each write |
| 154 |
} |
| 155 |
|
| 156 |
func (c *collection) Key(doc driver.Document) (any, error) { |
| 157 |
if c.keyField != "" { |
| 158 |
key, _ := doc.GetField(c.keyField) // no error on missing key, and it will be nil |
| 159 |
return key, nil |
| 160 |
} |
| 161 |
key := c.keyFunc(doc.Origin) |
| 162 |
if key == nil || driver.IsEmptyValue(reflect.ValueOf(key)) { |
| 163 |
return nil, gcerr.Newf(gcerr.InvalidArgument, nil, "missing document key") |
| 164 |
} |
| 165 |
return key, nil |
| 166 |
} |
| 167 |
|
| 168 |
func (c *collection) RevisionField() string { |
| 169 |
return c.opts.RevisionField |
| 170 |
} |
| 171 |
|
| 172 |
// ErrorCode implements driver.ErrorCode. |
| 173 |
func (c *collection) ErrorCode(err error) gcerrors.ErrorCode { |
| 174 |
return gcerrors.Code(err) |
| 175 |
} |
| 176 |
|
| 177 |
// RunActions implements driver.RunActions. |
| 178 |
func (c *collection) RunActions(ctx context.Context, actions []*driver.Action, opts *driver.RunActionsOptions) driver.ActionListError { |
| 179 |
errs := make([]error, len(actions)) |
| 180 |
|
| 181 |
// Run the actions concurrently with each other. |
| 182 |
run := func(as []*driver.Action) { |
| 183 |
t := driver.NewThrottle(c.opts.MaxOutstandingActions) |
| 184 |
for _, a := range as { |
| 185 |
t.Acquire() |
| 186 |
go func() { |
| 187 |
defer t.Release() |
| 188 |
errs[a.Index] = c.runAction(ctx, a) |
| 189 |
}() |
| 190 |
} |
| 191 |
t.Wait() |
| 192 |
} |
| 193 |
|
| 194 |
if opts.BeforeDo != nil { |
| 195 |
if err := opts.BeforeDo(func(any) bool { return false }); err != nil { |
| 196 |
for i := range errs { |
| 197 |
errs[i] = err |
| 198 |
} |
| 199 |
return driver.NewActionListError(errs) |
| 200 |
} |
| 201 |
} |
| 202 |
|
| 203 |
beforeGets, gets, writes, writesTx, afterGets := driver.GroupActions(actions) |
| 204 |
run(beforeGets) |
| 205 |
run(gets) |
| 206 |
run(writes) |
| 207 |
|
| 208 |
// Handle atomic writes separately to ensure they are truly atomic |
| 209 |
if len(writesTx) > 0 { |
| 210 |
c.runAtomicWrites(ctx, writesTx, errs) |
| 211 |
} |
| 212 |
|
| 213 |
run(afterGets) |
| 214 |
return driver.NewActionListError(errs) |
| 215 |
} |
| 216 |
|
| 217 |
// runAtomicWrites executes multiple write actions atomically. |
| 218 |
// All writes either succeed or all fail together. |
| 219 |
func (c *collection) runAtomicWrites(ctx context.Context, actions []*driver.Action, errs []error) { |
| 220 |
// Stop if the context is done. |
| 221 |
if ctx.Err() != nil { |
| 222 |
for _, a := range actions { |
| 223 |
errs[a.Index] = ctx.Err() |
| 224 |
} |
| 225 |
return |
| 226 |
} |
| 227 |
|
| 228 |
c.mu.Lock() |
| 229 |
defer c.mu.Unlock() |
| 230 |
|
| 231 |
// First, validate all actions and collect current documents |
| 232 |
type actionInfo struct { |
| 233 |
action *driver.Action |
| 234 |
current storedDoc |
| 235 |
exists bool |
| 236 |
} |
| 237 |
|
| 238 |
actionInfos := make([]actionInfo, len(actions)) |
| 239 |
for i, a := range actions { |
| 240 |
info := &actionInfos[i] |
| 241 |
info.action = a |
| 242 |
|
| 243 |
if a.Key != nil { |
| 244 |
info.current, info.exists = c.docs[a.Key] |
| 245 |
} |
| 246 |
|
| 247 |
// Check for NotFound errors |
| 248 |
if !info.exists && (a.Kind == driver.Replace || a.Kind == driver.Update || a.Kind == driver.Get) { |
| 249 |
for _, a2 := range actions { |
| 250 |
errs[a2.Index] = gcerr.Newf(gcerr.NotFound, nil, "document with key %v does not exist", a.Key) |
| 251 |
} |
| 252 |
return |
| 253 |
} |
| 254 |
|
| 255 |
// Check revision conflicts |
| 256 |
if err := c.checkRevision(a.Doc, info.current); err != nil { |
| 257 |
for _, a2 := range actions { |
| 258 |
errs[a2.Index] = err |
| 259 |
} |
| 260 |
return |
| 261 |
} |
| 262 |
} |
| 263 |
|
| 264 |
// Now execute all actions atomically |
| 265 |
for _, info := range actionInfos { |
| 266 |
if err := c.executeAction(info.action, info.current, info.exists); err != nil { |
| 267 |
// If any action fails, mark all actions as failed |
| 268 |
for _, a2 := range actions { |
| 269 |
errs[a2.Index] = err |
| 270 |
} |
| 271 |
return |
| 272 |
} |
| 273 |
} |
| 274 |
} |
| 275 |
|
| 276 |
// runAction executes a single action. |
| 277 |
func (c *collection) runAction(ctx context.Context, a *driver.Action) error { |
| 278 |
// Stop if the context is done. |
| 279 |
if ctx.Err() != nil { |
| 280 |
return ctx.Err() |
| 281 |
} |
| 282 |
// Get the key from the doc so we can look it up in the map. |
| 283 |
c.mu.Lock() |
| 284 |
defer c.mu.Unlock() |
| 285 |
// If there is a key, get the current document with that key. |
| 286 |
var ( |
| 287 |
current storedDoc |
| 288 |
exists bool |
| 289 |
) |
| 290 |
if a.Key != nil { |
| 291 |
current, exists = c.docs[a.Key] |
| 292 |
} |
| 293 |
// Check for a NotFound error. |
| 294 |
if !exists && (a.Kind == driver.Replace || a.Kind == driver.Update || a.Kind == driver.Get) { |
| 295 |
return gcerr.Newf(gcerr.NotFound, nil, "document with key %v does not exist", a.Key) |
| 296 |
} |
| 297 |
|
| 298 |
// Check revision conflicts |
| 299 |
if a.Kind != driver.Get && a.Kind != driver.Create { |
| 300 |
if err := c.checkRevision(a.Doc, current); err != nil { |
| 301 |
return err |
| 302 |
} |
| 303 |
} |
| 304 |
|
| 305 |
// Execute the action for Get |
| 306 |
if a.Kind == driver.Get { |
| 307 |
// Handle Get separately since it doesn't modify the document. |
| 308 |
// We've already retrieved the document into current, above. |
| 309 |
// Now we copy its fields into the user-provided document. |
| 310 |
return decodeDoc(current, a.Doc, a.FieldPaths) |
| 311 |
} |
| 312 |
|
| 313 |
return c.executeAction(a, current, exists) |
| 314 |
} |
| 315 |
|
| 316 |
// executeAction executes a single action. Must be called with the lock held. |
| 317 |
// This method is shared between runAction and runAtomicWrites to eliminate code duplication. |
| 318 |
func (c *collection) executeAction(a *driver.Action, current storedDoc, exists bool) error { |
| 319 |
switch a.Kind { |
| 320 |
case driver.Create: |
| 321 |
// It is an error to attempt to create an existing document. |
| 322 |
if exists { |
| 323 |
return gcerr.Newf(gcerr.AlreadyExists, nil, "Create: document with key %v exists", a.Key) |
| 324 |
} |
| 325 |
// If the user didn't supply a value for the key field, create a new one. |
| 326 |
if a.Key == nil { |
| 327 |
a.Key = driver.UniqueString() |
| 328 |
// Set the new key in the document. |
| 329 |
if err := a.Doc.SetField(c.keyField, a.Key); err != nil { |
| 330 |
return gcerr.Newf(gcerr.InvalidArgument, nil, "cannot set key field %q", c.keyField) |
| 331 |
} |
| 332 |
} |
| 333 |
fallthrough |
| 334 |
|
| 335 |
case driver.Replace, driver.Put: |
| 336 |
doc, err := encodeDoc(a.Doc) |
| 337 |
if err != nil { |
| 338 |
return err |
| 339 |
} |
| 340 |
if a.Doc.HasField(c.opts.RevisionField) { |
| 341 |
c.changeRevision(doc) |
| 342 |
if err := a.Doc.SetField(c.opts.RevisionField, doc[c.opts.RevisionField]); err != nil { |
| 343 |
return err |
| 344 |
} |
| 345 |
} |
| 346 |
c.docs[a.Key] = doc |
| 347 |
|
| 348 |
case driver.Delete: |
| 349 |
delete(c.docs, a.Key) |
| 350 |
|
| 351 |
case driver.Update: |
| 352 |
if err := c.update(current, a.Mods); err != nil { |
| 353 |
return err |
| 354 |
} |
| 355 |
if a.Doc.HasField(c.opts.RevisionField) { |
| 356 |
c.changeRevision(current) |
| 357 |
if err := a.Doc.SetField(c.opts.RevisionField, current[c.opts.RevisionField]); err != nil { |
| 358 |
return err |
| 359 |
} |
| 360 |
} |
| 361 |
|
| 362 |
default: |
| 363 |
return gcerr.Newf(gcerr.Internal, nil, "unknown kind %v", a.Kind) |
| 364 |
} |
| 365 |
return nil |
| 366 |
} |
| 367 |
|
| 368 |
// Must be called with the lock held. |
| 369 |
// Does not change the stored doc's revision field; that is up to the caller. |
| 370 |
func (c *collection) update(doc storedDoc, mods []driver.Mod) error { |
| 371 |
// Sort mods by first field path element so tests are deterministic. |
| 372 |
sort.Slice(mods, func(i, j int) bool { return mods[i].FieldPath[0] < mods[j].FieldPath[0] }) |
| 373 |
|
| 374 |
// To make update atomic, we first convert the actions into a form that can't |
| 375 |
// fail. |
| 376 |
type guaranteedMod struct { |
| 377 |
parentMap map[string]any // the map holding the key to be modified |
| 378 |
key string |
| 379 |
encodedValue any // the value after encoding |
| 380 |
} |
| 381 |
|
| 382 |
gmods := make([]guaranteedMod, len(mods)) |
| 383 |
var err error |
| 384 |
for i, mod := range mods { |
| 385 |
gmod := &gmods[i] |
| 386 |
// Check that the field path is valid. That is, every component of the path |
| 387 |
// but the last refers to a map, and no component along the way is nil. |
| 388 |
if gmod.parentMap, err = getParentMap(doc, mod.FieldPath, false); err != nil { |
| 389 |
return err |
| 390 |
} |
| 391 |
gmod.key = mod.FieldPath[len(mod.FieldPath)-1] |
| 392 |
if inc, ok := mod.Value.(driver.IncOp); ok { |
| 393 |
amt, err := encodeValue(inc.Amount) |
| 394 |
if err != nil { |
| 395 |
return err |
| 396 |
} |
| 397 |
if gmod.encodedValue, err = add(gmod.parentMap[gmod.key], amt); err != nil { |
| 398 |
return err |
| 399 |
} |
| 400 |
} else if mod.Value != nil { |
| 401 |
// Make sure the value encodes successfully. |
| 402 |
if gmod.encodedValue, err = encodeValue(mod.Value); err != nil { |
| 403 |
return err |
| 404 |
} |
| 405 |
} |
| 406 |
} |
| 407 |
// Now execute the guaranteed mods. |
| 408 |
for _, m := range gmods { |
| 409 |
if m.encodedValue == nil { |
| 410 |
delete(m.parentMap, m.key) |
| 411 |
} else { |
| 412 |
m.parentMap[m.key] = m.encodedValue |
| 413 |
} |
| 414 |
} |
| 415 |
return nil |
| 416 |
} |
| 417 |
|
| 418 |
// Add two encoded numbers. |
| 419 |
// Since they're encoded, they are either int64 or float64. |
| 420 |
// Allow adding a float to an int, producing a float. |
| 421 |
// TODO(jba): see how other drivers handle that. |
| 422 |
func add(x, y any) (any, error) { |
| 423 |
if x == nil { |
| 424 |
return y, nil |
| 425 |
} |
| 426 |
switch x := x.(type) { |
| 427 |
case int64: |
| 428 |
switch y := y.(type) { |
| 429 |
case int64: |
| 430 |
return x + y, nil |
| 431 |
case float64: |
| 432 |
return float64(x) + y, nil |
| 433 |
default: |
| 434 |
// This shouldn't happen because it should be checked by docstore. |
| 435 |
return nil, gcerr.Newf(gcerr.Internal, nil, "bad increment aount type %T", y) |
| 436 |
} |
| 437 |
case float64: |
| 438 |
switch y := y.(type) { |
| 439 |
case int64: |
| 440 |
return x + float64(y), nil |
| 441 |
case float64: |
| 442 |
return x + y, nil |
| 443 |
default: |
| 444 |
// This shouldn't happen because it should be checked by docstore. |
| 445 |
return nil, gcerr.Newf(gcerr.Internal, nil, "bad increment aount type %T", y) |
| 446 |
} |
| 447 |
default: |
| 448 |
return nil, gcerr.Newf(gcerr.InvalidArgument, nil, "value %v being incremented not int64 or float64", x) |
| 449 |
} |
| 450 |
} |
| 451 |
|
| 452 |
// Must be called with the lock held. |
| 453 |
func (c *collection) changeRevision(doc storedDoc) { |
| 454 |
c.curRevision++ |
| 455 |
doc[c.opts.RevisionField] = c.curRevision |
| 456 |
} |
| 457 |
|
| 458 |
func (c *collection) checkRevision(arg driver.Document, current storedDoc) error { |
| 459 |
if current == nil { |
| 460 |
return nil // no existing document or the incoming doc has no revision |
| 461 |
} |
| 462 |
curRev, ok := current[c.opts.RevisionField] |
| 463 |
if !ok { |
| 464 |
return nil // there is no revision to check |
| 465 |
} |
| 466 |
curRev = curRev.(int64) |
| 467 |
r, err := arg.GetField(c.opts.RevisionField) |
| 468 |
if err != nil || r == nil { |
| 469 |
return nil // no incoming revision information: nothing to check |
| 470 |
} |
| 471 |
wantRev, ok := r.(int64) |
| 472 |
if !ok { |
| 473 |
return gcerr.Newf(gcerr.InvalidArgument, nil, "revision field %s is not an int64", c.opts.RevisionField) |
| 474 |
} |
| 475 |
if wantRev != curRev { |
| 476 |
return gcerr.Newf(gcerr.FailedPrecondition, nil, "mismatched revisions: want %d, current %d", wantRev, curRev) |
| 477 |
} |
| 478 |
return nil |
| 479 |
} |
| 480 |
|
| 481 |
// getAtFieldPath gets the value of m at fp. It returns an error if fp is invalid. |
| 482 |
// If nested is true compare against all elements of a slice, see AllowNestedSliceQueries |
| 483 |
// (see getParentMap). |
| 484 |
func getAtFieldPath(m map[string]any, fp []string, nested bool) (result any, err error) { |
| 485 |
var get func(m any, name string) any |
| 486 |
get = func(m any, name string) any { |
| 487 |
switch m := m.(type) { |
| 488 |
case map[string]any: |
| 489 |
return m[name] |
| 490 |
case []any: |
| 491 |
if !nested { |
| 492 |
return nil |
| 493 |
} |
| 494 |
var result []any |
| 495 |
for _, e := range m { |
| 496 |
next := get(e, name) |
| 497 |
// If we have slices within slices the compare function does not see the nested slices. |
| 498 |
// Changing the compare function to be recursive would be more effort than flattening the slices here. |
| 499 |
sliced, ok := next.([]any) |
| 500 |
if ok { |
| 501 |
result = append(result, sliced...) |
| 502 |
} else { |
| 503 |
result = append(result, next) |
| 504 |
} |
| 505 |
} |
| 506 |
return result |
| 507 |
} |
| 508 |
return nil |
| 509 |
} |
| 510 |
result = m |
| 511 |
for _, k := range fp { |
| 512 |
next := get(result, k) |
| 513 |
if next == nil { |
| 514 |
return nil, gcerr.Newf(gcerr.NotFound, nil, "field %s not found", strings.Join(fp, ".")) |
| 515 |
} |
| 516 |
result = next |
| 517 |
} |
| 518 |
return result, nil |
| 519 |
} |
| 520 |
|
| 521 |
// setAtFieldPath sets m's value at fp to val. It creates intermediate maps as |
| 522 |
// needed. It returns an error if a non-final component of fp does not denote a map. |
| 523 |
func setAtFieldPath(m map[string]any, fp []string, val any) error { |
| 524 |
m2, err := getParentMap(m, fp, true) |
| 525 |
if err != nil { |
| 526 |
return err |
| 527 |
} |
| 528 |
m2[fp[len(fp)-1]] = val |
| 529 |
return nil |
| 530 |
} |
| 531 |
|
| 532 |
// getParentMap returns the map that directly contains the given field path; |
| 533 |
// that is, the value of m at the field path that excludes the last component |
| 534 |
// of fp. If a non-map is encountered along the way, an InvalidArgument error is |
| 535 |
// returned. If nil is encountered, nil is returned unless create is true, in |
| 536 |
// which case a map is added at that point. |
| 537 |
func getParentMap(m map[string]any, fp []string, create bool) (map[string]any, error) { |
| 538 |
var ok bool |
| 539 |
for _, k := range fp[:len(fp)-1] { |
| 540 |
if m[k] == nil { |
| 541 |
if !create { |
| 542 |
return nil, nil |
| 543 |
} |
| 544 |
m[k] = map[string]any{} |
| 545 |
} |
| 546 |
m, ok = m[k].(map[string]any) |
| 547 |
if !ok { |
| 548 |
return nil, gcerr.Newf(gcerr.InvalidArgument, nil, "invalid field path %q at %q", strings.Join(fp, "."), k) |
| 549 |
} |
| 550 |
} |
| 551 |
return m, nil |
| 552 |
} |
| 553 |
|
| 554 |
// RevisionToBytes implements driver.RevisionToBytes. |
| 555 |
func (c *collection) RevisionToBytes(rev any) ([]byte, error) { |
| 556 |
r, ok := rev.(int64) |
| 557 |
if !ok { |
| 558 |
return nil, gcerr.Newf(gcerr.InvalidArgument, nil, "revision %v of type %[1]T is not an int64", rev) |
| 559 |
} |
| 560 |
return strconv.AppendInt(nil, r, 10), nil |
| 561 |
} |
| 562 |
|
| 563 |
// BytesToRevision implements driver.BytesToRevision. |
| 564 |
func (c *collection) BytesToRevision(b []byte) (any, error) { |
| 565 |
return strconv.ParseInt(string(b), 10, 64) |
| 566 |
} |
| 567 |
|
| 568 |
// As implements driver.As. |
| 569 |
func (c *collection) As(i any) bool { return false } |
| 570 |
|
| 571 |
// As implements driver.Collection.ErrorAs. |
| 572 |
func (c *collection) ErrorAs(err error, i any) bool { return false } |
| 573 |
|
| 574 |
// Close implements driver.Collection.Close. |
| 575 |
// If the collection was created with a Filename option, Close writes the |
| 576 |
// collection's documents to the file. |
| 577 |
func (c *collection) Close() error { |
| 578 |
if c.opts.onClose != nil { |
| 579 |
c.opts.onClose() |
| 580 |
} |
| 581 |
return saveDocs(c.opts.Filename, c.docs) |
| 582 |
} |
| 583 |
|
| 584 |
type mapOfDocs = map[any]storedDoc |
| 585 |
|
| 586 |
// Read a map from the filename if is is not empty and the file exists. |
| 587 |
// Otherwise return an empty (not nil) map. |
| 588 |
func loadDocs(filename string) (mapOfDocs, error) { |
| 589 |
if filename == "" { |
| 590 |
return mapOfDocs{}, nil |
| 591 |
} |
| 592 |
f, err := os.Open(filename) |
| 593 |
if err != nil { |
| 594 |
if !os.IsNotExist(err) { |
| 595 |
return nil, err |
| 596 |
} |
| 597 |
// If the file doesn't exist, return an empty map without error. |
| 598 |
return mapOfDocs{}, nil |
| 599 |
} |
| 600 |
defer f.Close() |
| 601 |
var m mapOfDocs |
| 602 |
if err := gob.NewDecoder(f).Decode(&m); err != nil { |
| 603 |
return nil, fmt.Errorf("failed to decode from %q: %v", filename, err) |
| 604 |
} |
| 605 |
return m, nil |
| 606 |
} |
| 607 |
|
| 608 |
// saveDocs saves m to filename if filename is not empty. |
| 609 |
func saveDocs(filename string, m mapOfDocs) error { |
| 610 |
if filename == "" { |
| 611 |
return nil |
| 612 |
} |
| 613 |
f, err := os.Create(filename) |
| 614 |
if err != nil { |
| 615 |
return err |
| 616 |
} |
| 617 |
if err := gob.NewEncoder(f).Encode(m); err != nil { |
| 618 |
_ = f.Close() |
| 619 |
return fmt.Errorf("failed to encode to %q: %v", filename, err) |
| 620 |
} |
| 621 |
return f.Close() |
| 622 |
} |