Skip to content

Instantly share code, notes, and snippets.

@kivanio
Forked from mattetti/gist:191596
Created September 23, 2009 12:27
Show Gist options
  • Save kivanio/191947 to your computer and use it in GitHub Desktop.
Save kivanio/191947 to your computer and use it in GitHub Desktop.
# For this experiment you need to have 2 instances of couchdb 0.10
# one running on port 5984 and one on port 5983
require 'rubygems'
require 'couchrest'
server = CouchRest.new("http://127.0.0.1:5984")
server2 = CouchRest.new("http://127.0.0.1:5983")
begin server.database('replication-test-1').delete!; rescue; nil; end
begin server2.database('replication-test-2').delete!; rescue; nil; end
DB_A = server.database!('replication-test-1')
DB_B = server2.database!('replication-test-2')
docs = []
999.times do |n|
docs << {"_id" => "#{n}", :to_replicate => false}
end
# save 999 documents not to replicate
DB_A.bulk_save(docs)
# save 1 doc to replicate
DB_A.save_doc("_id" => "#{server.next_uuid}", :to_replicate => true )
# add the validation rule
DB_B.save_doc({
"_id" => "_design/rules",
:validate_doc_update => "function(newDoc, oldDoc, userCtx) {
if(newDoc.to_replicate != true) {
throw {forbidden: 'This doc should be ignored during replication.'};
}};"
})
# start the replication
DB_A.replicate_to(DB_B)
raise "replication failed" unless DB_B.documents['rows'].size == 2 # 2 as a design doc and the doc to replicate
puts "setting up continuous replication"
puts RestClient.post "#{server.uri}/_replicate", %Q[{"source":"#{DB_A.name}","target":"#{DB_B.root}", "continuous": true}]
# same as: `curl -X POST -d '{"source":"#{DB_A.name}","target":"#{DB_B.root}", "continuous": true}' #{server.uri}/_replicate`
puts "checking on running tasks:"
puts RestClient.get "#{server.uri}/_active_tasks"
puts "add a replicatable and not replicated document to DB A"
new_doc_id = server.next_uuid
new_doc_id_2 = server.next_uuid
DB_A.save_doc("_id" => "#{new_doc_id}", :to_replicate => true )
DB_A.save_doc("_id" => "#{new_doc_id_2}", :to_replicate => false )
puts "the documents are now being replicated to DB B"
sleep(1) # let's give some time to replicate
begin
DB_B.get(new_doc_id)
rescue RestClient::ResourceNotFound
puts "FAIL document not available yet"
else
puts "everything worked fine, filtered replication of a valid object worked"
end
begin
DB_B.get(new_doc_id_2)
rescue RestClient::ResourceNotFound
puts "invalid document not replicated as expected"
else
puts "FAIL, the document shouldn't have replicated"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment