2018-07-19 20:11:21 +00:00
|
|
|
// Package mdatastore implements connecting to Google's Datastore service and
|
|
|
|
// simplifying a number of interactions with it.
|
|
|
|
package mdatastore
|
|
|
|
|
|
|
|
import (
|
2019-02-05 20:18:17 +00:00
|
|
|
"context"
|
|
|
|
|
2018-07-19 20:11:21 +00:00
|
|
|
"cloud.google.com/go/datastore"
|
2019-02-03 21:05:33 +00:00
|
|
|
"github.com/mediocregopher/mediocre-go-lib/mctx"
|
2018-07-19 20:11:21 +00:00
|
|
|
"github.com/mediocregopher/mediocre-go-lib/mdb"
|
2019-02-03 21:05:33 +00:00
|
|
|
"github.com/mediocregopher/mediocre-go-lib/merr"
|
2018-07-19 20:11:21 +00:00
|
|
|
"github.com/mediocregopher/mediocre-go-lib/mlog"
|
2019-02-03 21:05:33 +00:00
|
|
|
"github.com/mediocregopher/mediocre-go-lib/mrun"
|
2018-07-19 20:11:21 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// Datastore is a wrapper around a datastore client providing more
|
|
|
|
// functionality.
|
|
|
|
type Datastore struct {
|
|
|
|
*datastore.Client
|
|
|
|
|
|
|
|
gce *mdb.GCE
|
2019-02-05 20:18:17 +00:00
|
|
|
ctx context.Context
|
2018-07-19 20:11:21 +00:00
|
|
|
}
|
|
|
|
|
2019-02-09 19:08:30 +00:00
|
|
|
// WithDatastore returns a Datastore instance which will be initialized and
|
|
|
|
// configured when the start event is triggered on the returned Context (see
|
|
|
|
// mrun.Start). The Datastore instance will have Close called on it when the
|
|
|
|
// stop event is triggered on the returned Context (see mrun.Stop).
|
2019-02-03 21:05:33 +00:00
|
|
|
//
|
|
|
|
// gce is optional and can be passed in if there's an existing gce object which
|
|
|
|
// should be used, otherwise a new one will be created with mdb.MGCE.
|
2019-02-09 19:08:30 +00:00
|
|
|
func WithDatastore(parent context.Context, gce *mdb.GCE) (context.Context, *Datastore) {
|
|
|
|
ctx := mctx.NewChild(parent, "datastore")
|
2019-02-03 21:05:33 +00:00
|
|
|
if gce == nil {
|
2019-02-09 19:08:30 +00:00
|
|
|
ctx, gce = mdb.WithGCE(ctx, "")
|
2019-02-03 21:05:33 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
ds := &Datastore{
|
|
|
|
gce: gce,
|
|
|
|
}
|
|
|
|
|
2019-02-09 19:08:30 +00:00
|
|
|
ctx = mrun.WithStartHook(ctx, func(innerCtx context.Context) error {
|
|
|
|
ds.ctx = mctx.MergeAnnotations(ds.ctx, ds.gce.Context())
|
|
|
|
mlog.Info("connecting to datastore", ds.ctx)
|
2018-07-19 20:11:21 +00:00
|
|
|
var err error
|
2019-02-03 21:05:33 +00:00
|
|
|
ds.Client, err = datastore.NewClient(innerCtx, ds.gce.Project, ds.gce.ClientOptions()...)
|
2019-02-27 18:05:51 +00:00
|
|
|
return merr.Wrap(err, ds.ctx)
|
2019-02-03 21:05:33 +00:00
|
|
|
})
|
2019-02-09 19:08:30 +00:00
|
|
|
ctx = mrun.WithStopHook(ctx, func(context.Context) error {
|
2019-02-03 21:05:33 +00:00
|
|
|
return ds.Client.Close()
|
2018-07-19 20:11:21 +00:00
|
|
|
})
|
2019-02-09 19:08:30 +00:00
|
|
|
ds.ctx = ctx
|
|
|
|
return mctx.WithChild(parent, ctx), ds
|
2018-07-19 20:11:21 +00:00
|
|
|
}
|