github.com/pingcap/tiflow@v0.0.0-20240520035814-5bf52d54e205/engine/pkg/adapter/keyadapter.go (about) 1 // Copyright 2022 PingCAP, Inc. 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 // http://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 // See the License for the specific language governing permissions and 12 // limitations under the License. 13 14 package adapter 15 16 import ( 17 "encoding/hex" 18 "path" 19 "strings" 20 21 "github.com/pingcap/tiflow/pkg/errors" 22 ) 23 24 // Defines all key adapters 25 var ( 26 DMJobKeyAdapter KeyAdapter = keyHexEncoderDecoder("/data-flow/dm/job") 27 DMInfoKeyAdapter KeyAdapter = keyHexEncoderDecoder("/data-flow/dm/info") 28 DMUnitStateAdapter KeyAdapter = keyHexEncoderDecoder("/data-flow/dm/unit-state") 29 DMDroppedColumnsKeyAdapter KeyAdapter = keyHexEncoderDecoder("/data-flow/dm/dropped-columns/") 30 ) 31 32 // KeyAdapter is used to construct etcd like key 33 type KeyAdapter interface { 34 Encode(keys ...string) string 35 Decode(key string) ([]string, error) 36 Path() string 37 Curry(keys ...string) KeyAdapter 38 } 39 40 type keyHexEncoderDecoder string 41 42 func (s keyHexEncoderDecoder) Encode(keys ...string) string { 43 hexKeys := []string{string(s)} 44 for _, key := range keys { 45 hexKeys = append(hexKeys, hex.EncodeToString([]byte(key))) 46 } 47 ret := path.Join(hexKeys...) 48 //if len(keys) < keyAdapterKeysLen(s) { 49 // ret += "/" 50 //} 51 return ret 52 } 53 54 func (s keyHexEncoderDecoder) Decode(key string) ([]string, error) { 55 if key[len(key)-1] == '/' { 56 key = key[:len(key)-1] 57 } 58 v := strings.Split(strings.TrimPrefix(key, string(s)), "/") 59 //if l := keyAdapterKeysLen(s); l != len(v) { 60 // return nil, terror.ErrDecodeEtcdKeyFail.Generate(fmt.Sprintf("decoder is %s, the key is %s", string(s), key)) 61 //} 62 for i, k := range v { 63 dec, err := hex.DecodeString(k) 64 if err != nil { 65 return nil, errors.WrapError(errors.ErrDecodeEtcdKeyFail, err, k) 66 } 67 v[i] = string(dec) 68 } 69 return v, nil 70 } 71 72 func (s keyHexEncoderDecoder) Path() string { 73 return string(s) 74 } 75 76 func (s keyHexEncoderDecoder) Curry(keys ...string) KeyAdapter { 77 prefix := s.Encode(keys...) 78 if prefix[len(prefix)-1] != '/' { 79 prefix += "/" 80 } 81 return keyHexEncoderDecoder(prefix) 82 }