diff --git a/weed/filer/tikv/tikv_store.go b/weed/filer/tikv/tikv_store.go index de6c7e5479..2043c09afc 100644 --- a/weed/filer/tikv/tikv_store.go +++ b/weed/filer/tikv/tikv_store.go @@ -111,8 +111,8 @@ func (store *TikvStore) FindEntry(ctx context.Context, path util.FullPath) (*fil return nil, err } var value []byte = nil - err = txn.RunInTxn(ctx, func(txn *txnkv.KVTxn) error { - val, err := txn.Get(ctx, key) + err = txn.RunInTxn(ctx, func(*txnkv.KVTxn) error { + val, err := txn.get(ctx, key) if err == nil { value = val } @@ -434,6 +434,24 @@ func (w *TxnWrapper) RunInTxn(ctx context.Context, f func(txn *txnkv.KVTxn) erro return err } +// get reads key in the transaction. In a caller's transaction it reads a batch +// of one: the client keeps batch-get answers, misses included, with the +// transaction's snapshot, so a later read of the key does not ask TiKV again. +func (w *TxnWrapper) get(ctx context.Context, key []byte) ([]byte, error) { + if !w.inContext { + return w.KVTxn.Get(ctx, key) + } + values, err := w.KVTxn.BatchGet(ctx, [][]byte{key}) + if err != nil { + return nil, err + } + value, found := values[string(key)] + if !found { + return nil, tikverr.ErrNotExist + } + return value, nil +} + func (store *TikvStore) getTxn(ctx context.Context) (*TxnWrapper, error) { if tx, ok := ctx.Value("tx").(*txnkv.KVTxn); ok { return &TxnWrapper{tx, true}, nil diff --git a/weed/filer/tikv/tikv_store_kv.go b/weed/filer/tikv/tikv_store_kv.go index 966f58b2d4..069f4bbb9d 100644 --- a/weed/filer/tikv/tikv_store_kv.go +++ b/weed/filer/tikv/tikv_store_kv.go @@ -21,8 +21,8 @@ func (store *TikvStore) KvGet(ctx context.Context, key []byte) ([]byte, error) { return nil, err } var data []byte = nil - err = tw.RunInTxn(ctx, func(txn *txnkv.KVTxn) error { - val, err := txn.Get(ctx, key) + err = tw.RunInTxn(ctx, func(*txnkv.KVTxn) error { + val, err := tw.get(ctx, key) if err == nil { data = val } diff --git a/weed/filer/tikv/tikv_store_read_test.go b/weed/filer/tikv/tikv_store_read_test.go new file mode 100644 index 0000000000..b2b2a2d457 --- /dev/null +++ b/weed/filer/tikv/tikv_store_read_test.go @@ -0,0 +1,210 @@ +//go:build tikv + +package tikv + +import ( + "context" + "errors" + "sync/atomic" + "testing" + "time" + + "github.com/tikv/client-go/v2/testutils" + "github.com/tikv/client-go/v2/tikv" + "github.com/tikv/client-go/v2/tikvrpc" + "github.com/tikv/client-go/v2/txnkv" + + "github.com/seaweedfs/seaweedfs/weed/filer" + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/util" +) + +// readCountingClient counts the reads of keys the store sends to TiKV. +type readCountingClient struct { + tikv.Client + reads atomic.Int64 +} + +func (c *readCountingClient) SendRequest(ctx context.Context, addr string, req *tikvrpc.Request, timeout time.Duration) (*tikvrpc.Response, error) { + if req.Type == tikvrpc.CmdGet || req.Type == tikvrpc.CmdBatchGet { + c.reads.Add(1) + } + return c.Client.SendRequest(ctx, addr, req, timeout) +} + +// newReadCountingStore is a store on the client library's in-process TiKV. +func newReadCountingStore(t *testing.T) (*TikvStore, *readCountingClient) { + t.Helper() + client, cluster, pdClient, err := testutils.NewMockTiKV("", nil) + if err != nil { + t.Fatalf("mock tikv: %v", err) + } + testutils.BootstrapWithSingleStore(cluster) + counting := &readCountingClient{} + kvStore, err := tikv.NewTestTiKVStore(client, pdClient, func(c tikv.Client) tikv.Client { + counting.Client = c + return counting + }, nil, 0) + if err != nil { + t.Fatalf("mock tikv store: %v", err) + } + store := &TikvStore{client: &txnkv.Client{KVStore: kvStore}} + t.Cleanup(store.Shutdown) + return store, counting +} + +func testFile(path string, size uint64) *filer.Entry { + return &filer.Entry{ + FullPath: util.FullPath(path), + Attr: filer.Attr{Mode: 0644, Mtime: time.Unix(1700000000, 0), Crtime: time.Unix(1700000000, 0), FileSize: size}, + } +} + +// during runs f and returns the reads of keys it sent to TiKV. +func (c *readCountingClient) during(f func()) int64 { + before := c.reads.Load() + f() + return c.reads.Load() - before +} + +// A rename looks its source up when it starts and again to delete it, and its +// target before the create and in it, all in one transaction. Each of those +// was a request to TiKV for a key the transaction had read already. +func TestTransactionReadsAKeyFromTiKVOnce(t *testing.T) { + store, client := newReadCountingStore(t) + ctx := context.Background() + if err := store.InsertEntry(ctx, testFile("/d/stored", 7)); err != nil { + t.Fatalf("insert: %v", err) + } + if err := store.KvPut(ctx, []byte("stored-key"), []byte("value")); err != nil { + t.Fatalf("kv put: %v", err) + } + + txCtx, err := store.BeginTransaction(ctx) + if err != nil { + t.Fatalf("begin: %v", err) + } + defer store.RollbackTransaction(txCtx) + + if sent := client.during(func() { + for i := 0; i < 3; i++ { + entry, err := store.FindEntry(txCtx, "/d/stored") + if err != nil || entry.FileSize != 7 { + t.Fatalf("find %d: %+v, %v", i, entry, err) + } + } + }); sent != 1 { + t.Errorf("three lookups of one entry sent %d reads to TiKV, want 1", sent) + } + + // a path that is not there is not asked for again either + if sent := client.during(func() { + for i := 0; i < 3; i++ { + if _, err := store.FindEntry(txCtx, "/d/missing"); err != filer_pb.ErrNotFound { + t.Fatalf("find missing %d: %v, want not found", i, err) + } + } + }); sent != 1 { + t.Errorf("three lookups of a missing path sent %d reads to TiKV, want 1", sent) + } + + if sent := client.during(func() { + for i := 0; i < 3; i++ { + if value, err := store.KvGet(txCtx, []byte("stored-key")); err != nil || string(value) != "value" { + t.Fatalf("kv get %d: %q, %v", i, value, err) + } + if _, err := store.KvGet(txCtx, []byte("missing-key")); !errors.Is(err, filer.ErrKvNotFound) { + t.Fatalf("kv get missing %d: %v, want not found", i, err) + } + } + }); sent != 2 { + t.Errorf("three reads each of two keys sent %d reads to TiKV, want 2", sent) + } +} + +// What the transaction reads is what it read before the change: the store as +// it was when the transaction began, under its own writes. +func TestTransactionReadsItsSnapshotUnderItsOwnWrites(t *testing.T) { + store, _ := newReadCountingStore(t) + ctx := context.Background() + for _, path := range []string{"/d/kept", "/d/rewritten", "/d/deleted"} { + if err := store.InsertEntry(ctx, testFile(path, 1)); err != nil { + t.Fatalf("insert %s: %v", path, err) + } + } + + txCtx, err := store.BeginTransaction(ctx) + if err != nil { + t.Fatalf("begin: %v", err) + } + defer store.RollbackTransaction(txCtx) + sizeOf := func(readCtx context.Context, path string) (size uint64, found bool) { + t.Helper() + entry, err := store.FindEntry(readCtx, util.FullPath(path)) + if err == filer_pb.ErrNotFound { + return 0, false + } + if err != nil { + t.Fatalf("find %s: %v", path, err) + } + return entry.FileSize, true + } + for _, path := range []string{"/d/kept", "/d/rewritten", "/d/deleted", "/d/created"} { + sizeOf(txCtx, path) + } + + // the transaction's own writes show in its next read + if err := store.UpdateEntry(txCtx, testFile("/d/rewritten", 2)); err != nil { + t.Fatalf("update: %v", err) + } + if err := store.DeleteEntry(txCtx, "/d/deleted"); err != nil { + t.Fatalf("delete: %v", err) + } + if err := store.InsertEntry(txCtx, testFile("/d/created", 3)); err != nil { + t.Fatalf("insert: %v", err) + } + if size, found := sizeOf(txCtx, "/d/rewritten"); !found || size != 2 { + t.Errorf("an entry the transaction rewrote reads size %d found %v, want its write", size, found) + } + if _, found := sizeOf(txCtx, "/d/deleted"); found { + t.Errorf("an entry the transaction deleted is still read") + } + if size, found := sizeOf(txCtx, "/d/created"); !found || size != 3 { + t.Errorf("an entry the transaction created reads size %d found %v, want its write", size, found) + } + + // another writer's commit shows to a new read, and not to the transaction + if err := store.UpdateEntry(ctx, testFile("/d/kept", 9)); err != nil { + t.Fatalf("update by another writer: %v", err) + } + if size, _ := sizeOf(ctx, "/d/kept"); size != 9 { + t.Errorf("a read outside the transaction reads size %d, want the other writer's 9", size) + } + if size, _ := sizeOf(txCtx, "/d/kept"); size != 1 { + t.Errorf("the transaction reads size %d, want the 1 it began with", size) + } +} + +// A read outside a caller's transaction is a transaction of its own, and +// reads what is stored by then. +func TestReadsOutsideATransactionEachAskTiKV(t *testing.T) { + store, client := newReadCountingStore(t) + ctx := context.Background() + if err := store.InsertEntry(ctx, testFile("/d/f", 1)); err != nil { + t.Fatalf("insert: %v", err) + } + + if sent := client.during(func() { + for size := uint64(1); size <= 3; size++ { + entry, err := store.FindEntry(ctx, "/d/f") + if err != nil || entry.FileSize != size { + t.Fatalf("find: %+v, %v, want size %d", entry, err, size) + } + if err := store.UpdateEntry(ctx, testFile("/d/f", size+1)); err != nil { + t.Fatalf("update: %v", err) + } + } + }); sent != 3 { + t.Errorf("three lookups outside a transaction sent %d reads to TiKV, want 3", sent) + } +}