Class: Couchbase::Bucket

Inherits:
Object
  • Object
show all
Defined in:
ext/couchbase_ext/couchbase_ext.c,
lib/couchbase/bucket.rb

Overview

This class in charge of all stuff connected to communication with Couchbase.

Since:

  • 1.0.0

Instance Method Summary collapse

Instance Method Details

#cas(key, options = {}) {|value| ... } ⇒ Fixnum Also known as: compare_and_swap

Compare and swap value.

Reads a key's value from the server and yields it to a block. Replaces the key's value with the result of the block as long as the key hasn't been updated in the meantime, otherwise raises Error::KeyExists. CAS stands for “compare and swap”, and avoids the need for manual key mutexing. Read more info here:

In asynchronous mode it will yield result twice, first for Bucket#get with Result#operation equal to :get and second time for Bucket#set with Result#operation equal to :set.

Setting the :retry option to a positive number will cause this method to rescue the Error::KeyExists error that happens when an update collision is detected, and automatically get a fresh copy of the value and retry the block. This will repeat as long as there continues to be conflicts, up to the maximum number of retries specified. For asynchronous mode, this means the block will be yielded once for the initial Bucket#get, once for the final Bucket#set (successful or last failure), and zero or more additional Bucket#get retries in between, up to the maximum allowed by the :retry option.

Examples:

Implement append to JSON encoded value


c.default_format = :document
c.set("foo", {"bar" => 1})
c.cas("foo") do |val|
  val["baz"] = 2
  val
end
c.get("foo")      #=> {"bar" => 1, "baz" => 2}

Append JSON encoded value asynchronously


c.default_format = :document
c.set("foo", {"bar" => 1})
c.run do
  c.cas("foo") do |val|
    case val.operation
    when :get
      val["baz"] = 2
      val
    when :set
      # verify all is ok
      puts "error: #{ret.error.inspect}" unless ret.success?
    end
  end
end
c.get("foo")      #=> {"bar" => 1, "baz" => 2}

Parameters:

  • key (String, Symbol)
  • options (Hash) (defaults to: {})

    the options for “swap” part

Options Hash (options):

  • :ttl (Fixnum) — default: self.default_ttl

    the time to live of this key

  • :format (Symbol) — default: self.default_format

    format of the value

  • :flags (Fixnum) — default: self.default_flags

    flags for this key

  • :retry (Fixnum) — default: 0

    maximum number of times to autmatically retry upon update collision

Yield Parameters:

  • value (Object, Result)

    old value in synchronous mode and Result object in asynchronous mode.

Yield Returns:

  • (Object)

    new value.

Returns:

  • (Fixnum)

    the CAS of new value

Raises:

  • (Couchbase::Error::KeyExists)

    if the key was updated before the the code in block has been completed (the CAS value has been changed).

  • (ArgumentError)

    if the block is missing for async mode

See Also:

Since:

  • 1.0.0



93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
# File 'lib/couchbase/bucket.rb', line 93

def cas(key, options = {})
  retries_remaining = options.delete(:retry) || 0
  if async?
    block = Proc.new
    get(key) do |ret|
      val = block.call(ret) # get new value from caller
      set(ret.key, val, options.merge(:cas => ret.cas, :flags => ret.flags)) do |set_ret|
        if set_ret.error.is_a?(Couchbase::Error::KeyExists) && (retries_remaining > 0)
          cas(key, options.merge(:retry => retries_remaining - 1), &block)
        else
          block.call(set_ret)
        end
      end
    end
  else
    begin
      val, flags, ver = get(key, :extended => true)
      val = yield(val) # get new value from caller
      set(key, val, options.merge(:cas => ver, :flags => flags))
    rescue Couchbase::Error::KeyExists
      if retries_remaining > 0
        retries_remaining -= 1
        retry
      else
        raise
      end
    end
  end
end

#create_periodic_timer(interval, &block) ⇒ Couchbase::Timer

Create and register periodic timer

Returns:

  • (Couchbase::Timer)


285
286
287
# File 'lib/couchbase/bucket.rb', line 285

def create_periodic_timer(interval, &block)
  Timer.new(self, interval, :periodic => true, &block)
end

#create_timer(interval, &block) ⇒ Couchbase::Timer

Create and register one-shot timer

Returns:

  • (Couchbase::Timer)


278
279
280
# File 'lib/couchbase/bucket.rb', line 278

def create_timer(interval, &block)
  Timer.new(self, interval, &block)
end

#delete_design_doc(id, rev = nil) ⇒ true, false

Delete design doc with given id and revision.

Parameters:

  • id (String)

    Design document id. It might have '_design/' prefix.

  • rev (String) (defaults to: nil)

    Document revision. It uses latest revision if rev parameter is nil.

Returns:

  • (true, false)

Since:

  • 1.2.0



209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
# File 'lib/couchbase/bucket.rb', line 209

def delete_design_doc(id, rev = nil)
  ddoc = design_docs[id.sub(/^_design\//, '')]
  unless ddoc
    yield nil if block_given?
    return nil
  end
  path = Utils.build_query(ddoc.id, :rev => rev || ddoc.meta['rev'])
  req = make_http_request(path, :method => :delete, :extended => true)
  rv = nil
  req.on_body do |res|
    rv = res
    val = MultiJson.load(res.value)
    if block_given?
      if res.success? && val['error']
        res.error = Error::View.new("delete_design_doc", val['error'])
      end
      yield(res)
    end
  end
  req.continue
  unless async?
    rv.success? or raise res.error
  end
end

#design_docsHash

Fetch design docs stored in current bucket

Returns:

  • (Hash)

Since:

  • 1.2.0



129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
# File 'lib/couchbase/bucket.rb', line 129

def design_docs
  req = make_http_request("/pools/default/buckets/#{bucket}/ddocs",
                          :type => :management, :extended => true)
  docmap = {}
  req.on_body do |body|
    res = MultiJson.load(body.value)
    res["rows"].each do |obj|
      if obj['doc']
        obj['doc']['value'] = obj['doc'].delete('json')
      end
      doc = DesignDoc.wrap(self, obj)
      key = doc.id.sub(/^_design\//, '')
      next if self.environment == :production && key =~ /dev_/
        docmap[key] = doc
    end
    yield(docmap) if block_given?
  end
  req.continue
  async? ? nil : docmap
end

#flush {|ret| ... } ⇒ true

Delete contents of the bucket

Examples:

Simple flush the bucket

c.flush    #=> true

Asynchronous flush

c.run do
  c.flush do |ret|
    ret.operation   #=> :flush
    ret.success?    #=> true
    ret.status      #=> 200
  end
end

Yield Parameters:

  • ret (Result)

    the object with error, status and operation attributes.

Returns:

  • (true)

    always return true (see raise section)

Raises:

See Also:

Since:

  • 1.2.0.beta



259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
# File 'lib/couchbase/bucket.rb', line 259

def flush
  if !async? && block_given?
    raise ArgumentError, "synchronous mode doesn't support callbacks"
  end
  req = make_http_request("/pools/default/buckets/#{bucket}/controller/doFlush",
                          :type => :management, :method => :post, :extended => true)
  res = nil
  req.on_body do |r|
    res = r
    res.instance_variable_set("@operation", :flush)
    yield(res) if block_given?
  end
  req.continue
  true
end

#observe_and_wait(*keys, &block) ⇒ Fixnum, Hash<String, Fixnum>

Wait for persistence condition

This operation is useful when some confidence needed regarding the state of the keys. With two parameters :replicated and :persisted it allows to set up the waiting rule.

Parameters:

  • keys (String, Symbol, Array, Hash)

    The list of the keys to observe. Full form is hash with key-cas value pairs, but there are also shortcuts like just Array of keys or single key. CAS value needed to when you need to ensure that the storage persisted exactly the same version of the key you are asking to observe.

  • options (Hash)

    The options for operation

Returns:

  • (Fixnum, Hash<String, Fixnum>)

    will return CAS value just like mutators or pairs key-cas in case of multiple keys.

Raises:

Since:

  • 1.2.0.dp6



313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
# File 'lib/couchbase/bucket.rb', line 313

def observe_and_wait(*keys, &block)
  options = {:timeout => default_observe_timeout}
  options.update(keys.pop) if keys.size > 1 && keys.last.is_a?(Hash)
  verify_observe_options(options)
  if block && !async?
    raise ArgumentError, "synchronous mode doesn't support callbacks"
  end
  if keys.size == 0
    raise ArgumentError, "at least one key is required"
  end
  if keys.size == 1 && keys[0].is_a?(Hash)
    key_cas = keys[0]
  else
    key_cas = keys.flatten.reduce({}) do |h, kk|
      h[kk] = nil   # set CAS to nil
      h
    end
  end
  if async?
    do_observe_and_wait(key_cas, options, &block)
  else
    res = do_observe_and_wait(key_cas, options, &block) while res.nil?
    unless async?
      if keys.size == 1 && (keys[0].is_a?(String) || keys[0].is_a?(Symbol))
        return res.values.first
      else
        return res
      end
    end
  end
end

#save_design_doc(data) ⇒ true, false

Update or create design doc with supplied views

Parameters:

  • data (Hash, IO, String)

    The source object containing JSON encoded design document. It must have _id key set, this key should start with _design/.

Returns:

  • (true, false)

Since:

  • 1.2.0



159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
# File 'lib/couchbase/bucket.rb', line 159

def save_design_doc(data)
  attrs = case data
          when String
            MultiJson.load(data)
          when IO
            MultiJson.load(data.read)
          when Hash
            data
          else
            raise ArgumentError, "Document should be Hash, String or IO instance"
          end
  rv = nil
  id = attrs.delete('_id').to_s
  attrs['language'] ||= 'javascript'
  if id !~ /\A_design\//
    rv = Result.new(:operation => :http_request,
                    :key => id,
                    :error => ArgumentError.new("'_id' key must be set and start with '_design/'."))
    yield rv if block_given?
    raise rv.error unless async?
  end
  req = make_http_request(id, :body => MultiJson.dump(attrs),
                          :method => :put, :extended => true)
  req.on_body do |res|
    rv = res
    val = MultiJson.load(res.value)
    if block_given?
      if res.success? && val['error']
        res.error = Error::View.new("save_design_doc", val['error'])
      end
      yield(res)
    end
  end
  req.continue
  unless async?
    rv.success? or raise res.error
  end
end