Class: Valkey

Inherits:
Object
  • Object
show all
Includes:
Commands, PubSubCallback, Utils
Defined in:
lib/valkey.rb,
lib/valkey/utils.rb,
lib/valkey/errors.rb,
lib/valkey/version.rb,
lib/valkey/bindings.rb,
lib/valkey/commands.rb,
lib/valkey/pipeline.rb,
lib/valkey/request_type.rb,
lib/valkey/response_type.rb,
lib/valkey/pubsub_callback.rb,
lib/valkey/request_error_type.rb,
lib/valkey/commands/geo_commands.rb,
lib/valkey/commands/list_commands.rb,
lib/valkey/commands/bitmap_commands.rb,
lib/valkey/commands/server_commands.rb,
lib/valkey/commands/string_commands.rb,
lib/valkey/commands/generic_commands.rb,
lib/valkey/commands/connection_commands.rb,
lib/valkey/commands/sorted_set_commands.rb,
lib/valkey/commands/hyper_log_log_commands.rb

Defined Under Namespace

Modules: Bindings, Commands, PubSubCallback, RequestErrorType, RequestType, ResponseType, Utils Classes: BaseConnectionError, BaseError, CannotConnectError, CommandError, ConnectionError, InheritedError, InvalidClientOptionError, NoScriptError, OutOfMemoryError, PermissionError, Pipeline, ProtocolError, ReadOnlyError, SubscriptionError, TimeoutError, WrongTypeError

Constant Summary collapse

VERSION =
"0.1.0"

Constants included from Utils

Utils::Boolify, Utils::BoolifySet, Utils::Floatify, Utils::FloatifyPair, Utils::FloatifyPairs, Utils::Hashify, Utils::HashifyClusterNodeInfo, Utils::HashifyClusterNodes, Utils::HashifyClusterSlaves, Utils::HashifyClusterSlots, Utils::HashifyInfo, Utils::HashifyStreamAutoclaim, Utils::HashifyStreamAutoclaimJustId, Utils::HashifyStreamEntries, Utils::HashifyStreamPendingDetails, Utils::HashifyStreamPendings, Utils::HashifyStreams, Utils::Noop, Utils::Pairify

Instance Method Summary collapse

Methods included from PubSubCallback

#pubsub_callback

Methods included from Commands::SortedSetCommands

#zadd, #zcard, #zincrby, #zrank, #zrem, #zrevrank, #zscore

Methods included from Commands::HyperLogLogCommands

#pfadd, #pfcount, #pfmerge

Methods included from Commands::GeoCommands

#geoadd, #geodist, #geohash, #geopos, #geosearch, #geosearchstore

Methods included from Commands::ListCommands

#blmove, #blmpop, #blpop, #brpop, #brpoplpush, #lindex, #linsert, #llen, #lmove, #lmpop, #lpop, #lpush, #lpushx, #lrange, #lrem, #lset, #ltrim, #rpop, #rpoplpush, #rpush, #rpushx

Methods included from Commands::BitmapCommands

#bitcount, #bitfield, #bitfield_ro, #bitop, #bitpos, #getbit, #setbit

Methods included from Commands::GenericCommands

#_scan, #copy, #del, #dump, #exists, #exists?, #expire, #expireat, #expiretime, #move, #object, #persist, #pexpire, #pexpireat, #pexpiretime, #pttl, #randomkey, #rename, #renamenx, #restore, #scan, #sort, #touch, #ttl, #type, #unlink, #wait, #waitof

Methods included from Commands::ServerCommands

#bgrewriteaof, #bgsave, #client, #config, #dbsize, #debug, #flushall, #flushdb, #info, #lastsave, #monitor, #save, #shutdown, #slaveof, #slowlog, #sync, #time

Methods included from Commands::ConnectionCommands

#auth, #echo, #ping, #quit, #select

Methods included from Commands::StringCommands

#append, #decr, #decrby, #get, #getdel, #getex, #getrange, #getset, #incr, #incrby, #incrbyfloat, #lcs, #mapped_mget, #mapped_mset, #mapped_msetnx, #mget, #mset, #msetnx, #psetex, #set, #setex, #setnx, #setrange, #strlen

Constructor Details

#initialize(options = {}) ⇒ Valkey

Returns a new instance of Valkey.



199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
# File 'lib/valkey.rb', line 199

def initialize(options = {})
  host = options[:host] || "127.0.0.1"
  port = options[:port] || 6379

  request = ConnectionRequest::ConnectionRequest.new(
    addresses: [ConnectionRequest::NodeAddress.new(host: host, port: port)]
  )

  client_type = Bindings::ClientType.new
  client_type[:tag] = 1 # AsyncClient

  request_str = ConnectionRequest::ConnectionRequest.encode(request)
  request_buf = FFI::MemoryPointer.new(:char, request_str.bytesize)
  request_buf.put_bytes(0, request_str)

  request_len = request_str.bytesize

  response_ptr = Bindings.create_client(
    request_buf,
    request_len,
    client_type,
    method(:pubsub_callback)
  )

  res = Bindings::ConnectionResponse.new(response_ptr)

  @connection = res[:conn_ptr]
end

Instance Method Details

#build_command_args(command_args) ⇒ Object



84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# File 'lib/valkey.rb', line 84

def build_command_args(command_args)
  arg_ptrs = FFI::MemoryPointer.new(:pointer, command_args.size)
  arg_lens = FFI::MemoryPointer.new(:ulong, command_args.size)
  buffers = []

  command_args.each_with_index do |arg, i|
    arg = arg.to_s # Ensure we convert to string

    buf = FFI::MemoryPointer.from_string(arg.to_s)
    buffers << buf # prevent garbage collection
    arg_ptrs.put_pointer(i * FFI::Pointer.size, buf)
    arg_lens.put_ulong(i * 8, arg.bytesize)
  end

  [arg_ptrs, arg_lens]
end

#closeObject Also known as: disconnect!



228
229
230
# File 'lib/valkey.rb', line 228

def close
  Bindings.close_client(@connection)
end

#convert_response(res, &block) ⇒ Object



101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
# File 'lib/valkey.rb', line 101

def convert_response(res, &block)
  result = Bindings::CommandResult.new(res)

  if result[:response].null?
    error = result[:command_error]

    case error[:command_error_type]
    when RequestErrorType::EXECABORT, RequestErrorType::UNSPECIFIED
      raise CommandError, error[:command_error_message]
    when RequestErrorType::TIMEOUT
      raise TimeoutError, error[:command_error_message]
    when RequestErrorType::DISCONNECT
      raise ConnectionError, error[:command_error_message]
    else
      raise "Unknown error type: #{error[:command_error_type]}"
    end
  end

  result = result[:response]

  convert_response = lambda { |result|
    # TODO: handle all types of responses
    case result[:response_type]
    when ResponseType::STRING
      result[:string_value].read_string(result[:string_value_len])
    when ResponseType::INT
      result[:int_value]
    when ResponseType::FLOAT
      result[:float_value]
    when ResponseType::BOOL
      result[:bool_value]
    when ResponseType::ARRAY
      ptr = result[:array_value]
      count = result[:array_value_len].to_i

      Array.new(count) do |i|
        item = Bindings::CommandResponse.new(ptr + i * Bindings::CommandResponse.size)
        convert_response.call(item)
      end
    when ResponseType::MAP
      return nil if result[:array_value].null?

      ptr = result[:array_value]
      count = result[:array_value_len].to_i
      map = {}

      Array.new(count) do |i|
        item = Bindings::CommandResponse.new(ptr + i * Bindings::CommandResponse.size)

        map_key = convert_response.call(Bindings::CommandResponse.new(item[:map_key]))
        map_value = convert_response.call(Bindings::CommandResponse.new(item[:map_value]))

        map[map_key] = map_value
      end

      # technically it has to return a Hash, but as of now we return just one pair
      map.to_a.flatten(1) # Flatten to get pairs
    when ResponseType::NULL
      nil
    when ResponseType::OK
      "OK"
    else
      raise "Unsupported response type: #{result[:response_type]}"
    end
  }

  response = convert_response.call(result)

  if block_given?
    block.call(response)
  else
    response
  end
end

#pipelined(exception: true) {|pipeline| ... } ⇒ Object

Yields:

  • (pipeline)


25
26
27
28
29
30
31
32
33
# File 'lib/valkey.rb', line 25

def pipelined(exception: true)
  pipeline = Pipeline.new

  yield pipeline

  return if pipeline.commands.empty?

  send_batch_commands(pipeline.commands, exception: exception)
end

#send_batch_commands(commands, exception: true) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/valkey.rb', line 35

def send_batch_commands(commands, exception: true)
  cmds = []
  blocks = []

  commands.each do |command_type, command_args, block|
    arg_ptrs, arg_lens = build_command_args(command_args)

    cmd = Bindings::CmdInfo.new
    cmd[:request_type] = command_type
    cmd[:args] = arg_ptrs
    cmd[:arg_count] = command_args.size
    cmd[:args_len] = arg_lens

    cmds << cmd
    blocks << block
  end

  batch_info = Bindings::BatchInfo.new
  batch_info[:cmd_count] = cmds.size
  batch_info[:cmds] = FFI::MemoryPointer.new(Bindings::CmdInfo, cmds.size)

  cmds.each_with_index do |cmd, i|
    batch_info[:cmds].put_pointer(i * Bindings::CmdInfo.size, cmd.to_ptr)
  end

  batch_options = Bindings::BatchOptionsInfo.new
  batch_options[:retry_server_error] = true
  batch_options[:retry_connection_error] = true
  batch_options[:has_timeout] = false
  batch_options[:timeout] = 0 # No timeout

  res = Bindings.batch(
    @connection, # Assuming @connection is set after create
    0,
    batch_info,
    exception,
    batch_options,
    0
  )

  results = convert_response(res)

  blocks.each_with_index do |block, i|
    results[i] = block.call(results[i]) if block
  end

  results
end

#send_command(command_type, command_args = [], &block) ⇒ Object



176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
# File 'lib/valkey.rb', line 176

def send_command(command_type, command_args = [], &block)
  channel = 0
  route = ""

  route_buf = FFI::MemoryPointer.from_string(route)

  arg_ptrs, arg_lens = build_command_args(command_args)

  res = Bindings.command(
    @connection, # Assuming @connection is set after create
    channel,
    command_type,
    command_args.size,
    arg_ptrs,
    arg_lens,
    route_buf,
    route.bytesize,
    0
  )

  convert_response(res, &block)
end