From 1db045bce379173c5826f1ce72332dd85fed2836 Mon Sep 17 00:00:00 2001 From: Gervasio Marchand Date: Mon, 4 Nov 2019 09:49:54 -0300 Subject: [PATCH] MM-16822 - Implement KVSetWithOptions (#11818) * Add SetWithOptions * Avoid passing two structs to the functions * Rename ExpiryInSeconds -> ExpireInSeconds * Use t.Run for the tests * Fix build * Address feedback * Update log message * Update docs and use KVSetWithOptions in KVCompareAndSetJSON * Improve code style * Use struct instead of pointer to struct * Fix minimum server versions * Update documentation * Address feedback * Revert new implemention of kv helpers * Adress feedback --- app/plugin_api.go | 4 + app/plugin_key_value_store.go | 44 ++++---- app/plugin_test.go | 146 ++++++++++++++++++++++++++- i18n/en.json | 8 ++ model/plugin_kvset_options.go | 77 ++++++++++++++ plugin/api.go | 9 ++ plugin/client_rpc_generated.go | 31 ++++++ plugin/helpers.go | 6 ++ plugin/helpers_kv.go | 44 ++++---- plugin/plugintest/api.go | 73 +++++++++----- store/sqlstore/plugin_store.go | 31 +++++- store/store.go | 1 + store/storetest/mocks/PluginStore.go | 23 +++++ 13 files changed, 420 insertions(+), 77 deletions(-) create mode 100644 model/plugin_kvset_options.go diff --git a/app/plugin_api.go b/app/plugin_api.go index d228a88d0d..1aaced6823 100644 --- a/app/plugin_api.go +++ b/app/plugin_api.go @@ -695,6 +695,10 @@ func (api *PluginAPI) InstallPlugin(file io.Reader, replace bool) (*model.Manife // KV Store Section +func (api *PluginAPI) KVSetWithOptions(key string, value interface{}, options model.PluginKVSetOptions) (bool, *model.AppError) { + return api.app.SetPluginKeyWithOptions(api.id, key, value, options) +} + func (api *PluginAPI) KVSet(key string, value []byte) *model.AppError { return api.app.SetPluginKey(api.id, key, value) } diff --git a/app/plugin_key_value_store.go b/app/plugin_key_value_store.go index 6bff32c3dd..8599f7e679 100644 --- a/app/plugin_key_value_store.go +++ b/app/plugin_key_value_store.go @@ -23,40 +23,30 @@ func (a *App) SetPluginKey(pluginId string, key string, value []byte) *model.App } func (a *App) SetPluginKeyWithExpiry(pluginId string, key string, value []byte, expireInSeconds int64) *model.AppError { - if expireInSeconds > 0 { - expireInSeconds = model.GetMillis() + (expireInSeconds * 1000) + options := model.PluginKVSetOptions{ + ExpireInSeconds: expireInSeconds, } - - kv := &model.PluginKeyValue{ - PluginId: pluginId, - Key: key, - Value: value, - ExpireAt: expireInSeconds, - } - - if _, err := a.Srv.Store.Plugin().SaveOrUpdate(kv); err != nil { - mlog.Error("Failed to set plugin key value", mlog.String("plugin_id", pluginId), mlog.String("key", key), mlog.Err(err)) - return err - } - - // Clean up a previous entry using the hashed key, if it exists. - if err := a.Srv.Store.Plugin().Delete(pluginId, getKeyHash(key)); err != nil { - mlog.Error("Failed to clean up previously hashed plugin key value", mlog.String("plugin_id", pluginId), mlog.String("key", key), mlog.Err(err)) - } - - return nil + _, err := a.SetPluginKeyWithOptions(pluginId, key, value, options) + return err } func (a *App) CompareAndSetPluginKey(pluginId string, key string, oldValue, newValue []byte) (bool, *model.AppError) { - kv := &model.PluginKeyValue{ - PluginId: pluginId, - Key: key, - Value: newValue, + options := model.PluginKVSetOptions{ + Atomic: true, + OldValue: oldValue, + } + return a.SetPluginKeyWithOptions(pluginId, key, newValue, options) +} + +func (a *App) SetPluginKeyWithOptions(pluginId string, key string, value interface{}, options model.PluginKVSetOptions) (bool, *model.AppError) { + if err := options.IsValid(); err != nil { + mlog.Error("Failed to set plugin key value with options", mlog.String("plugin_id", pluginId), mlog.String("key", key), mlog.Err(err)) + return false, err } - updated, err := a.Srv.Store.Plugin().CompareAndSet(kv, oldValue) + updated, err := a.Srv.Store.Plugin().SetWithOptions(pluginId, key, value, options) if err != nil { - mlog.Error("Failed to compare and set plugin key value", mlog.String("plugin_id", pluginId), mlog.String("key", key), mlog.Err(err)) + mlog.Error("Failed to set plugin key value with options", mlog.String("plugin_id", pluginId), mlog.String("key", key), mlog.Err(err)) return updated, err } diff --git a/app/plugin_test.go b/app/plugin_test.go index c505917bea..aa2f5654ac 100644 --- a/app/plugin_test.go +++ b/app/plugin_test.go @@ -16,11 +16,12 @@ import ( "testing" "github.com/gorilla/mux" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "github.com/mattermost/mattermost-server/model" "github.com/mattermost/mattermost-server/plugin" "github.com/mattermost/mattermost-server/utils/fileutils" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" ) func getHashedKey(key string) string { @@ -186,6 +187,147 @@ func TestPluginKeyValueStoreCompareAndSet(t *testing.T) { assert.Equal(t, []byte("test2"), ret) } +func TestPluginKeyValueStoreSetWithOptionsJSON(t *testing.T) { + th := Setup(t).InitBasic() + defer th.TearDown() + + pluginId := "testpluginid" + + defer func() { + assert.Nil(t, th.App.DeletePluginKey(pluginId, "key")) + }() + + t.Run("fails with a non-serializable object as the new value", func(t *testing.T) { + result, err := th.App.SetPluginKeyWithOptions(pluginId, "key", func() {}, model.PluginKVSetOptions{ + EncodeJSON: true, + }) + assert.False(t, result) + assert.NotNil(t, err) + + // verify that after the failure it was not set + ret, err := th.App.GetPluginKey(pluginId, "key") + assert.Nil(t, err) + assert.Equal(t, []byte(nil), ret) + }) + + t.Run("fails with a non-serializable object as the old value", func(t *testing.T) { + result, err := th.App.SetPluginKeyWithOptions(pluginId, "key", map[string]interface{}{ + "val-a": 10, + }, model.PluginKVSetOptions{ + EncodeJSON: true, + Atomic: true, + OldValue: func() {}, + }) + assert.False(t, result) + assert.NotNil(t, err) + + // verify that after the failure it was not set + ret, err := th.App.GetPluginKey(pluginId, "key") + assert.Nil(t, err) + assert.Equal(t, []byte(nil), ret) + }) + + t.Run("storing a value json encoded works", func(t *testing.T) { + result, err := th.App.SetPluginKeyWithOptions(pluginId, "key", map[string]interface{}{ + "val-a": 10, + }, model.PluginKVSetOptions{ + EncodeJSON: true, + }) + assert.True(t, result) + assert.Nil(t, err) + + // and I can get it back! + ret, err := th.App.GetPluginKey(pluginId, "key") + assert.Nil(t, err) + assert.Equal(t, []byte(`{"val-a":10}`), ret) + }) + + t.Run("test that setting it atomic when it doesn't match doesn't change anything", func(t *testing.T) { + result, err := th.App.SetPluginKeyWithOptions(pluginId, "key", map[string]interface{}{ + "val-a": 30, + }, model.PluginKVSetOptions{ + EncodeJSON: true, + Atomic: true, + OldValue: map[string]interface{}{ + "val-a": 20, + }, + }) + assert.False(t, result) + assert.Nil(t, err) + + // test that the value didn't change + ret, err := th.App.GetPluginKey(pluginId, "key") + assert.Nil(t, err) + assert.Equal(t, []byte(`{"val-a":10}`), ret) + }) + + t.Run("test the atomic change with the proper old value", func(t *testing.T) { + result, err := th.App.SetPluginKeyWithOptions(pluginId, "key", map[string]interface{}{ + "val-a": 30, + }, model.PluginKVSetOptions{ + EncodeJSON: true, + Atomic: true, + OldValue: map[string]interface{}{ + "val-a": 10, + }, + }) + assert.True(t, result) + assert.Nil(t, err) + + // test that the value did change + ret, err := th.App.GetPluginKey(pluginId, "key") + assert.Nil(t, err) + assert.Equal(t, []byte(`{"val-a":30}`), ret) + }) +} + +func TestPluginKeyValueStoreSetWithOptionsByteArray(t *testing.T) { + th := Setup(t).InitBasic() + defer th.TearDown() + + pluginId := "testpluginid" + + defer func() { + assert.Nil(t, th.App.DeletePluginKey(pluginId, "key")) + }() + + // storing a value works + result, err := th.App.SetPluginKeyWithOptions(pluginId, "key", []byte(`myvalue`), model.PluginKVSetOptions{}) + assert.True(t, result) + assert.Nil(t, err) + + // and I can get it back! + ret, err := th.App.GetPluginKey(pluginId, "key") + assert.Nil(t, err) + assert.Equal(t, []byte(`myvalue`), ret) + + // test that setting it atomic when it doesn't match doesn't change anything + result, err = th.App.SetPluginKeyWithOptions(pluginId, "key", []byte(`newvalue`), model.PluginKVSetOptions{ + Atomic: true, + OldValue: []byte(`differentvalue`), + }) + assert.False(t, result) + assert.Nil(t, err) + + // test that the value didn't change + ret, err = th.App.GetPluginKey(pluginId, "key") + assert.Nil(t, err) + assert.Equal(t, []byte(`myvalue`), ret) + + // now do the atomic change with the proper old value + result, err = th.App.SetPluginKeyWithOptions(pluginId, "key", []byte(`newvalue`), model.PluginKVSetOptions{ + Atomic: true, + OldValue: []byte(`myvalue`), + }) + assert.True(t, result) + assert.Nil(t, err) + + // test that the value did change + ret, err = th.App.GetPluginKey(pluginId, "key") + assert.Nil(t, err) + assert.Equal(t, []byte(`newvalue`), ret) +} + func TestServePluginRequest(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() diff --git a/i18n/en.json b/i18n/en.json index 27478cae3b..c20c213a7f 100644 --- a/i18n/en.json +++ b/i18n/en.json @@ -5154,6 +5154,14 @@ "id": "model.plugin_key_value.is_valid.plugin_id.app_error", "translation": "Invalid plugin ID, must be more than {{.Min}} and a of maximum {{.Max}} characters long." }, + { + "id": "model.plugin_kvset_options.is_valid.old_value.app_error", + "translation": "Invalid old value, it shouldn't be set when the operation is not atomic." + }, + { + "id": "model.plugin_kvset_options.serialize_value.app_error", + "translation": "Could not deserialize a value. EncodeJSON: {{.EncodeJSON}}." + }, { "id": "model.post.is_valid.channel_id.app_error", "translation": "Invalid channel id" diff --git a/model/plugin_kvset_options.go b/model/plugin_kvset_options.go new file mode 100644 index 0000000000..6498fa4b9e --- /dev/null +++ b/model/plugin_kvset_options.go @@ -0,0 +1,77 @@ +// Copyright (c) 2017-present Mattermost, Inc. All Rights Reserved. +// See License.txt for license information. + +package model + +import ( + "encoding/json" + "net/http" +) + +// PluginKVSetOptions contains information on how to store a value in the plugin KV store. +type PluginKVSetOptions struct { + EncodeJSON bool // If true, store the JSON encoding of newValue + Atomic bool // Only store the value if the current value matches the oldValue + OldValue interface{} // The value to compare with the current value. Only used when Atomic is true + ExpireInSeconds int64 // Set an expire counter +} + +// IsValid returns nil if the chosen options are valid. +func (opt *PluginKVSetOptions) IsValid() *AppError { + if !opt.Atomic && opt.OldValue != nil { + return NewAppError( + "PluginKVSetOptions.IsValid", + "model.plugin_kvset_options.is_valid.old_value.app_error", + nil, + "", + http.StatusBadRequest, + ) + } + + return nil +} + +// GetOldValueSerialized returns the serialized old value either as directly +// or encoded as JSON depending on the chosen options. +func (opt *PluginKVSetOptions) GetOldValueSerialized() ([]byte, *AppError) { + return opt.serializeValue(opt.OldValue) +} + +func (opt *PluginKVSetOptions) serializeValue(value interface{}) ([]byte, *AppError) { + if opt.EncodeJSON { + data, err := json.Marshal(value) + if err != nil { + return nil, NewAppError("PluginKVSetOptions.serializeValue", "model.plugin_kvset_options.serialize_value.app_error", map[string]interface{}{"EncodeJSON": opt.EncodeJSON}, "Could not serialize JSON value", http.StatusBadRequest) + } + return data, nil + } + + castResult, ok := value.([]byte) + if !ok { + return nil, NewAppError("PluginKVSetOptions.SerializeValue", "model.plugin_kvset_options.serialize_value.app_error", map[string]interface{}{"EncodeJSON": opt.EncodeJSON}, "Could not cast value to []byte", http.StatusBadRequest) + } + + return castResult, nil +} + +// NewPluginKeyValueFromOptions return a PluginKeyValue given a pluginID, a KV pair and options. +func NewPluginKeyValueFromOptions(pluginId, key string, value interface{}, opt PluginKVSetOptions) (*PluginKeyValue, *AppError) { + serializedValue, err := opt.serializeValue(value) + if err != nil { + return nil, err + } + + expireAt := int64(0) + if opt.ExpireInSeconds > 0 { + expireAt = GetMillis() + (opt.ExpireInSeconds * 1000) + } + + kv := &PluginKeyValue{ + PluginId: pluginId, + Key: key, + Value: serializedValue, + ExpireAt: expireAt, + } + + return kv, nil +} diff --git a/plugin/api.go b/plugin/api.go index 6a2ce229c3..7c7a665efa 100644 --- a/plugin/api.go +++ b/plugin/api.go @@ -612,6 +612,15 @@ type API interface { // Minimum server version: 5.16 KVCompareAndDelete(key string, oldValue []byte) (bool, *model.AppError) + // KVSetWithOptions stores a key-value pair, unique per plugin, according to the given options. + // If options.EncodeJSON is not true, the type of newValue must be of type []byte. + // Returns (false, err) if DB error occurred + // Returns (false, nil) if the value was not set + // Returns (true, nil) if the value was set + // + // Minimum server version: 5.18 + KVSetWithOptions(key string, newValue interface{}, options model.PluginKVSetOptions) (bool, *model.AppError) + // KVSet stores a key-value pair with an expiry time, unique per plugin. // // Minimum server version: 5.6 diff --git a/plugin/client_rpc_generated.go b/plugin/client_rpc_generated.go index 37e6587321..67543f50cc 100644 --- a/plugin/client_rpc_generated.go +++ b/plugin/client_rpc_generated.go @@ -3727,6 +3727,37 @@ func (s *apiRPCServer) KVCompareAndDelete(args *Z_KVCompareAndDeleteArgs, return return nil } +type Z_KVSetWithOptionsArgs struct { + A string + B interface{} + C model.PluginKVSetOptions +} + +type Z_KVSetWithOptionsReturns struct { + A bool + B *model.AppError +} + +func (g *apiRPCClient) KVSetWithOptions(key string, newValue interface{}, options model.PluginKVSetOptions) (bool, *model.AppError) { + _args := &Z_KVSetWithOptionsArgs{key, newValue, options} + _returns := &Z_KVSetWithOptionsReturns{} + if err := g.client.Call("Plugin.KVSetWithOptions", _args, _returns); err != nil { + log.Printf("RPC call to KVSetWithOptions API failed: %s", err.Error()) + } + return _returns.A, _returns.B +} + +func (s *apiRPCServer) KVSetWithOptions(args *Z_KVSetWithOptionsArgs, returns *Z_KVSetWithOptionsReturns) error { + if hook, ok := s.impl.(interface { + KVSetWithOptions(key string, newValue interface{}, options model.PluginKVSetOptions) (bool, *model.AppError) + }); ok { + returns.A, returns.B = hook.KVSetWithOptions(args.A, args.B, args.C) + } else { + return encodableError(fmt.Errorf("API KVSetWithOptions called but not implemented.")) + } + return nil +} + type Z_KVSetWithExpiryArgs struct { A string B []byte diff --git a/plugin/helpers.go b/plugin/helpers.go index 94d66c0683..726741ad68 100644 --- a/plugin/helpers.go +++ b/plugin/helpers.go @@ -14,6 +14,8 @@ type Helpers interface { // KVSetJSON stores a key-value pair, unique per plugin, marshalling the given value as a JSON string. // + // Deprecated: Use p.API.KVSetWithOptions instead. + // // Minimum server version: 5.2 KVSetJSON(key string, value interface{}) error @@ -23,6 +25,8 @@ type Helpers interface { // Returns (false, nil) if current value != oldValue or key already exists when inserting // Returns (true, nil) if current value == oldValue or new key is inserted // + // Deprecated: Use p.API.KVSetWithOptions instead. + // // Minimum server version: 5.12 KVCompareAndSetJSON(key string, oldValue interface{}, newValue interface{}) (bool, error) @@ -41,6 +45,8 @@ type Helpers interface { // KVSetWithExpiryJSON stores a key-value pair with an expiry time, unique per plugin, marshalling the given value as a JSON string. // + // Deprecated: Use p.API.KVSetWithOptions instead. + // // Minimum server version: 5.6 KVSetWithExpiryJSON(key string, value interface{}, expireInSeconds int64) error } diff --git a/plugin/helpers_kv.go b/plugin/helpers_kv.go index 78efa31467..9b054502e2 100644 --- a/plugin/helpers_kv.go +++ b/plugin/helpers_kv.go @@ -9,25 +9,7 @@ import ( "github.com/pkg/errors" ) -// KVGetJSON is a wrapper around KVGet to simplify reading a JSON object from the key value store. -func (p *HelpersImpl) KVGetJSON(key string, value interface{}) (bool, error) { - data, appErr := p.API.KVGet(key) - if appErr != nil { - return false, appErr - } - if data == nil { - return false, nil - } - - err := json.Unmarshal(data, value) - if err != nil { - return false, err - } - - return true, nil -} - -// KVSetJSON is a wrapper around KVSet to simplify writing a JSON object to the key value store. +// KVSetJSON implements Helpers.KVSetJSON. func (p *HelpersImpl) KVSetJSON(key string, value interface{}) error { data, err := json.Marshal(value) if err != nil { @@ -42,7 +24,7 @@ func (p *HelpersImpl) KVSetJSON(key string, value interface{}) error { return nil } -// KVCompareAndSetJSON is a wrapper around KVCompareAndSet to simplify atomically writing a JSON object to the key value store. +// KVCompareAndSetJSON implements Helpers.KVCompareAndSetJSON. func (p *HelpersImpl) KVCompareAndSetJSON(key string, oldValue interface{}, newValue interface{}) (bool, error) { var oldData, newData []byte var err error @@ -69,7 +51,7 @@ func (p *HelpersImpl) KVCompareAndSetJSON(key string, oldValue interface{}, newV return set, nil } -// KVCompareAndDeleteJSON is a wrapper around KVCompareAndDelete to simplify atomically deleting a JSON object from the key value store. +// KVCompareAndDeleteJSON implements Helpers.KVCompareAndDeleteJSON. func (p *HelpersImpl) KVCompareAndDeleteJSON(key string, oldValue interface{}) (bool, error) { var oldData []byte var err error @@ -89,7 +71,25 @@ func (p *HelpersImpl) KVCompareAndDeleteJSON(key string, oldValue interface{}) ( return deleted, nil } -// KVSetWithExpiryJSON is a wrapper around KVSetWithExpiry to simplify atomically writing a JSON object with expiry to the key value store. +// KVGetJSON implements Helpers.KVGetJSON. +func (p *HelpersImpl) KVGetJSON(key string, value interface{}) (bool, error) { + data, appErr := p.API.KVGet(key) + if appErr != nil { + return false, appErr + } + if data == nil { + return false, nil + } + + err := json.Unmarshal(data, value) + if err != nil { + return false, err + } + + return true, nil +} + +// KVSetWithExpiryJSON implements Helpers.KVSetWithExpiryJSON. func (p *HelpersImpl) KVSetWithExpiryJSON(key string, value interface{}, expireInSeconds int64) error { data, err := json.Marshal(value) if err != nil { diff --git a/plugin/plugintest/api.go b/plugin/plugintest/api.go index 4db7d5e5e2..81c8eb44d3 100644 --- a/plugin/plugintest/api.go +++ b/plugin/plugintest/api.go @@ -2023,6 +2023,31 @@ func (_m *API) HasPermissionToTeam(userId string, teamId string, permission *mod return r0 } +// InstallPlugin provides a mock function with given fields: file, replace +func (_m *API) InstallPlugin(file io.Reader, replace bool) (*model.Manifest, *model.AppError) { + ret := _m.Called(file, replace) + + var r0 *model.Manifest + if rf, ok := ret.Get(0).(func(io.Reader, bool) *model.Manifest); ok { + r0 = rf(file, replace) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*model.Manifest) + } + } + + var r1 *model.AppError + if rf, ok := ret.Get(1).(func(io.Reader, bool) *model.AppError); ok { + r1 = rf(file, replace) + } else { + if ret.Get(1) != nil { + r1 = ret.Get(1).(*model.AppError) + } + } + + return r0, r1 +} + // KVCompareAndDelete provides a mock function with given fields: key, oldValue func (_m *API) KVCompareAndDelete(key string, oldValue []byte) (bool, *model.AppError) { ret := _m.Called(key, oldValue) @@ -2183,6 +2208,29 @@ func (_m *API) KVSetWithExpiry(key string, value []byte, expireInSeconds int64) return r0 } +// KVSetWithOptions provides a mock function with given fields: key, newValue, options +func (_m *API) KVSetWithOptions(key string, newValue interface{}, options model.PluginKVSetOptions) (bool, *model.AppError) { + ret := _m.Called(key, newValue, options) + + var r0 bool + if rf, ok := ret.Get(0).(func(string, interface{}, model.PluginKVSetOptions) bool); ok { + r0 = rf(key, newValue, options) + } else { + r0 = ret.Get(0).(bool) + } + + var r1 *model.AppError + if rf, ok := ret.Get(1).(func(string, interface{}, model.PluginKVSetOptions) *model.AppError); ok { + r1 = rf(key, newValue, options) + } else { + if ret.Get(1) != nil { + r1 = ret.Get(1).(*model.AppError) + } + } + + return r0, r1 +} + // LoadPluginConfiguration provides a mock function with given fields: dest func (_m *API) LoadPluginConfiguration(dest interface{}) error { ret := _m.Called(dest) @@ -2885,28 +2933,3 @@ func (_m *API) UploadFile(data []byte, channelId string, filename string) (*mode return r0, r1 } - -// InstallPlugin provides a mock function with given fields: file, replace -func (_m *API) InstallPlugin(file io.Reader, replace bool) (*model.Manifest, *model.AppError) { - ret := _m.Called(file, replace) - - var r0 *model.Manifest - if rf, ok := ret.Get(0).(func(io.Reader, bool) *model.Manifest); ok { - r0 = rf(file, replace) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*model.Manifest) - } - } - - var r1 *model.AppError - if rf, ok := ret.Get(1).(func(io.Reader, bool) *model.AppError); ok { - r1 = rf(file, replace) - } else { - if ret.Get(1) != nil { - r1 = ret.Get(1).(*model.AppError) - } - } - - return r0, r1 -} diff --git a/store/sqlstore/plugin_store.go b/store/sqlstore/plugin_store.go index 4d2f00a2d8..3c4d61d1ec 100644 --- a/store/sqlstore/plugin_store.go +++ b/store/sqlstore/plugin_store.go @@ -91,12 +91,13 @@ func (ps SqlPluginStore) CompareAndSet(kv *model.PluginKeyValue, oldValue []byte } else { // Update if oldValue is not nil updateResult, err := ps.GetMaster().Exec( - `UPDATE PluginKeyValueStore SET PValue = :New WHERE PluginId = :PluginId AND PKey = :Key AND PValue = :Old`, + `UPDATE PluginKeyValueStore SET PValue = :New, ExpireAt = :ExpireAt WHERE PluginId = :PluginId AND PKey = :Key AND PValue = :Old`, map[string]interface{}{ "PluginId": kv.PluginId, "Key": kv.Key, "Old": oldValue, "New": kv.Value, + "ExpireAt": kv.ExpireAt, }, ) if err != nil { @@ -147,6 +148,34 @@ func (ps SqlPluginStore) CompareAndDelete(kv *model.PluginKeyValue, oldValue []b return true, nil } +func (ps SqlPluginStore) SetWithOptions(pluginId string, key string, value interface{}, opt model.PluginKVSetOptions) (bool, *model.AppError) { + if err := opt.IsValid(); err != nil { + return false, err + } + + kv, err := model.NewPluginKeyValueFromOptions(pluginId, key, value, opt) + if err != nil { + return false, err + } + + if opt.Atomic { + var serializedOldValue []byte + serializedOldValue, err = opt.GetOldValueSerialized() + if err != nil { + return false, err + } + + return ps.CompareAndSet(kv, serializedOldValue) + } + + savedKv, err := ps.SaveOrUpdate(kv) + if err != nil { + return false, err + } + + return savedKv != nil, nil +} + func (ps SqlPluginStore) Get(pluginId, key string) (*model.PluginKeyValue, *model.AppError) { var kv *model.PluginKeyValue currentTime := model.GetMillis() diff --git a/store/store.go b/store/store.go index 26fb519a7e..59ef9f693e 100644 --- a/store/store.go +++ b/store/store.go @@ -528,6 +528,7 @@ type PluginStore interface { SaveOrUpdate(keyVal *model.PluginKeyValue) (*model.PluginKeyValue, *model.AppError) CompareAndSet(keyVal *model.PluginKeyValue, oldValue []byte) (bool, *model.AppError) CompareAndDelete(keyVal *model.PluginKeyValue, oldValue []byte) (bool, *model.AppError) + SetWithOptions(pluginId string, key string, value interface{}, options model.PluginKVSetOptions) (bool, *model.AppError) Get(pluginId, key string) (*model.PluginKeyValue, *model.AppError) Delete(pluginId, key string) *model.AppError DeleteAllForPlugin(PluginId string) *model.AppError diff --git a/store/storetest/mocks/PluginStore.go b/store/storetest/mocks/PluginStore.go index 54812a66a6..71a19c4fb7 100644 --- a/store/storetest/mocks/PluginStore.go +++ b/store/storetest/mocks/PluginStore.go @@ -182,3 +182,26 @@ func (_m *PluginStore) SaveOrUpdate(keyVal *model.PluginKeyValue) (*model.Plugin return r0, r1 } + +// SetWithOptions provides a mock function with given fields: pluginId, key, value, options +func (_m *PluginStore) SetWithOptions(pluginId string, key string, value interface{}, options model.PluginKVSetOptions) (bool, *model.AppError) { + ret := _m.Called(pluginId, key, value, options) + + var r0 bool + if rf, ok := ret.Get(0).(func(string, string, interface{}, model.PluginKVSetOptions) bool); ok { + r0 = rf(pluginId, key, value, options) + } else { + r0 = ret.Get(0).(bool) + } + + var r1 *model.AppError + if rf, ok := ret.Get(1).(func(string, string, interface{}, model.PluginKVSetOptions) *model.AppError); ok { + r1 = rf(pluginId, key, value, options) + } else { + if ret.Get(1) != nil { + r1 = ret.Get(1).(*model.AppError) + } + } + + return r0, r1 +}