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/set_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/cluster_commands.rb,
lib/valkey/commands/generic_commands.rb,
lib/valkey/commands/scripting_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::ClusterCommands

#asking, #cluster_addslots, #cluster_addslotsrange, #cluster_bumpepoch, #cluster_count_failure_reports, #cluster_countkeysinslot, #cluster_delslots, #cluster_delslotsrange, #cluster_failover, #cluster_flushslots, #cluster_forget, #cluster_getkeysinslot, #cluster_info, #cluster_keyslot, #cluster_links, #cluster_meet, #cluster_myid, #cluster_myshardid, #cluster_nodes, #cluster_replicas, #cluster_replicate, #cluster_reset, #cluster_saveconfig, #cluster_set_config_epoch, #cluster_setslot, #cluster_shards, #cluster_slaves, #cluster_slots, #readonly, #readwrite

Methods included from Commands::ScriptingCommands

#eval, #evalsha, #invoke_script, #script, #script_exists, #script_flush, #script_kill, #script_load

Methods included from Commands::SetCommands

#sadd, #sadd?, #scard, #sdiff, #sdiffstore, #sinter, #sinterstore, #sismember, #smembers, #smismember, #smove, #spop, #srandmember, #srem, #srem?, #sscan, #sscan_each, #sunion, #sunionstore

Methods included from Commands::SortedSetCommands

#zadd, #zcard, #zcount, #zdiff, #zdiffstore, #zincrby, #zinter, #zinterstore, #zlexcount, #zmscore, #zpopmax, #zpopmin, #zrange, #zrangestore, #zrank, #zrem, #zremrangebyrank, #zremrangebyscore, #zrevrank, #zscan, #zscore, #zunion, #zunionstore

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, #client_caching, #client_get_name, #client_getredir, #client_id, #client_info, #client_kill, #client_kill_simple, #client_list, #client_no_evict, #client_no_touch, #client_pause, #client_reply, #client_set_info, #client_set_name, #client_tracking, #client_tracking_info, #client_unblock, #client_unpause, #config, #config_get, #config_resetstat, #config_rewrite, #config_set, #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.



224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
# File 'lib/valkey.rb', line 224

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

  nodes = options[:nodes] || [{ host: host, port: port }]

  cluster_mode_enabled = options[:cluster_mode] || false

  request = ConnectionRequest::ConnectionRequest.new(
    cluster_mode_enabled: cluster_mode_enabled,
    request_timeout: options[:timeout] || 3.0,
    addresses: nodes.map { |node| ConnectionRequest::NodeAddress.new(host: node[:host], port: node[:port]) }
  )

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

  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)

  # Check if connection was successful
  if res[:conn_ptr].null?
    error_message = res[:connection_error_message]
    raise CannotConnectError, "Failed to connect to cluster: #{error_message}"
  end

  @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!



265
266
267
268
269
270
# File 'lib/valkey.rb', line 265

def close
  return if @connection.nil? || @connection.null?

  Bindings.close_client(@connection)
  @connection = nil
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
175
176
177
178
179
180
181
182
# 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::SETS
      ptr = result[:sets_value]
      count = result[:sets_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::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



184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
# File 'lib/valkey.rb', line 184

def send_command(command_type, command_args = [], &block)
  # Validate connection
  if @connection.nil?
    raise "Connection is nil"
  elsif @connection.null?
    raise "Connection pointer is null"
  elsif @connection.address.zero?
    raise "Connection address is 0"
  end

  channel = 0
  route = ""

  route_buf = FFI::MemoryPointer.from_string(route)

  # Handle empty command_args case
  if command_args.empty?
    arg_ptrs = FFI::MemoryPointer.new(:pointer, 1)
    arg_lens = FFI::MemoryPointer.new(:ulong, 1)
    arg_ptrs.put_pointer(0, FFI::MemoryPointer.new(1))
    arg_lens.put_ulong(0, 0)
  else
    arg_ptrs, arg_lens = build_command_args(command_args)
  end

  res = Bindings.command(
    @connection,
    channel,
    command_type,
    command_args.size,
    arg_ptrs,
    arg_lens,
    route_buf,
    route.bytesize,
    0
  )

  convert_response(res, &block)
end