microsoft / etcd3

:bookmark: Node.js client for etcd3
https://microsoft.github.io/etcd3/classes/etcd3.html
Other
518 stars 73 forks source link

the result of if() compare condition is wrong #104

Closed klom303 closed 4 years ago

klom303 commented 5 years ago

etcd3 Version: 0.2.13 etcd Version: 3.3.12 nodejs Version: 10.15.3 OS: Ubuntu 18.04

In a transaction, if() support compare condition. In my case, I want to compare Value to a number, but the result is wrong.

const Etcd3 = require('etcd3').Etcd3;

const client = new Etcd3({hosts: ['192.168.142.135:2379']});

(async () => {
  const key = 'test_key';
  const oldValue = 9;
  const newValue = 10;
  await client.put(key).value(oldValue).exec();
  const response = await client.if(key, 'Value', '<', newValue).then(client.put(key).value(newValue)).commit();
  console.log(response);
})();

response

{ responses: [],
  header:
   { cluster_id: '18011104697467366872',
     member_id: '6460912315094810421',
     revision: '583',
     raft_term: '7' },
  succeeded: false }

It seems before the compare step, the number parameter was converted to a string. Is this the correct usage ?

connor4312 commented 5 years ago

How is your number being stored? ETcd uses the byte sort order to compare the values. So the string "100" is less than "7", since the byte for the character 1 comes before 7.

If this is the problem, I'd suggest storing your numbers encoded as big endian integers to make sure the sort is correct.


function store(myValue) {
  const buf = Buffer.alloc(4);
  buf.writeUInt32BE(myValue);
  return client.put(key).value(buf);
}

async function read() {
  const buf = await client.get(key).buffer();
  return buf === null ? null : buf.readUint32BE();
}