Adam Sadovsky | 8db7443 | 2015-05-29 17:37:32 -0700 | [diff] [blame^] | 1 | // Copyright 2015 The Vanadium Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style |
| 3 | // license that can be found in the LICENSE file. |
| 4 | |
| 5 | package watchable |
| 6 | |
| 7 | // TODO(sadovsky): Avoid copying back and forth between []byte's and strings. |
| 8 | // We should probably convert incoming strings to []byte's as early as possible, |
| 9 | // and deal exclusively in []byte's internally. |
| 10 | |
| 11 | import ( |
| 12 | "fmt" |
| 13 | "math/rand" |
| 14 | "time" |
| 15 | |
| 16 | "v.io/syncbase/x/ref/services/syncbase/server/util" |
| 17 | "v.io/syncbase/x/ref/services/syncbase/store" |
| 18 | ) |
| 19 | |
| 20 | var rng *rand.Rand = rand.New(rand.NewSource(time.Now().UTC().UnixNano())) |
| 21 | |
| 22 | func makeVersionKey(key []byte) []byte { |
| 23 | return []byte(join(util.VersionPrefix, string(key))) |
| 24 | } |
| 25 | |
| 26 | func makeAtVersionKey(key, version []byte) []byte { |
| 27 | return []byte(join(string(key), string(version))) |
| 28 | } |
| 29 | |
| 30 | func getVersion(st store.StoreReader, key []byte) ([]byte, error) { |
| 31 | return st.Get(makeVersionKey(key), nil) |
| 32 | } |
| 33 | |
| 34 | func getAtVersion(st store.StoreReader, key, valbuf, version []byte) ([]byte, error) { |
| 35 | return st.Get(makeAtVersionKey(key, version), valbuf) |
| 36 | } |
| 37 | |
| 38 | func getVersioned(st store.StoreReader, key, valbuf []byte) ([]byte, error) { |
| 39 | checkTransactionOrSnapshot(st) |
| 40 | version, err := getVersion(st, key) |
| 41 | if err != nil { |
| 42 | return valbuf, err |
| 43 | } |
| 44 | return getAtVersion(st, key, valbuf, version) |
| 45 | } |
| 46 | |
| 47 | func putVersioned(tx store.Transaction, key, value []byte) error { |
| 48 | version := []byte(fmt.Sprintf("%x", rng.Int63())) |
| 49 | if err := tx.Put(makeVersionKey(key), version); err != nil { |
| 50 | return err |
| 51 | } |
| 52 | return tx.Put(makeAtVersionKey(key, version), value) |
| 53 | } |
| 54 | |
| 55 | func deleteVersioned(tx store.Transaction, key []byte) error { |
| 56 | return tx.Delete(makeVersionKey(key)) |
| 57 | } |
| 58 | |
| 59 | func checkTransactionOrSnapshot(st store.StoreReader) { |
| 60 | _, isTransaction := st.(store.Transaction) |
| 61 | _, isSnapshot := st.(store.Snapshot) |
| 62 | if !isTransaction && !isSnapshot { |
| 63 | panic("neither a Transaction nor a Snapshot") |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | func join(parts ...string) string { |
| 68 | return util.JoinKeyParts(parts...) |
| 69 | } |
| 70 | |
| 71 | func split(key string) []string { |
| 72 | return util.SplitKeyParts(key) |
| 73 | } |