Class: Libcouchbase::Connection

Inherits:
Object
  • Object
show all
Includes:
Callbacks
Defined in:
lib/libcouchbase/connection.rb

Defined Under Namespace

Classes: Durability, Request

Constant Summary collapse

NonJsonValue =
[:append, :prepend].freeze
FormatFlags =

These are client specific

{
    document: 0,
    marshal: 1,
    plain: 2
}
SupportedFormats =
FormatFlags.keys.freeze
CMDHTTP_F_STREAM =

Stream the response (not used, we’re only making simple requests)

1<<16
CMDHTTP_F_CASTMO =

If specified, the lcb_CMDHTTP::cas field becomes the timeout

1<<17
CMDHTTP_F_NOUPASS =

If specified, do not inject authentication header into the request.

1<<18
HttpBodyRequired =
[:put, :post].freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(hosts: '127.0.0.1', bucket: 'default', password: nil, thread: nil, **opts) ⇒ Connection

Returns a new instance of Connection.



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/libcouchbase/connection.rb', line 42

def initialize(hosts: '127.0.0.1', bucket: 'default', password: nil, thread: nil, **opts)
    # build host string http://docs.couchbase.com/sdk-api/couchbase-c-client-2.5.6/group__lcb-init.html
    hosts = Array(hosts).flatten.join(',')
    connstr = "couchbase://#{hosts}/#{bucket}"
    connstr = "#{connstr}?#{opts.map { |k, v| "#{k}=#{v}" }.join('&') }" unless opts.empty?

    # It's good to know
    @bucket = bucket

    # Configure the event loop settings
    @reactor = thread || ::Libuv::Reactor.current || ::Libuv::Reactor.new
    @reactor.on_program_interrupt { destroy }
    @io_ptr = FFI::MemoryPointer.new :pointer, 1

    if FFI::Platform.windows?
        @io_opts = Ext::IOOptions.new
        @io_opts[:version] = 0
        @io_opts[:type] = :IO_winIOCP

        err = Ext.create_io_ops(@io_ptr, @io_opts)
    else
        @io_opts = Ext::Libuv::UVOptions.new
        @io_opts[:version] = 0
        @io_opts[:loop] = @reactor.handle
        @io_opts[:start_stop_noop] = 1 # We want to control the start and stopping of the loop
        
        err = Ext::Libuv.create_libuv_io_opts(0, @io_ptr, @io_opts)
    end

    if err != :success
        raise Error.lookup(err), 'failed to allocate IO plugin'
    end

    # Configure the connection to the database
    @connection = Ext::CreateSt.new
    @connection[:version] = 3
    @connection[:v][:v3][:connstr] = FFI::MemoryPointer.from_string(connstr)
    @connection[:v][:v3][:passwd]  = FFI::MemoryPointer.from_string(password) if password
    @connection[:v][:v3][:io]      = @io_ptr.get_pointer(0)
    @handle_ptr = FFI::MemoryPointer.new :pointer, 1
end

Instance Attribute Details

#bucketObject (readonly)

Returns the value of attribute bucket.



85
86
87
# File 'lib/libcouchbase/connection.rb', line 85

def bucket
  @bucket
end

#handleObject (readonly)

Returns the value of attribute handle.



85
86
87
# File 'lib/libcouchbase/connection.rb', line 85

def handle
  @handle
end

#reactorObject (readonly)

Returns the value of attribute reactor.



85
86
87
# File 'lib/libcouchbase/connection.rb', line 85

def reactor
  @reactor
end

#requestsObject (readonly)

Returns the value of attribute requests.



85
86
87
# File 'lib/libcouchbase/connection.rb', line 85

def requests
  @requests
end

Instance Method Details

#configure(setting, value) ⇒ Object



139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
# File 'lib/libcouchbase/connection.rb', line 139

def configure(setting, value)
    # Ensure it is thread safe
    defer = @reactor.defer
    @reactor.schedule {
        if @handle
            err = Ext.cntl_string(@handle, setting.to_s, value.to_s)
            if err == :success
                defer.resolve(self)
            else
                defer.reject(Error.lookup(err).new("failed to configure #{setting}=#{value}"))
            end
        else
            defer.reject(RuntimeError.new('not connected'))
        end
    }

    defer.promise
end

#connect(defer: nil, flush_enabled: false) ⇒ Object



92
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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
# File 'lib/libcouchbase/connection.rb', line 92

def connect(defer: nil, flush_enabled: false)
    raise 'already connected' if @handle || @bootstrap_defer
    @bootstrap_defer = defer || @reactor.defer
    promise = @bootstrap_defer.promise

    @reactor.schedule {
        @flush_enabled = flush_enabled

        @requests = {}

        # Create a library handle
        #  the create call allocates the memory and updates our pointer
        err = Ext.create(@handle_ptr, @connection)
        if err != :success
            @bootstrap_defer.reject(Error.lookup(err).new('failed to create instance'))
            handle_destroyed
        else
            # We extract the pointer and create the handle structure
            @ref = @handle_ptr.get_pointer(0).address
            @handle = Ext::T.new @handle_ptr.get_pointer(0)

            # Register the callbacks we are interested in
            Ext.set_bootstrap_callback(@handle, callback(:bootstrap_callback))

            Ext.install_callback3(@handle, Ext::CALLBACKTYPE[:callback_get],     callback(:callback_get))
            Ext.install_callback3(@handle, Ext::CALLBACKTYPE[:callback_unlock],  callback(:callback_unlock))
            Ext.install_callback3(@handle, Ext::CALLBACKTYPE[:callback_store],   callback(:callback_store))
            Ext.install_callback3(@handle, Ext::CALLBACKTYPE[:callback_storedur],callback(:callback_storedur))
            Ext.install_callback3(@handle, Ext::CALLBACKTYPE[:callback_counter], callback(:callback_counter))
            Ext.install_callback3(@handle, Ext::CALLBACKTYPE[:callback_touch],   callback(:callback_touch))
            Ext.install_callback3(@handle, Ext::CALLBACKTYPE[:callback_remove],  callback(:callback_remove))
            Ext.install_callback3(@handle, Ext::CALLBACKTYPE[:callback_http],    callback(:callback_http))
            Ext.install_callback3(@handle, Ext::CALLBACKTYPE[:callback_cbflush], callback(:callback_cbflush)) if @flush_enabled

            # Connect to the database
            err = Ext.connect(@handle)
            if err != :success
                @bootstrap_defer.reject(Error.lookup(err).new('failed to schedule connect'))
                destroy
            end
        end
    }

    promise
end

#counter(key, delta: 1, initial: nil, expire_in: nil, ttl: nil, expire_at: nil, cas: nil, **opts) ⇒ Object



375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
# File 'lib/libcouchbase/connection.rb', line 375

def counter(key, delta: 1, initial: nil, expire_in: nil, ttl: nil, expire_at: nil, cas: nil, **opts)
    raise 'not connected' unless @handle
    defer ||= @reactor.defer

    cmd = Ext::CMDCOUNTER.new
    req = Request.new(cmd, defer)
    key = cmd_set_key(req, cmd, key)

    cmd[:cas] = cas if cas
    expire_in ||= ttl
    cmd[:exptime] = expire_in ? expires_in(expire_in) : expire_at.to_i
    cmd[:delta] = delta
    if initial
        cmd[:initial] = initial
        cmd[:create] = 1
    end

    @reactor.schedule {
        pointer = cmd.to_ptr
        @requests[pointer.address] = req
        check_error key, defer, Ext.counter3(@handle, pointer, cmd)
    }

    defer.promise
end

#destroyObject



158
159
160
161
162
163
164
165
166
167
168
169
170
171
# File 'lib/libcouchbase/connection.rb', line 158

def destroy
    defer = @reactor.defer

    # Ensure it is thread safe
    @reactor.schedule {
        if @handle
            Ext.destroy(@handle)
            handle_destroyed
        end
        defer.resolve(self)
    }

    defer.promise
end

#flush(defer: nil) ⇒ Object



425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
# File 'lib/libcouchbase/connection.rb', line 425

def flush(defer: nil)
    raise 'not connected' unless @handle
    raise 'flush not enabled' unless @flush_enabled
    defer ||= @reactor.defer

    cmd = Ext::CMDBASE.new

    @reactor.schedule {
        pointer = cmd.to_ptr
        @requests[pointer.address] = Request.new(cmd, defer, :flush)
        check_error :flush, defer, Ext.cbflush3(@handle, pointer, cmd)
    }

    defer.promise
end

#full_text_search(index, **opts) ⇒ Object



516
517
518
519
# File 'lib/libcouchbase/connection.rb', line 516

def full_text_search(index, **opts)
    opts[:indexName] = index
    QueryFullText.new(self, @reactor, **opts)
end

#get(key, defer: nil, lock: false, cas: nil, format: nil, **opts) ⇒ Object



305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
# File 'lib/libcouchbase/connection.rb', line 305

def get(key, defer: nil, lock: false, cas: nil, format: nil, **opts)
    raise 'not connected' unless @handle
    defer ||= @reactor.defer

    cmd = Ext::CMDGET.new
    req = Request.new(cmd, defer)
    req.value = format
    key = cmd_set_key(req, cmd, key)
    cmd[:cas] = cas if cas

    # exptime == the lock expire time
    if lock
        time = lock == true ? 30 : lock.to_i
        time = 30 if time > 30 || time < 0

        # We only want to lock if time is between 1 and 30
        if time > 0
            cmd[:exptime] = time
            cmd[:lock] = 1
        end
    end

    @reactor.schedule {
        pointer = cmd.to_ptr
        @requests[pointer.address] = req
        check_error key, defer, Ext.get3(@handle, pointer, cmd)
    }

    defer.promise
end

#get_callback(cb) ⇒ Object



87
88
89
# File 'lib/libcouchbase/connection.rb', line 87

def get_callback(cb)
    callback(cb)
end

#get_num_nodesObject



208
209
210
211
212
213
214
215
216
217
218
219
220
221
# File 'lib/libcouchbase/connection.rb', line 208

def get_num_nodes
    defer = @reactor.defer

    # Ensure it is thread safe
    @reactor.schedule {
        if @handle
            defer.resolve(Ext.get_num_nodes(@handle))
        else
            defer.reject(RuntimeError.new('not connected'))
        end
    }

    defer.promise
end

#get_num_replicasObject



193
194
195
196
197
198
199
200
201
202
203
204
205
206
# File 'lib/libcouchbase/connection.rb', line 193

def get_num_replicas
    defer = @reactor.defer

    # Ensure it is thread safe
    @reactor.schedule {
        if @handle
            defer.resolve(Ext.get_num_replicas(@handle))
        else
            defer.reject(RuntimeError.new('not connected'))
        end
    }

    defer.promise
end

#get_server_listObject



173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
# File 'lib/libcouchbase/connection.rb', line 173

def get_server_list
    defer = @reactor.defer

    # Ensure it is thread safe
    @reactor.schedule {
        if @handle
            resp = Ext.get_server_list(@handle)
            if resp.null?
                defer.reject(RuntimeError.new('not connected'))
            else
                defer.resolve(resp.get_array_of_string(0))
            end
        else
            defer.reject(RuntimeError.new('not connected'))
        end
    }

    defer.promise
end

#http(path, type: :view, method: :get, body: nil, content_type: 'application/json', defer: nil, timeout: nil, username: nil, password: nil, no_auth: false, **opts) ⇒ Object



448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
# File 'lib/libcouchbase/connection.rb', line 448

def http(path,
        type: :view,
        method: :get,
        body: nil,
        content_type: 'application/json',
        defer: nil,
        timeout: nil,
        username: nil,
        password: nil,
        no_auth: false,
**opts)
    raise 'not connected' unless @handle
    raise 'unsupported request type' unless Ext::HttpTypeT[type]
    raise 'unsupported HTTP method' unless Ext::HttpMethodT[method]
    body_content = if HttpBodyRequired.include? method
        raise 'no HTTP body provided' unless body
        if body.is_a? String
            body
        else
            # This will raise an error if not valid json
            JSON.generate([body])[1..-2]
        end
    end

    defer ||= @reactor.defer

    cmd = Ext::CMDHTTP.new
    req = Request.new(cmd, defer)
    req.value = {
        path: path,
        method: method,
        body: body,
        content_type: content_type,
        type: type,
        no_auth: no_auth
    }
    cmd_set_key(req, cmd, path)

    if timeout
        cmd[:cas] = timeout
        cmd[:cmdflags] |= CMDHTTP_F_CASTMO
    end
    cmd[:cmdflags] |= CMDHTTP_F_NOUPASS if no_auth
    cmd[:type] = type
    cmd[:method] = method

    if body_content
        cmd[:body] = req.ref(body_content)
        cmd[:nbody] = body_content.bytesize
    end
    cmd[:content_type] = req.ref(content_type) if content_type
    cmd[:username] = req.ref(username) if username
    cmd[:password] = req.ref(password) if password


    @reactor.schedule {
        pointer = cmd.to_ptr
        @requests[pointer.address] = req
        check_error path, defer, Ext.http3(@handle, pointer, cmd)
    }

    defer.promise
end

#n1ql_query(n1ql, **opts) ⇒ Object



521
522
523
# File 'lib/libcouchbase/connection.rb', line 521

def n1ql_query(n1ql, **opts)
    QueryN1QL.new(self, @reactor, n1ql, **opts)
end

#parse_document(raw_string, flags: 0, hint: nil) ⇒ Object



525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
# File 'lib/libcouchbase/connection.rb', line 525

def parse_document(raw_string, flags: 0, hint: nil)
    flag_mask = flags & 3
    format = hint || FormatFlags[flag_mask] # Defaults to document
    val = begin
        case format
        when :marshal
            Marshal.load(raw_string)
        when :document
            JSON.parse("[#{raw_string}]", DECODE_OPTIONS)[0]
        else
            format = :plain
            raw_string
        end
    rescue => e
        format = :plain
        raw_string
    end
    [val, format]
end

#query_view(design, view, **opts) ⇒ Object



512
513
514
# File 'lib/libcouchbase/connection.rb', line 512

def query_view(design, view, **opts)
    QueryView.new(self, @reactor, design, view, **opts)
end

#remove(key, defer: nil, cas: nil, **opts) ⇒ Object



356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
# File 'lib/libcouchbase/connection.rb', line 356

def remove(key, defer: nil, cas: nil, **opts)
    raise 'not connected' unless @handle
    defer ||= @reactor.defer

    cmd = Ext::CMDBASE.new
    req = Request.new(cmd, defer)
    key = cmd_set_key(req, cmd, key)
    cmd[:cas] = cas if cas

    @reactor.schedule {
        pointer = cmd.to_ptr
        @requests[pointer.address] = req
        check_error key, defer, Ext.remove3(@handle, pointer, cmd)
    }

    defer.promise
end

#store(key, value, defer: nil, operation: :set, expire_in: nil, expire_at: nil, ttl: nil, persist_to: 0, replicate_to: 0, format: :document, cas: nil, flags: 0, **opts) ⇒ Object



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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
# File 'lib/libcouchbase/connection.rb', line 238

def store(key, value, 
        defer: nil,
        operation: :set,
        expire_in: nil,
        expire_at: nil,
        ttl: nil,
        persist_to: 0,
        replicate_to: 0,
        format: :document,
        cas: nil,
        flags: 0,
**opts)
    raise 'not connected' unless @handle
    raise 'format not supported' unless SupportedFormats.include?(:document)
    defer ||= @reactor.defer

    # Check if this should be a durable operation
    durable = (persist_to | replicate_to) != 0
    if durable
        cmd = Ext::CMDSTOREDUR.new
        cmd[:persist_to]   = persist_to
        cmd[:replicate_to] = replicate_to
    else
        cmd = Ext::CMDSTORE.new
    end
    cmd[:operation] = operation

    # Check if we are storing a string or partial value
    if NonJsonValue.include?(operation)
        format = :plain
    else
        # Preserve any application specific flags and set the format flags
        flag_mask = flags & 3
        flags = flags ^ flag_mask
        cmd[:flags] = flags | FormatFlags[format]
    end

    # Move the data into the correct format for storage
    if format == :marshal
        str_value = Marshal.dump(value)
    elsif format == :plain
        # Use coercion as it was intended
        str_value = value.respond_to?(:to_str) ? value.to_str : value.to_s
    else
        # This will raise an error if we're not storing valid json
        str_value = JSON.generate([value])[1..-2]
    end

    req = Request.new(cmd, defer)
    req.value = value
    cmd_set_value(req, cmd, str_value)
    key = cmd_set_key(req, cmd, key)

    cmd[:cas] = cas if cas
    expire_in ||= ttl
    cmd[:exptime] = expire_in ? expires_in(expire_in) : expire_at.to_i

    @reactor.schedule {
        pointer = cmd.to_ptr
        @requests[pointer.address] = req
        check_error(key, defer, durable ? Ext.storedur3(@handle, pointer, cmd) : Ext.store3(@handle, pointer, cmd))
    }
    
    defer.promise
end

#touch(key, expire_in: nil, ttl: nil, expire_at: nil, cas: nil, **opts) ⇒ Object

Raises:

  • (ArgumentError)


402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
# File 'lib/libcouchbase/connection.rb', line 402

def touch(key, expire_in: nil, ttl: nil, expire_at: nil, cas: nil, **opts)
    raise 'not connected' unless @handle
    raise ArgumentError.new('requires either expire_in or expire_at to be set') unless expire_in || expire_at
    defer ||= @reactor.defer

    cmd = Ext::CMDBASE.new
    req = Request.new(cmd, defer)
    key = cmd_set_key(req, cmd, key)

    cmd[:cas] = cas if cas
    expire_in ||= ttl
    cmd[:exptime] = expire_in ? expires_in(expire_in) : expire_at.to_i

    @reactor.schedule {
        pointer = cmd.to_ptr
        @requests[pointer.address] = req
        check_error key, defer, Ext.touch3(@handle, pointer, cmd)
    }

    defer.promise
end

#unlock(key, cas:, **opts) ⇒ Object



337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
# File 'lib/libcouchbase/connection.rb', line 337

def unlock(key, cas: , **opts)
    raise 'not connected' unless @handle
    defer ||= @reactor.defer

    cmd = Ext::CMDBASE.new
    req = Request.new(cmd, defer)
    key = cmd_set_key(req, cmd, key)
    cmd[:cas] = cas

    @reactor.schedule {
        pointer = cmd.to_ptr
        @requests[pointer.address] = Request.new(cmd, defer, key)
        check_error key, defer, Ext.unlock3(@handle, pointer, cmd)
    }

    defer.promise
end