You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@couchdb.apache.org by va...@apache.org on 2025/11/06 00:27:12 UTC
(couchdb) branch 3.5.x updated (11f0d3643 -> 44f6a43d8)
This is an automated email from the ASF dual-hosted git repository.
vatamane pushed a change to branch 3.5.x
in repository https://gitbox.apache.org/repos/asf/couchdb.git
from 11f0d3643 Bump version to 3.5.0
new 0f7f208dc Cherry-pick main changes into 3.5.x
new 449f5e2d7 Bump version to 3.5.1
new 44f6a43d8 Doc updates for 3.5.1
The 3 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
Summary of changes:
.asf.yaml | 3 +
.elp.toml | 38 +
.gitignore | 2 +
CONTRIBUTING.md | 13 +
INSTALL.Unix.md | 18 +-
Makefile | 19 +-
Makefile.win | 4 +
README-DEV.rst | 12 +-
build-aux/{Jenkinsfile.full => Jenkinsfile} | 387 +-
build-aux/Jenkinsfile.pr | 293 -
build-aux/xref-helper.sh | 1 -
configure | 10 +-
configure.ps1 | 8 +-
dev/run | 23 +-
.../{core/ser/LongWrapper.java => api/Ok.java} | 11 +-
.../apache/couchdb/nouveau/core/IndexManager.java | 61 +-
.../couchdb/nouveau/resources/IndexResource.java | 26 +-
.../couchdb/nouveau/core/IndexManagerTest.java | 77 +-
rebar.config.script | 13 +-
rel/nouveau.yaml | 4 +-
rel/overlay/etc/default.ini | 110 +-
rel/overlay/etc/vm.args | 11 +
rel/reltool.config | 4 +
share/server/views.js | 4 +-
src/chttpd/src/chttpd_db.erl | 40 +-
src/chttpd/src/chttpd_external.erl | 2 +-
src/chttpd/src/chttpd_misc.erl | 4 +-
src/chttpd/src/chttpd_node.erl | 3 +-
.../eunit/chttpd_auth_hash_algorithms_tests.erl | 2 +-
src/chttpd/test/eunit/chttpd_purge_tests.erl | 34 +-
src/config/src/config.erl | 4 +-
src/config/src/config_listener_mon.erl | 2 +-
src/config/test/config_tests.erl | 38 +-
src/couch/include/couch_db.hrl | 10 -
src/couch/include/couch_eunit.hrl | 2 +-
src/couch/include/couch_eunit_proper.hrl | 4 +-
src/couch/priv/couch_cfile/couch_cfile.c | 30 +-
src/couch/priv/stats_descriptions.cfg | 12 +
src/couch/rebar.config.script | 64 +-
src/couch/src/couch_att.erl | 12 +-
src/couch/src/couch_base32.erl | 2 +-
src/couch/src/couch_bt_engine.erl | 191 +-
src/couch/src/couch_bt_engine_cache.erl | 292 +
src/couch/src/couch_bt_engine_compactor.erl | 6 +-
src/couch/src/couch_bt_engine_header.erl | 80 +-
src/couch/src/couch_btree.erl | 362 +-
src/couch/src/couch_db.erl | 78 +-
src/couch/src/couch_db_updater.erl | 53 +-
src/couch/src/couch_debug.erl | 55 +-
src/couch/src/couch_doc.erl | 30 +-
src/couch/src/couch_file.erl | 77 +-
src/couch/src/couch_flags_config.erl | 2 +-
src/couch/src/couch_httpd_auth.erl | 4 +-
src/couch/src/couch_httpd_db.erl | 2 +-
src/couch/src/couch_httpd_multipart.erl | 10 +-
src/couch/src/couch_httpd_vhost.erl | 2 +-
src/couch/src/couch_key_tree.erl | 6 +-
src/couch/src/couch_multidb_changes.erl | 8 +-
src/couch/src/couch_native_process.erl | 6 +-
src/couch/src/couch_os_process.erl | 6 +-
src/couch/src/couch_primary_sup.erl | 3 +-
src/couch/src/couch_proc_manager.erl | 24 +-
src/couch/src/couch_query_servers.erl | 13 +-
src/couch/src/couch_server.erl | 11 +-
src/couch/src/couch_stream.erl | 4 +-
src/couch/src/couch_task_status.erl | 4 +-
src/couch/src/couch_util.erl | 99 +-
src/couch/src/couch_uuids.erl | 32 +-
src/couch/src/test_util.erl | 6 +-
.../test/eunit/couch_bt_engine_cache_test.erl | 102 +
.../eunit/couch_bt_engine_compactor_ev_tests.erl | 6 +-
.../test/eunit/couch_bt_engine_compactor_tests.erl | 4 +-
src/couch/test/eunit/couch_btree_prop_tests.erl | 225 +
src/couch/test/eunit/couch_btree_tests.erl | 108 +-
src/couch/test/eunit/couch_changes_tests.erl | 6 +-
src/couch/test/eunit/couch_file_tests.erl | 83 +
src/couch/test/eunit/couch_index_tests.erl | 2 +-
src/couch/test/eunit/couch_query_servers_tests.erl | 142 +-
src/couch/test/eunit/couch_server_tests.erl | 8 +-
src/couch/test/eunit/couch_stream_tests.erl | 2 +-
src/couch/test/eunit/couch_task_status_tests.erl | 4 +-
src/couch/test/eunit/couch_work_queue_tests.erl | 4 +-
src/couch/test/eunit/couchdb_attachments_tests.erl | 2 +-
.../test/eunit/couchdb_file_compression_tests.erl | 2 +-
src/couch/test/eunit/couchdb_os_proc_pool.erl | 10 +-
.../test/eunit/couchdb_update_conflicts_tests.erl | 6 +-
src/couch/test/eunit/couchdb_vhosts_tests.erl | 22 +-
src/couch/test/eunit/couchdb_views_tests.erl | 12 +-
src/couch_event/src/couch_event_listener.erl | 20 +-
src/couch_event/src/couch_event_listener_mfa.erl | 6 +-
src/couch_event/src/couch_event_server.erl | 6 +-
src/couch_index/src/couch_index.erl | 4 +-
src/couch_index/src/couch_index_server.erl | 2 +-
src/couch_index/src/couch_index_util.erl | 47 +
.../test/eunit/couch_index_ddoc_updated_tests.erl | 4 +-
src/couch_log/src/couch_log_config.erl | 2 +-
src/couch_log/src/couch_log_trunc_io.erl | 10 +-
src/couch_log/src/couch_log_trunc_io_fmt.erl | 14 +-
.../test/eunit/couch_log_config_listener_test.erl | 4 +-
.../test/eunit/couch_log_formatter_test.erl | 64 +-
src/couch_log/test/eunit/couch_log_server_test.erl | 4 +-
src/couch_log/test/eunit/couch_log_test_util.erl | 4 +-
src/couch_mrview/src/couch_mrview.erl | 18 +-
src/couch_mrview/src/couch_mrview_cleanup.erl | 51 +-
src/couch_mrview/src/couch_mrview_compactor.erl | 8 +-
src/couch_mrview/src/couch_mrview_index.erl | 4 +-
src/couch_mrview/src/couch_mrview_test_util.erl | 2 +-
src/couch_mrview/src/couch_mrview_updater.erl | 8 +-
src/couch_mrview/src/couch_mrview_util.erl | 66 +-
.../test/eunit/couch_mrview_collation_tests.erl | 6 +-
.../test/eunit/couch_mrview_compact_tests.erl | 8 +-
.../test/eunit/couch_mrview_ddoc_updated_tests.erl | 6 +-
.../eunit/couch_mrview_purge_docs_fabric_tests.erl | 2 +-
.../test/eunit/couch_mrview_purge_docs_tests.erl | 6 +-
.../test/eunit/couch_mrview_util_tests.erl | 28 +
src/couch_peruser/src/couch_peruser.erl | 2 +-
src/couch_prometheus/src/couch_prometheus.erl | 20 +-
.../test/eunit/couch_prometheus_e2e_tests.erl | 6 +-
src/couch_pse_tests/src/cpse_test_ref_counting.erl | 8 +-
src/couch_pse_tests/src/cpse_util.erl | 18 +-
src/couch_quickjs/.gitignore | 2 +
src/couch_quickjs/c_src/couchjs.c | 27 +-
.../patches/01-spidermonkey-185-mode.patch | 6 +-
src/couch_quickjs/patches/02-test262-errors.patch | 11 +
src/couch_quickjs/quickjs/Changelog | 28 +
src/couch_quickjs/quickjs/Makefile | 13 +
src/couch_quickjs/quickjs/VERSION | 2 +-
src/couch_quickjs/quickjs/cutils.c | 52 +-
src/couch_quickjs/quickjs/cutils.h | 102 +-
src/couch_quickjs/quickjs/libregexp-opcode.h | 12 +-
src/couch_quickjs/quickjs/libregexp.c | 1019 ++-
src/couch_quickjs/quickjs/libregexp.h | 1 +
src/couch_quickjs/quickjs/libunicode-table.h | 421 +-
src/couch_quickjs/quickjs/libunicode.c | 237 +-
src/couch_quickjs/quickjs/libunicode.h | 14 +-
src/couch_quickjs/quickjs/qjsc.c | 107 +-
src/couch_quickjs/quickjs/quickjs-atom.h | 14 +
src/couch_quickjs/quickjs/quickjs-libc.c | 260 +-
src/couch_quickjs/quickjs/quickjs-libc.h | 8 +-
src/couch_quickjs/quickjs/quickjs-opcode.h | 15 +-
src/couch_quickjs/quickjs/quickjs.c | 8586 ++++++++++++++------
src/couch_quickjs/quickjs/quickjs.h | 81 +-
src/couch_quickjs/quickjs/run-test262.c | 114 +-
src/couch_quickjs/quickjs/test262.conf | 93 +-
src/couch_quickjs/quickjs/test262_errors.txt | 131 +-
src/couch_quickjs/quickjs/tests/test262.patch | 41 +-
src/couch_quickjs/rebar.config.script | 22 +-
.../src/couch_quickjs_scanner_plugin.erl | 9 +-
.../{update_and_apply_patches.sh => update.sh} | 8 +-
src/couch_quickjs/update_patches.sh | 28 +
.../src/couch_replicator_api_wrap.erl | 18 +-
.../src/couch_replicator_auth_session.erl | 38 +-
.../src/couch_replicator_connection.erl | 3 +
.../src/couch_replicator_doc_processor_worker.erl | 2 +-
src/couch_replicator/src/couch_replicator_docs.erl | 2 +-
.../src/couch_replicator_fabric.erl | 2 +-
.../src/couch_replicator_fabric_rpc.erl | 10 +-
.../src/couch_replicator_httpc.erl | 165 +-
.../src/couch_replicator_httpc_pool.erl | 51 +-
.../src/couch_replicator_notifier.erl | 30 +-
.../src/couch_replicator_parse.erl | 25 +-
src/couch_replicator/src/couch_replicator_pg.erl | 14 +-
.../src/couch_replicator_rate_limiter.erl | 6 +-
.../src/couch_replicator_scheduler.erl | 913 ++-
.../src/couch_replicator_scheduler_job.erl | 130 +-
.../src/couch_replicator_utils.erl | 54 +-
.../src/couch_replicator_worker.erl | 82 +-
src/couch_replicator/src/json_stream_parse.erl | 2 +-
.../test/eunit/couch_replicator_compact_tests.erl | 26 +-
.../eunit/couch_replicator_connection_tests.erl | 2 +-
.../couch_replicator_error_reporting_tests.erl | 2 +-
.../eunit/couch_replicator_httpc_pool_tests.erl | 2 +-
.../eunit/couch_replicator_rate_limiter_tests.erl | 2 +-
...ch_replicator_retain_stats_between_job_runs.erl | 6 +-
...ch_replicator_small_max_request_size_target.erl | 2 +-
.../test/eunit/couch_replicator_test_helper.erl | 2 +-
src/couch_scanner/src/couch_scanner_plugin.erl | 193 +-
.../src/couch_scanner_plugin_conflict_finder.erl | 10 +-
.../src/couch_scanner_plugin_find.erl | 10 +-
.../src/couch_scanner_rate_limiter.erl | 56 +-
src/couch_scanner/src/couch_scanner_server.erl | 2 +
src/couch_scanner/src/couch_scanner_util.erl | 35 +-
.../test/eunit/couch_scanner_test.erl | 54 +-
src/couch_stats/src/couch_stats_httpd.erl | 4 +-
.../src/couch_stats_process_tracker.erl | 2 +-
src/custodian/src/custodian_util.erl | 2 +-
src/ddoc_cache/src/ddoc_cache_entry.erl | 16 +-
.../src/ddoc_cache_entry_validation_funs.erl | 13 +-
src/ddoc_cache/src/ddoc_cache_lru.erl | 2 +-
.../test/eunit/ddoc_cache_coverage_test.erl | 4 +-
.../test/eunit/ddoc_cache_entry_test.erl | 4 +-
src/ddoc_cache/test/eunit/ddoc_cache_lru_test.erl | 12 +-
.../test/eunit/ddoc_cache_open_error_test.erl | 2 +-
src/ddoc_cache/test/eunit/ddoc_cache_open_test.erl | 2 +-
.../test/eunit/ddoc_cache_remove_test.erl | 4 +-
src/ddoc_cache/test/eunit/ddoc_cache_tutil.erl | 2 +-
src/docs/src/api/database/changes.rst | 5 +-
src/docs/src/api/server/authn.rst | 91 +
src/docs/src/api/server/common.rst | 20 +-
src/docs/src/cluster/databases.rst | 3 +
src/docs/src/cluster/purging.rst | 4 +-
src/docs/src/cluster/sharding.rst | 5 +-
src/docs/src/cluster/troubleshooting.rst | 2 +-
src/docs/src/config/misc.rst | 33 +-
src/docs/src/config/query-servers.rst | 14 +-
src/docs/src/config/replicator.rst | 16 +-
src/docs/src/config/resharding.rst | 2 +-
src/docs/src/config/scanner.rst | 19 +
src/docs/src/ddocs/ddocs.rst | 3 +
src/docs/src/install/nouveau.rst | 11 +-
src/docs/src/install/troubleshooting.rst | 10 +
src/docs/src/install/unix.rst | 3 +-
src/docs/src/replication/protocol.rst | 2 +-
src/docs/src/setup/cluster.rst | 2 +-
src/docs/src/whatsnew/3.5.rst | 145 +
src/dreyfus/src/clouseau_rpc.erl | 90 +-
src/dreyfus/src/dreyfus_fabric_cleanup.erl | 122 +-
src/dreyfus/src/dreyfus_fabric_group1.erl | 4 +-
src/dreyfus/src/dreyfus_fabric_group2.erl | 4 +-
src/dreyfus/src/dreyfus_fabric_search.erl | 4 +-
src/dreyfus/src/dreyfus_index.erl | 11 +-
src/dreyfus/src/dreyfus_rpc.erl | 47 +-
src/dreyfus/src/dreyfus_util.erl | 34 +-
src/dreyfus/test/eunit/dreyfus_purge_test.erl | 8 +-
src/ets_lru/src/ets_lru.erl | 2 +-
src/ets_lru/test/ets_lru_test.erl | 4 +-
src/exxhash/README.md | 2 +-
src/exxhash/c_src/xxhash.h | 207 +-
src/fabric/src/fabric.erl | 79 +-
src/fabric/src/fabric_db_create.erl | 8 +-
src/fabric/src/fabric_db_delete.erl | 2 +-
src/fabric/src/fabric_db_meta.erl | 25 +-
src/fabric/src/fabric_db_purged_infos.erl | 17 +-
src/fabric/src/fabric_db_update_listener.erl | 10 +-
src/fabric/src/fabric_doc_open.erl | 20 +-
src/fabric/src/fabric_doc_open_revs.erl | 5 +-
src/fabric/src/fabric_doc_purge.erl | 523 +-
src/fabric/src/fabric_doc_update.erl | 3 +-
src/fabric/src/fabric_index_cleanup.erl | 81 +
src/fabric/src/fabric_open_revs.erl | 3 +-
src/fabric/src/fabric_rpc.erl | 53 +-
src/fabric/src/fabric_streams.erl | 14 +-
src/fabric/src/fabric_util.erl | 184 +-
src/fabric/src/fabric_view_all_docs.erl | 6 +-
src/fabric/src/fabric_view_changes.erl | 4 +-
src/fabric/src/fabric_view_map.erl | 2 +-
src/fabric/test/eunit/fabric_bench_test.erl | 2 +-
src/fabric/test/eunit/fabric_db_info_tests.erl | 38 +-
.../test/eunit/fabric_moved_shards_seq_tests.erl | 2 +-
src/fabric/test/eunit/fabric_rpc_purge_tests.erl | 8 +-
src/fabric/test/eunit/fabric_rpc_tests.erl | 2 +-
src/fabric/test/eunit/fabric_tests.erl | 23 +-
src/global_changes/src/global_changes_server.erl | 4 +-
src/ioq/src/ioq.erl | 4 +-
src/ken/rebar.config.script | 14 +-
src/ken/src/ken.app.src.script | 13 +-
src/ken/src/ken_server.erl | 92 +-
src/ken/test/ken_server_test.erl | 2 +-
src/mango/rebar.config.script | 16 +-
src/mango/requirements.txt | 2 +-
src/mango/src/mango_cursor.erl | 8 -
src/mango/src/mango_cursor_nouveau.erl | 4 +-
src/mango/src/mango_cursor_text.erl | 8 +-
src/mango/src/mango_doc.erl | 10 +-
src/mango/src/mango_idx_special.erl | 8 +-
src/mango/src/mango_json.erl | 2 +-
src/mango/src/mango_native_proc.erl | 2 +-
src/mango/src/mango_selector.erl | 2 +-
src/mango/src/mango_selector_text.erl | 8 +-
src/mango/src/mango_util.erl | 16 +-
src/mango/test/02-basic-find-test.py | 2 +-
src/mango/test/04-key-tests.py | 7 +-
src/mango/test/mango.py | 58 +-
src/mem3/include/mem3.hrl | 4 +-
src/mem3/src/mem3.erl | 74 +-
src/mem3/src/mem3_db_doc_updater.erl | 107 +
src/mem3/src/mem3_hash.erl | 30 +-
src/mem3/src/mem3_httpd.erl | 4 +-
src/mem3/src/mem3_nodes.erl | 61 +-
src/mem3/src/mem3_rep.erl | 23 +-
src/mem3/src/mem3_reshard.erl | 4 +-
src/mem3/src/mem3_reshard_dbdoc.erl | 141 +-
src/mem3/src/mem3_reshard_index.erl | 26 +-
src/mem3/src/mem3_reshard_job.erl | 10 +-
src/mem3/src/mem3_reshard_sup.erl | 3 -
src/mem3/src/mem3_rpc.erl | 10 +-
src/mem3/src/mem3_shards.erl | 387 +-
src/mem3/src/mem3_sup.erl | 31 +-
src/mem3/src/mem3_sync.erl | 43 +-
src/mem3/src/mem3_sync_event_listener.erl | 4 +-
src/mem3/src/mem3_sync_security.erl | 2 +-
src/mem3/src/mem3_util.erl | 99 +-
src/mem3/test/eunit/mem3_distribution_test.erl | 5 +-
src/mem3/test/eunit/mem3_rep_test.erl | 10 +-
.../test/eunit/mem3_reshard_changes_feed_test.erl | 10 +-
src/mem3/test/eunit/mem3_reshard_test.erl | 79 +-
src/mem3/test/eunit/mem3_shards_test.erl | 77 +-
src/mem3/test/eunit/mem3_zone_test.erl | 77 +
src/nouveau/src/nouveau.app.src | 2 +-
src/nouveau/src/nouveau_api.erl | 298 +-
src/nouveau/src/nouveau_bookmark.erl | 2 +-
src/nouveau/src/nouveau_fabric_cleanup.erl | 70 +-
src/nouveau/src/nouveau_gun.erl | 162 +
src/nouveau/src/nouveau_index_manager.erl | 33 -
src/nouveau/src/nouveau_index_updater.erl | 46 +-
src/nouveau/src/nouveau_rpc.erl | 76 +-
src/nouveau/src/nouveau_sup.erl | 1 +
src/nouveau/src/nouveau_util.erl | 30 +-
src/rexi/src/rexi.erl | 2 +-
src/rexi/src/rexi_monitor.erl | 2 +-
src/rexi/src/rexi_server.erl | 2 +-
src/rexi/src/rexi_server_mon.erl | 9 +-
src/rexi/src/rexi_utils.erl | 2 +-
src/rexi/test/rexi_tests.erl | 4 +-
src/setup/src/setup.erl | 2 +-
src/setup/test/t-frontend-setup.sh | 4 +-
src/smoosh/src/smoosh.erl | 9 +-
src/smoosh/src/smoosh_channel.erl | 14 +-
src/smoosh/src/smoosh_persist.erl | 4 +-
src/smoosh/test/smoosh_tests.erl | 16 +-
.../src/weatherreport_check_mem3_sync.erl | 2 +-
.../src/weatherreport_check_node_stats.erl | 2 +-
.../src/weatherreport_check_nodes_connected.erl | 2 +-
.../src/weatherreport_check_process_calls.erl | 2 +-
src/weatherreport/src/weatherreport_getopt.erl | 2 +-
src/weatherreport/src/weatherreport_node.erl | 2 +-
src/weatherreport/src/weatherreport_util.erl | 2 +-
test/elixir/lib/asserts.ex | 20 +
test/elixir/test/changes_async_test.exs | 2 +-
test/elixir/test/config/nouveau.elixir | 3 +-
test/elixir/test/nouveau_test.exs | 17 +
test/elixir/test/partition_search_test.exs | 47 +-
test/elixir/test/search_test.exs | 83 +-
version.mk | 2 +-
334 files changed, 15388 insertions(+), 6811 deletions(-)
create mode 100644 .elp.toml
rename build-aux/{Jenkinsfile.full => Jenkinsfile} (65%)
delete mode 100644 build-aux/Jenkinsfile.pr
copy nouveau/src/main/java/org/apache/couchdb/nouveau/{core/ser/LongWrapper.java => api/Ok.java} (77%)
create mode 100644 src/couch/src/couch_bt_engine_cache.erl
create mode 100644 src/couch/test/eunit/couch_bt_engine_cache_test.erl
create mode 100644 src/couch/test/eunit/couch_btree_prop_tests.erl
create mode 100644 src/couch_quickjs/patches/02-test262-errors.patch
rename src/couch_quickjs/{update_and_apply_patches.sh => update.sh} (88%)
create mode 100755 src/couch_quickjs/update_patches.sh
create mode 100644 src/fabric/src/fabric_index_cleanup.erl
create mode 100644 src/mem3/src/mem3_db_doc_updater.erl
create mode 100644 src/mem3/test/eunit/mem3_zone_test.erl
create mode 100644 src/nouveau/src/nouveau_gun.erl
create mode 100644 test/elixir/lib/asserts.ex
(couchdb) 03/03: Doc updates for 3.5.1
Posted by va...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
vatamane pushed a commit to branch 3.5.x
in repository https://gitbox.apache.org/repos/asf/couchdb.git
commit 44f6a43d81b83b203a110f6036d107dc2afb5556
Author: Nick Vatamaniuc <va...@gmail.com>
AuthorDate: Thu Oct 30 03:25:45 2025 -0400
Doc updates for 3.5.1
Whatsnew and other fixes
---
src/docs/src/config/misc.rst | 4 +-
src/docs/src/whatsnew/3.5.rst | 145 ++++++++++++++++++++++++++++++++++++++++++
2 files changed, 147 insertions(+), 2 deletions(-)
diff --git a/src/docs/src/config/misc.rst b/src/docs/src/config/misc.rst
index 6c9d6003e..c5843680b 100644
--- a/src/docs/src/config/misc.rst
+++ b/src/docs/src/config/misc.rst
@@ -66,7 +66,7 @@ UUIDs Configuration
.. config:option:: algorithm :: Generation Algorithm
.. versionchanged:: 1.3 Added ``utc_id`` algorithm.
- .. versionchanged:: 3.6 Added ``uuid_v7`` algorithm.
+ .. versionchanged:: 3.5.1 Added ``uuid_v7`` algorithm.
CouchDB provides various algorithms to generate the UUID values that
are used for document `_id`'s by default::
@@ -317,7 +317,7 @@ Configuration of Database Purge
revisions per Purge-Request
.. versionadded:: 3.0
- .. versionchanged:: 3.6
+ .. versionchanged:: 3.5.1
Sets the maximum number of accumulated revisions allowed in a single purge
request::
diff --git a/src/docs/src/whatsnew/3.5.rst b/src/docs/src/whatsnew/3.5.rst
index 02124d611..b4c560f96 100644
--- a/src/docs/src/whatsnew/3.5.rst
+++ b/src/docs/src/whatsnew/3.5.rst
@@ -20,6 +20,151 @@
:depth: 1
:local:
+.. _release/3.5.1:
+
+Version 3.5.1
+=============
+
+Features
+--------
+
+* :ghissue:`5626`, :ghissue:`5665`: Debian Trixie support
+* :ghissue:`5709`: Automatic Nouveau and Clouseau index cleanup
+* :ghissue:`5697`: Add UUID v7 as a ``uuid`` algorithm option. The default is
+ still the default ``sequential`` algorithm.
+* :ghissue:`5713`, :ghissue:`5697`, :ghissue:`5701`, :ghissue:`5704`: Purge
+ improvements and fixes. Optimize it up to ~30% faster for large batches.
+ ``max_document_id_number`` setting was removed and ``max_revisions_number``
+ set to ``unlimited`` by default to match ``_bulk_docs`` and ``_bulk_get``
+ endpoints.
+* :ghissue:`5611`: Implement the ability to downgrade CouchDB versions
+* :ghissue:`5588`: Populate zone from ``COUCHDB_ZONE`` env variable in Docker
+* :ghissue:`5563`: Set Erlang/OTP 26 as minimum supported version
+* :ghissue:`5546`, :ghissue:`5641`: Improve Clouseau service checks in
+ ``clouseau_rpc`` module.
+* :ghissue:`5639`: Use OS certificates for replication
+* :ghissue:`5728`: Configurable reduce limit threshold and ratio
+
+Performance
+-----------
+
+* :ghissue:`5625`: BTree engine term cache
+* :ghissue:`5617`: Optimize Nouveau searches when index is fresh
+* :ghissue:`5598`: Use HTTP/2 for Nouveau
+* :ghissue:`5701`: Optimize revid parsing: 50-90% faster. Should help purge
+ requests as well as ``_bulk_docs`` and ``_bulk_get`` endpoints.
+* :ghissue:`5564`: Use the built-in binary hex encode
+* :ghissue:`5613`: Improve scanner performance
+* :ghissue:`5545`: Bump process limit to 1M
+
+Bugfixes
+--------
+
+* :ghissue:`5722`, :ghissue:`5683`, :ghissue:`5678`, :ghissue:`5646`,
+ :ghissue:`5630`, :ghissue:`5615`, :ghissue:`5696`: Scanner fixes. Add write
+ limiting and switch to traversing documents by sequence IDs instead of by
+ document IDs.
+* :ghissue:`5707`, :ghissue:`5706`, :ghissue:`5706`, :ghissue:`5694`,
+ :ghissue:`5691`, :ghissue:`5669`, :ghissue:`5629`, :ghissue:`5574`,
+ :ghissue:`5573`, :ghissue:`5566`, :ghissue:`5553`, :ghissue:`5550`,
+ :ghissue:`5534`, :ghissue:`5730`: QuickJS Updates. Optimized string operations,
+ faster context creation, a lot of bug fixes.
+* :ghissue:`5719`: Use "all" ring options for purged_infos
+* :ghissue:`5649`: Retry call to dreyfus index on noproc errors
+* :ghissue:`5663`: More informative error if epochs out of order
+* :ghissue:`5649`: Dreyfus retries on error
+* :ghissue:`5643`: Fix reduce_limit = log feature
+* :ghissue:`5620`: Use copy_props in the compactor instead of set_props
+* :ghissue:`5632`, :ghissue:`5627`, :ghissue:`5607`: Nouveau fixes. Enhance
+ ``_nouveau_cleanup``. Improve security on http/2.
+* :ghissue:`5614`: Stop replication jobs to nodes which are not part of the cluster
+* :ghissue:`5596`: Fix query args parsing during cluster upgrades
+* :ghissue:`5595`: Make replicator shutdown a bit more orderly
+* :ghissue:`5595`: Avoid making a mess in the logs when stopping replicator app
+* :ghissue:`5588`: Fix ``couch_util:set_value/3``
+* :ghissue:`5587`: Improve ``mem3_rep:find_source_seq/4`` logging
+* :ghissue:`5586`: Don't wait indefinitely for replication jobs to stop
+* :ghissue:`5578`: Use ``[sync]`` option in ``couch_bt_engine:commit_data/1``
+* :ghissue:`5556`: Add guards to ``fabric:design_docs/1`` to prevent
+ ``function_clause`` error
+* :ghissue:`5555`: Improve replicator client mailbox flush
+* :ghissue:`5551`: Handle ``bad_generator`` and ``case_clause`` in ``ken_server``
+* :ghissue:`5552`: Improve cluster startup logging
+* :ghissue:`5552`: Improve mem3 supervisor
+* :ghissue:`5552`: Handle shard opener tables not being initializes better
+* :ghissue:`5549`: Don't spawn more than one ``init_delete_dir`` instance
+* :ghissue:`5535`: Disk monitor always allows ``mem3_rep`` checkpoints
+* :ghissue:`5536`: Fix ``mem3_util`` overlapping shards
+* :ghissue:`5533`: No cfile support for 32bit systems
+* :ghissue:`5688`: Handle timeout in ``dreyfus_fabric_search``
+* :ghissue:`5548`: Fix config key typo in mem3_reshard_dbdoc
+* :ghissue:`5540`: Ignore extraneous cookie in replicator session plugin
+
+Cleanups
+--------
+
+* :ghissue:`5717`: Do not check for Dreyfus. It's part of the tree now.
+* :ghissue:`5715`: Remove Hastings references
+* :ghissue:`5714`: Cleanup fabric r/w parameter handling
+* :ghissue:`5693`: Remove explicit erlang module prefix for auto-imported functions
+* :ghissue:`5686`: Remove ``erlang:`` prefix from ``erlang:error()``
+* :ghissue:`5686`: Fix ``case_clause`` when got ``missing_target`` error
+* :ghissue:`5690`: Fix props caching in mem3
+* :ghissue:`5680`: Implement db doc updating
+* :ghissue:`5666`: Replace ``gen_server:format_status/2`` with ``format_status/1``
+* :ghissue:`5672`: Cache and store mem3 shard properties in one place only
+* :ghissue:`5644`: Remove redundant ``*_to_list`` / ``list_to_*`` conversion
+* :ghissue:`5633`: Use ``config:get_integer/3`` in couch_btree
+* :ghissue:`5618`: DRY out ``couch_bt_engine`` header pointer term access
+* :ghissue:`5614`: Stop replication jobs to nodes which are not part of the cluster
+* :ghissue:`5610`: Add a ``range_to_hex/1`` utility function
+* :ghissue:`5565`: Use maps comprehensions and generators in a few places
+* :ghissue:`5649`: Remove pointless message
+* :ghissue:`5649`: Remove obsolete clauses from dreyfus
+* :ghissue:`5621`: Minor couch_btree refactoring
+
+Docs
+----
+
+* :ghissue:`5705`: Docs: Update the /_up endpoint docs to include status responses
+* :ghissue:`5653`: Document that _all_dbs endpoint supports inclusive_end query param
+* :ghissue:`5575`: Document how to mitigate high memory usage in docker
+* :ghissue:`5600`: Avoid "master" wording at setup cluster
+* :ghissue:`5381`: Change unauthorized example to 401 for replication
+* :ghissue:`5682`: Update install instructions
+* :ghissue:`5674`: Add setup documentation for two factor authentication
+* :ghissue:`5562`: Add AI policy
+* :ghissue:`5548`: Fix reshard doc section name
+* :ghissue:`5543`: Add ``https`` to allowed replication proxy protocols
+
+Tests/CI/Builds
+---------------
+
+* :ghissue:`5720`: Update deps: Fauxton, meck and PropEr
+* :ghissue:`5708`: Improve search test
+* :ghissue:`5702`: Increase timeout for `process_response/3` to fix flaky tests
+* :ghissue:`5703`: Use deterministic doc IDs in Mango key test
+* :ghissue:`5692`: Implement 'assert_on_status' macro
+* :ghissue:`5684`: Sequester docker ARM builds and fail early
+* :ghissue:`5679`: Add ``--disable-spidermonkey`` to ``--dev[-with-nouveau]``
+* :ghissue:`5671`: Print request/response body on errors from mango test suite
+* :ghissue:`5670`: Fix ``make clean`` after ``dev/run --enable-tls``
+* :ghissue:`5668`: Update xxHash
+* :ghissue:`5667`: Update mochiweb to v3.3.0
+* :ghissue:`5664`: Disable ppc64le and s390x builds
+* :ghissue:`5604`: Use ASF fork of ``gun`` for ``cowlib`` dependency
+* :ghissue:`5636`: Reduce btree prop test count a bit
+* :ghissue:`5633`: Fix and improve couch_btree testing
+* :ghissue:`5572`: Remove a few more instances of Ubuntu Focal
+* :ghissue:`5571`: Upgrade Erlang for CI
+* :ghissue:`5570`: Skip macos CI for now and remove Ubuntu Focal
+* :ghissue:`5488`: Bump Clouseau to 2.25.0
+* :ghissue:`5541`: Enable Clouseau for the Windows CI
+* :ghissue:`5537`: Add retries to native full CI stage
+* :ghissue:`5531`: Fix Erlang cookie configuration in ``dev/run``
+* :ghissue:`5662`: Remove old Jenkinsfiles
+* :ghissue:`5661`: Unify CI jobs
+
.. _release/3.5.0:
Version 3.5.0
(couchdb) 01/03: Cherry-pick main changes into 3.5.x
Posted by va...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
vatamane pushed a commit to branch 3.5.x
in repository https://gitbox.apache.org/repos/asf/couchdb.git
commit 0f7f208dccfeba1cc69081f4c27a018a72f92ecb
Author: Nick Vatamaniuc <va...@gmail.com>
AuthorDate: Mon May 5 13:10:31 2025 -0400
Cherry-pick main changes into 3.5.x
This is an amalgamated commit from these commits:
edit d6e284e58 # Protect 3.5.x branch
fixup 0b85b414a # dev/run: complete Erlang cookie configuration
fixup 9cd775263 # No cfile support for 32bit systems
fixup 8ae40d887 # Update QuickJS: FP16 support, regex escape compat
fixup 942c94e3b # Fix mem3_util overlapping shards
fixup c6fc3cb77 # Always allow mem3_rep checkpoints
fixup 5693d7251 # Add retries to native full CI stage
fixup 1fe50d703 # Ignore extraneous cookie in replicator session plugin
fixup 03f0acc5a # Enable Clouseau for the Windows CI
fixup 0da8cf2d4 # Bump Clouseau to 2.25.0
fixup ed763ef59 # Bump process limit to 1M
fixup 234a01f15 # doc: add https to allowed replication proxy protocols
fixup 859fbcdba # Improve `couch_debug.erl` (#5542)
fixup fa2d5243d # Fix config key typo in mem3_reshard_dbdoc
fixup fdb7cc156 # Fix reshard doc section name
fixup 7397df54a # Don't spawn more than one init_delete_dir instance
fixup 65f97ae54 # Improve init_delete_dir
fixup 6e885301c # QuickJS update
fixup 88f424cc9 # Improve `clouseau_rpc.erl`
fixup 0c6237e59 # Handle shard opener tables not being initializes better
fixup dc9837f04 # Improve mem3 supervisor
fixup 2574fd18c # Improve cluster startup logging
fixup adbc9489b # Fix QuickJS bigint heap overflow
fixup 3cfd7e418 # Handle `bad_generator` and `case_clause` in ken_server
fixup 7ef02ab16 # Improve replicator client mailbox flush
fixup 20701cb68 # Add guards to `fabric:design_docs/1` to prevent function_clause error
fixup b2cbfb875 # Bump requests to 2.32.4 and set trust_env=False
fixup 004783446 # Set Erlang/OTP 26 as minimum supported version
fixup 87007992e # Use the built-in binary hex encode
fixup fff371bc1 # Use maps comprehensions and generators in a few places
fixup cedeb738e # doc: add AI policy h/t @dch
fixup 7a8e19ecb # Remove lto for quickjs
fixup a179d0c82 # Skip macos CI for now and remove Ubuntu Focal
fixup 02e2930ef # Upgrade Erlang for CI
fixup 5ee3d737c # Remove a few more instances of Ubuntu Focal
fixup 1a58a1cf7 # Update QuickJS
fixup 6e0e8f39c # Run test262 JS conformance tests for QuickJS
fixup bd0139e62 # Document how to mitigate high memory usage in docker
fixup 1b62f06ea # wip suggestion for fsync pr
fixup 5e658d324 # Add tests for write_header/3 with [sync]
fixup ce1042338 # Use couch_file:write_header(., [sync]) in couch_bt_engine:commit_data/1
fixup 8f2c253fd # docs/replication: change unauthorized example to 401
fixup aae623bce # Don't wait indefinitely for replication jobs to stop
fixup e3e445f28 # Improve mem3_rep:find_source_seq/4 logging
fixup 58c56148e # fix couch_util:set_value/3
fixup 2cf6e558b # Populate zone from `COUCHDB_ZONE` env variable
fixup febba3efa # update docs
fixup 66ed28358 # Avoid making a mess in the logs when stopping replicator app
fixup a5db3138e # Make replicator shutdown a bit more orderly
fixup 786dc5d13 # Fix query args parsing during cluster upgrades
fixup 9b2c1febd # Print the name of the failed property test
fixup c609d4779 # nouveau: use http/2
fixup 4d24a701c # chore(docs): avoid master wording at setup cluster
fixup 074e3a476 # don't start gun if nouveau disabled
fixup 2fc406b8a # address PR feedback - move state to gen_server
fixup b7adda961 # use ASF fork of gun for cowlib dep
fixup 25acff4e7 # fix CI
fixup 66996a1cd # docs: securing nouveau on http/2
fixup b936d99ff # Increase some test timeouts to hopefully fix a flaky PPC64LE test
fixup e5175d1d6 # Add a range_to_hex/1 utility function
fixup 540ca24d9 # Improve scanner performance
fixup bdc7904b0 # Stop replication jobs to nodes which are not part of the cluster
fixup b22adbb2e # In the scanner, traverse docs by sequence instead of by ID.
fixup 27888d91e # DRY out couch_bt_engine header pointer term access
fixup d25ff9175 # Implement the ability to downgrade CouchDB versions
fixup f8c5938c7 # allow stale queries
fixup a2ae7e332 # optimize searches when index is fresh
fixup 2e49f7477 # stale test
fixup 35f3d4f6d # Use copy_props in the compactor instead of set_props
fixup bf8f48978 # Minor couch_btree refactoring
fixup bb2083096 # retry if no connection available
fixup 36b19b46d # switch to couch_util:to_hex_bin
fixup 0c15f0f92 # gun takes iodata so no need for io_lib or flatten
fixup 7a1584086 # QuickJS Update
fixup 8c3df0385 # include rev when scanning
fixup 866348c60 # Avoid timeouts in ddoc scanner callback
fixup 044f74641 # enhance _nouveau_cleanup
fixup 89b42aba0 # BTree engine term cache
fixup 6568e2a4f # Use config:get_integer/3 in couch_btree
fixup 6fb33bab3 # Fix and improve couch_btree testing
fixup d4f421184 # Prevent B-tree duplicate entries. Add property tests.
fixup 9db197a60 # Reduce btree prop test count a bit
fixup 29518a402 # Use OS certificates for replication
fixup 8f086d17e # Allow user to customize the `Timeout` threshold for checking search services
fixup df2ff6342 # Remove redundant *_to_list / list_to_* conversion
fixup 4a6ce811f # Fix reduce_limit = log feature
fixup 5ccfa2e77 # Configure ELP
fixup 00b6849f5 # Add write limiting to the scanner
fixup 2802610b5 # Upgrade erlfmt and rebar3
fixup 0cc1ba499 # Implement prop updates for shards
fixup 29f3992bb # Document that _all_dbs endpoint supports inclusive_end query param
fixup 8db6286f4 # Retry call to dreyfus index on noproc errors
fixup a0b43b120 # Remove absolete clauses from dreyfus
fixup f51f6084f # Remove pointless message
fixup 0e1591556 # Add delay before retry
fixup e4979be7e # dev: support multiarch names (Debian based systems) (#5626)
fixup 3bf07be54 # Use upgraded Erlang CI images
fixup 3969b4019 # fix homebrew spidermonkey build
fixup d17400591 # fix centos/freebsd build
fixup 030bb8fee # Unify CI jobs
fixup 2a96d0f01 # Remove old Jenkinsfiles
fixup 420863397 # more informative error if epochs out of order
fixup c3c98e249 # Disable ppc64le and s390x builds
fixup 3444f5224 # Add Trixie to CI
fixup e1c60c30d # Update mochiweb to v3.3.0
fixup b2a5a93dc # Update xxHash
fixup 7a32ab7aa # Update QuickJS
fixup 7bcf1a5a9 # fix make clean after dev/run --enable-tls
fixup 3754deb3a # Cache and store mem3 shard properties in one place only
fixup 2caf34166 # Print request/response body on errors from mango test suite
fixup 8ab2dbc2e # Add setup documentation for two factor authentication (#5674)
fixup fffa62e4a # Replace `gen_server:format_status/2` with `format_status/1`
fixup c52d67d2c # Fix config options (#5642)
fixup 01520a69e # Handle plugin stops without crashing
fixup e65aa5ecc # Reschedule scanner plugins if they return skip on start or resume
fixup 55b53273c # feat(configure): add --disable-spidermonkey to --dev[-with-nouveau]
fixup 4f7f46f27 # Implement db doc updating
fixup ba771b49b # Update QuickJS
fixup 7066c8e43 # doc: update install instructions
fixup 1908ea2c8 # Fix run_on_first_node scanner features
fixup ee2bfe8f0 # Sequestrate docker ARM builds and fail early
fixup 0266498eb # Handle timeout in `dreyfus_fabric_search:go`
fixup abe1f6efa # Fix props caching in mem3
fixup 1eb2ea54d # QuickJS Update
fixup 31de49a20 # Fix `case_clause` when got `missing_target` error
fixup dac11b247 # Remove `erlang:` prefix from `erlang:error()`
fixup d00248097 # Remove explicit erlang module prefix for auto-imported functions
fixup d377697bc # Add assert comments to search related elixir tests
fixup 0a1e26420 # Implement 'assert_on_status' macro
fixup 639656802 # More QuickJS Optimization
fixup 55fc7cba7 # Tighten the rules for parsing time periods
fixup 2fc64fd28 # Add UUID v7
fixup 66a053c83 # Optimize purge
fixup 7c33b2851 # Replace `dbg:stop_clear/0` with `dbg:stop/0`
fixup 7ada53925 # Optimize revid parsing: 50-90% faster
fixup cc27d73d0 # Use determistic doc IDs in Mango key test
fixup 83aa0daf8 # Docs: Update the /_up endpoint docs to include status response's
fixup 3b056091b # Remove purge max_document_id_number and change max_revisions_number
fixup 3ecef046f # Update QuickJS: faster context creation and faster dbuf
fixup e76a8b6ba # Increase timeout for `process_response/3` to fix flaky tests
fixup 416e0776e # QuickJS Update. Optimized string operations.
fixup 2903cd5f0 # improve search test
fixup 2a9c1bd41 # Avoid using function closures in mem3
fixup 76577f3ab # Optimize purge. ~30% for large batches.
fixup 0182fd1cf # Improve index cleanup
fixup c543a88d7 # Cleanup fabric r/w parameter handling
fixup 743312c75 # Remove hastings references
fixup 74039c4c7 # Do not check for dreyfus
fixup db57168cf # fixup: remove HAVE_DREYFUS refs
fixup 458bc0de8 # Update elp toml file
fixup e3583db45 # Use "all" ring options for purged_infos
fixup 39cb8c539 # Update deps: fauxton, meck and proper
fixup 516df2387 # Fix typo in .elp.toml
fixup 53a6db7fd # Ignore design docs in the shards db in the scanner
fixup da9afabb9 # Update Quickjs: optimize global var access, fix use-after-free error
fixup df9a9a732 # Fix a few regressions recent updates
fixup c71e71730 # parameterise reduce_limit threshold and ratio
---
.asf.yaml | 3 +
.elp.toml | 38 +
.gitignore | 2 +
CONTRIBUTING.md | 13 +
INSTALL.Unix.md | 18 +-
Makefile | 19 +-
Makefile.win | 4 +
README-DEV.rst | 12 +-
build-aux/{Jenkinsfile.full => Jenkinsfile} | 387 +-
build-aux/Jenkinsfile.pr | 293 -
build-aux/xref-helper.sh | 1 -
configure | 10 +-
configure.ps1 | 8 +-
dev/run | 23 +-
.../java/org/apache/couchdb/nouveau/api/Ok.java | 26 +
.../apache/couchdb/nouveau/core/IndexManager.java | 61 +-
.../couchdb/nouveau/resources/IndexResource.java | 26 +-
.../couchdb/nouveau/core/IndexManagerTest.java | 77 +-
rebar.config.script | 13 +-
rel/nouveau.yaml | 4 +-
rel/overlay/etc/default.ini | 110 +-
rel/overlay/etc/vm.args | 11 +
rel/reltool.config | 4 +
share/server/views.js | 4 +-
src/chttpd/src/chttpd_db.erl | 40 +-
src/chttpd/src/chttpd_external.erl | 2 +-
src/chttpd/src/chttpd_misc.erl | 4 +-
src/chttpd/src/chttpd_node.erl | 3 +-
.../eunit/chttpd_auth_hash_algorithms_tests.erl | 2 +-
src/chttpd/test/eunit/chttpd_purge_tests.erl | 34 +-
src/config/src/config.erl | 4 +-
src/config/src/config_listener_mon.erl | 2 +-
src/config/test/config_tests.erl | 38 +-
src/couch/include/couch_db.hrl | 10 -
src/couch/include/couch_eunit.hrl | 2 +-
src/couch/include/couch_eunit_proper.hrl | 4 +-
src/couch/priv/couch_cfile/couch_cfile.c | 30 +-
src/couch/priv/stats_descriptions.cfg | 12 +
src/couch/rebar.config.script | 64 +-
src/couch/src/couch_att.erl | 12 +-
src/couch/src/couch_base32.erl | 2 +-
src/couch/src/couch_bt_engine.erl | 191 +-
src/couch/src/couch_bt_engine_cache.erl | 292 +
src/couch/src/couch_bt_engine_compactor.erl | 6 +-
src/couch/src/couch_bt_engine_header.erl | 80 +-
src/couch/src/couch_btree.erl | 362 +-
src/couch/src/couch_db.erl | 78 +-
src/couch/src/couch_db_updater.erl | 53 +-
src/couch/src/couch_debug.erl | 55 +-
src/couch/src/couch_doc.erl | 30 +-
src/couch/src/couch_file.erl | 77 +-
src/couch/src/couch_flags_config.erl | 2 +-
src/couch/src/couch_httpd_auth.erl | 4 +-
src/couch/src/couch_httpd_db.erl | 2 +-
src/couch/src/couch_httpd_multipart.erl | 10 +-
src/couch/src/couch_httpd_vhost.erl | 2 +-
src/couch/src/couch_key_tree.erl | 6 +-
src/couch/src/couch_multidb_changes.erl | 8 +-
src/couch/src/couch_native_process.erl | 6 +-
src/couch/src/couch_os_process.erl | 6 +-
src/couch/src/couch_primary_sup.erl | 3 +-
src/couch/src/couch_proc_manager.erl | 24 +-
src/couch/src/couch_query_servers.erl | 13 +-
src/couch/src/couch_server.erl | 11 +-
src/couch/src/couch_stream.erl | 4 +-
src/couch/src/couch_task_status.erl | 4 +-
src/couch/src/couch_util.erl | 99 +-
src/couch/src/couch_uuids.erl | 32 +-
src/couch/src/test_util.erl | 6 +-
.../test/eunit/couch_bt_engine_cache_test.erl | 102 +
.../eunit/couch_bt_engine_compactor_ev_tests.erl | 6 +-
.../test/eunit/couch_bt_engine_compactor_tests.erl | 4 +-
src/couch/test/eunit/couch_btree_prop_tests.erl | 225 +
src/couch/test/eunit/couch_btree_tests.erl | 108 +-
src/couch/test/eunit/couch_changes_tests.erl | 6 +-
src/couch/test/eunit/couch_file_tests.erl | 83 +
src/couch/test/eunit/couch_index_tests.erl | 2 +-
src/couch/test/eunit/couch_query_servers_tests.erl | 142 +-
src/couch/test/eunit/couch_server_tests.erl | 8 +-
src/couch/test/eunit/couch_stream_tests.erl | 2 +-
src/couch/test/eunit/couch_task_status_tests.erl | 4 +-
src/couch/test/eunit/couch_work_queue_tests.erl | 4 +-
src/couch/test/eunit/couchdb_attachments_tests.erl | 2 +-
.../test/eunit/couchdb_file_compression_tests.erl | 2 +-
src/couch/test/eunit/couchdb_os_proc_pool.erl | 10 +-
.../test/eunit/couchdb_update_conflicts_tests.erl | 6 +-
src/couch/test/eunit/couchdb_vhosts_tests.erl | 22 +-
src/couch/test/eunit/couchdb_views_tests.erl | 12 +-
src/couch_event/src/couch_event_listener.erl | 20 +-
src/couch_event/src/couch_event_listener_mfa.erl | 6 +-
src/couch_event/src/couch_event_server.erl | 6 +-
src/couch_index/src/couch_index.erl | 4 +-
src/couch_index/src/couch_index_server.erl | 2 +-
src/couch_index/src/couch_index_util.erl | 47 +
.../test/eunit/couch_index_ddoc_updated_tests.erl | 4 +-
src/couch_log/src/couch_log_config.erl | 2 +-
src/couch_log/src/couch_log_trunc_io.erl | 10 +-
src/couch_log/src/couch_log_trunc_io_fmt.erl | 14 +-
.../test/eunit/couch_log_config_listener_test.erl | 4 +-
.../test/eunit/couch_log_formatter_test.erl | 64 +-
src/couch_log/test/eunit/couch_log_server_test.erl | 4 +-
src/couch_log/test/eunit/couch_log_test_util.erl | 4 +-
src/couch_mrview/src/couch_mrview.erl | 18 +-
src/couch_mrview/src/couch_mrview_cleanup.erl | 51 +-
src/couch_mrview/src/couch_mrview_compactor.erl | 8 +-
src/couch_mrview/src/couch_mrview_index.erl | 4 +-
src/couch_mrview/src/couch_mrview_test_util.erl | 2 +-
src/couch_mrview/src/couch_mrview_updater.erl | 8 +-
src/couch_mrview/src/couch_mrview_util.erl | 66 +-
.../test/eunit/couch_mrview_collation_tests.erl | 6 +-
.../test/eunit/couch_mrview_compact_tests.erl | 8 +-
.../test/eunit/couch_mrview_ddoc_updated_tests.erl | 6 +-
.../eunit/couch_mrview_purge_docs_fabric_tests.erl | 2 +-
.../test/eunit/couch_mrview_purge_docs_tests.erl | 6 +-
.../test/eunit/couch_mrview_util_tests.erl | 28 +
src/couch_peruser/src/couch_peruser.erl | 2 +-
src/couch_prometheus/src/couch_prometheus.erl | 20 +-
.../test/eunit/couch_prometheus_e2e_tests.erl | 6 +-
src/couch_pse_tests/src/cpse_test_ref_counting.erl | 8 +-
src/couch_pse_tests/src/cpse_util.erl | 18 +-
src/couch_quickjs/.gitignore | 2 +
src/couch_quickjs/c_src/couchjs.c | 27 +-
.../patches/01-spidermonkey-185-mode.patch | 6 +-
src/couch_quickjs/patches/02-test262-errors.patch | 11 +
src/couch_quickjs/quickjs/Changelog | 28 +
src/couch_quickjs/quickjs/Makefile | 13 +
src/couch_quickjs/quickjs/VERSION | 2 +-
src/couch_quickjs/quickjs/cutils.c | 52 +-
src/couch_quickjs/quickjs/cutils.h | 102 +-
src/couch_quickjs/quickjs/libregexp-opcode.h | 12 +-
src/couch_quickjs/quickjs/libregexp.c | 1019 ++-
src/couch_quickjs/quickjs/libregexp.h | 1 +
src/couch_quickjs/quickjs/libunicode-table.h | 421 +-
src/couch_quickjs/quickjs/libunicode.c | 237 +-
src/couch_quickjs/quickjs/libunicode.h | 14 +-
src/couch_quickjs/quickjs/qjsc.c | 107 +-
src/couch_quickjs/quickjs/quickjs-atom.h | 14 +
src/couch_quickjs/quickjs/quickjs-libc.c | 260 +-
src/couch_quickjs/quickjs/quickjs-libc.h | 8 +-
src/couch_quickjs/quickjs/quickjs-opcode.h | 15 +-
src/couch_quickjs/quickjs/quickjs.c | 8586 ++++++++++++++------
src/couch_quickjs/quickjs/quickjs.h | 81 +-
src/couch_quickjs/quickjs/run-test262.c | 114 +-
src/couch_quickjs/quickjs/test262.conf | 93 +-
src/couch_quickjs/quickjs/test262_errors.txt | 131 +-
src/couch_quickjs/quickjs/tests/test262.patch | 41 +-
src/couch_quickjs/rebar.config.script | 22 +-
.../src/couch_quickjs_scanner_plugin.erl | 9 +-
.../{update_and_apply_patches.sh => update.sh} | 8 +-
src/couch_quickjs/update_patches.sh | 28 +
.../src/couch_replicator_api_wrap.erl | 18 +-
.../src/couch_replicator_auth_session.erl | 38 +-
.../src/couch_replicator_connection.erl | 3 +
.../src/couch_replicator_doc_processor_worker.erl | 2 +-
src/couch_replicator/src/couch_replicator_docs.erl | 2 +-
.../src/couch_replicator_fabric.erl | 2 +-
.../src/couch_replicator_fabric_rpc.erl | 10 +-
.../src/couch_replicator_httpc.erl | 165 +-
.../src/couch_replicator_httpc_pool.erl | 51 +-
.../src/couch_replicator_notifier.erl | 30 +-
.../src/couch_replicator_parse.erl | 25 +-
src/couch_replicator/src/couch_replicator_pg.erl | 14 +-
.../src/couch_replicator_rate_limiter.erl | 6 +-
.../src/couch_replicator_scheduler.erl | 913 ++-
.../src/couch_replicator_scheduler_job.erl | 130 +-
.../src/couch_replicator_utils.erl | 54 +-
.../src/couch_replicator_worker.erl | 82 +-
src/couch_replicator/src/json_stream_parse.erl | 2 +-
.../test/eunit/couch_replicator_compact_tests.erl | 26 +-
.../eunit/couch_replicator_connection_tests.erl | 2 +-
.../couch_replicator_error_reporting_tests.erl | 2 +-
.../eunit/couch_replicator_httpc_pool_tests.erl | 2 +-
.../eunit/couch_replicator_rate_limiter_tests.erl | 2 +-
...ch_replicator_retain_stats_between_job_runs.erl | 6 +-
...ch_replicator_small_max_request_size_target.erl | 2 +-
.../test/eunit/couch_replicator_test_helper.erl | 2 +-
src/couch_scanner/src/couch_scanner_plugin.erl | 193 +-
.../src/couch_scanner_plugin_conflict_finder.erl | 10 +-
.../src/couch_scanner_plugin_find.erl | 10 +-
.../src/couch_scanner_rate_limiter.erl | 56 +-
src/couch_scanner/src/couch_scanner_server.erl | 2 +
src/couch_scanner/src/couch_scanner_util.erl | 35 +-
.../test/eunit/couch_scanner_test.erl | 54 +-
src/couch_stats/src/couch_stats_httpd.erl | 4 +-
.../src/couch_stats_process_tracker.erl | 2 +-
src/custodian/src/custodian_util.erl | 2 +-
src/ddoc_cache/src/ddoc_cache_entry.erl | 16 +-
.../src/ddoc_cache_entry_validation_funs.erl | 13 +-
src/ddoc_cache/src/ddoc_cache_lru.erl | 2 +-
.../test/eunit/ddoc_cache_coverage_test.erl | 4 +-
.../test/eunit/ddoc_cache_entry_test.erl | 4 +-
src/ddoc_cache/test/eunit/ddoc_cache_lru_test.erl | 12 +-
.../test/eunit/ddoc_cache_open_error_test.erl | 2 +-
src/ddoc_cache/test/eunit/ddoc_cache_open_test.erl | 2 +-
.../test/eunit/ddoc_cache_remove_test.erl | 4 +-
src/ddoc_cache/test/eunit/ddoc_cache_tutil.erl | 2 +-
src/docs/src/api/database/changes.rst | 5 +-
src/docs/src/api/server/authn.rst | 91 +
src/docs/src/api/server/common.rst | 20 +-
src/docs/src/cluster/databases.rst | 3 +
src/docs/src/cluster/purging.rst | 4 +-
src/docs/src/cluster/sharding.rst | 5 +-
src/docs/src/cluster/troubleshooting.rst | 2 +-
src/docs/src/config/misc.rst | 33 +-
src/docs/src/config/query-servers.rst | 14 +-
src/docs/src/config/replicator.rst | 16 +-
src/docs/src/config/resharding.rst | 2 +-
src/docs/src/config/scanner.rst | 19 +
src/docs/src/ddocs/ddocs.rst | 3 +
src/docs/src/install/nouveau.rst | 11 +-
src/docs/src/install/troubleshooting.rst | 10 +
src/docs/src/install/unix.rst | 3 +-
src/docs/src/replication/protocol.rst | 2 +-
src/docs/src/setup/cluster.rst | 2 +-
src/dreyfus/src/clouseau_rpc.erl | 90 +-
src/dreyfus/src/dreyfus_fabric_cleanup.erl | 122 +-
src/dreyfus/src/dreyfus_fabric_group1.erl | 4 +-
src/dreyfus/src/dreyfus_fabric_group2.erl | 4 +-
src/dreyfus/src/dreyfus_fabric_search.erl | 4 +-
src/dreyfus/src/dreyfus_index.erl | 11 +-
src/dreyfus/src/dreyfus_rpc.erl | 47 +-
src/dreyfus/src/dreyfus_util.erl | 34 +-
src/dreyfus/test/eunit/dreyfus_purge_test.erl | 8 +-
src/ets_lru/src/ets_lru.erl | 2 +-
src/ets_lru/test/ets_lru_test.erl | 4 +-
src/exxhash/README.md | 2 +-
src/exxhash/c_src/xxhash.h | 207 +-
src/fabric/src/fabric.erl | 79 +-
src/fabric/src/fabric_db_create.erl | 8 +-
src/fabric/src/fabric_db_delete.erl | 2 +-
src/fabric/src/fabric_db_meta.erl | 25 +-
src/fabric/src/fabric_db_purged_infos.erl | 17 +-
src/fabric/src/fabric_db_update_listener.erl | 10 +-
src/fabric/src/fabric_doc_open.erl | 20 +-
src/fabric/src/fabric_doc_open_revs.erl | 5 +-
src/fabric/src/fabric_doc_purge.erl | 523 +-
src/fabric/src/fabric_doc_update.erl | 3 +-
src/fabric/src/fabric_index_cleanup.erl | 81 +
src/fabric/src/fabric_open_revs.erl | 3 +-
src/fabric/src/fabric_rpc.erl | 53 +-
src/fabric/src/fabric_streams.erl | 14 +-
src/fabric/src/fabric_util.erl | 184 +-
src/fabric/src/fabric_view_all_docs.erl | 6 +-
src/fabric/src/fabric_view_changes.erl | 4 +-
src/fabric/src/fabric_view_map.erl | 2 +-
src/fabric/test/eunit/fabric_bench_test.erl | 2 +-
src/fabric/test/eunit/fabric_db_info_tests.erl | 38 +-
.../test/eunit/fabric_moved_shards_seq_tests.erl | 2 +-
src/fabric/test/eunit/fabric_rpc_purge_tests.erl | 8 +-
src/fabric/test/eunit/fabric_rpc_tests.erl | 2 +-
src/fabric/test/eunit/fabric_tests.erl | 23 +-
src/global_changes/src/global_changes_server.erl | 4 +-
src/ioq/src/ioq.erl | 4 +-
src/ken/rebar.config.script | 14 +-
src/ken/src/ken.app.src.script | 13 +-
src/ken/src/ken_server.erl | 92 +-
src/ken/test/ken_server_test.erl | 2 +-
src/mango/rebar.config.script | 16 +-
src/mango/requirements.txt | 2 +-
src/mango/src/mango_cursor.erl | 8 -
src/mango/src/mango_cursor_nouveau.erl | 4 +-
src/mango/src/mango_cursor_text.erl | 8 +-
src/mango/src/mango_doc.erl | 10 +-
src/mango/src/mango_idx_special.erl | 8 +-
src/mango/src/mango_json.erl | 2 +-
src/mango/src/mango_native_proc.erl | 2 +-
src/mango/src/mango_selector.erl | 2 +-
src/mango/src/mango_selector_text.erl | 8 +-
src/mango/src/mango_util.erl | 16 +-
src/mango/test/02-basic-find-test.py | 2 +-
src/mango/test/04-key-tests.py | 7 +-
src/mango/test/mango.py | 58 +-
src/mem3/include/mem3.hrl | 4 +-
src/mem3/src/mem3.erl | 74 +-
src/mem3/src/mem3_db_doc_updater.erl | 107 +
src/mem3/src/mem3_hash.erl | 30 +-
src/mem3/src/mem3_httpd.erl | 4 +-
src/mem3/src/mem3_nodes.erl | 61 +-
src/mem3/src/mem3_rep.erl | 23 +-
src/mem3/src/mem3_reshard.erl | 4 +-
src/mem3/src/mem3_reshard_dbdoc.erl | 141 +-
src/mem3/src/mem3_reshard_index.erl | 26 +-
src/mem3/src/mem3_reshard_job.erl | 10 +-
src/mem3/src/mem3_reshard_sup.erl | 3 -
src/mem3/src/mem3_rpc.erl | 10 +-
src/mem3/src/mem3_shards.erl | 387 +-
src/mem3/src/mem3_sup.erl | 31 +-
src/mem3/src/mem3_sync.erl | 43 +-
src/mem3/src/mem3_sync_event_listener.erl | 4 +-
src/mem3/src/mem3_sync_security.erl | 2 +-
src/mem3/src/mem3_util.erl | 99 +-
src/mem3/test/eunit/mem3_distribution_test.erl | 5 +-
src/mem3/test/eunit/mem3_rep_test.erl | 10 +-
.../test/eunit/mem3_reshard_changes_feed_test.erl | 10 +-
src/mem3/test/eunit/mem3_reshard_test.erl | 79 +-
src/mem3/test/eunit/mem3_shards_test.erl | 77 +-
src/mem3/test/eunit/mem3_zone_test.erl | 77 +
src/nouveau/src/nouveau.app.src | 2 +-
src/nouveau/src/nouveau_api.erl | 298 +-
src/nouveau/src/nouveau_bookmark.erl | 2 +-
src/nouveau/src/nouveau_fabric_cleanup.erl | 70 +-
src/nouveau/src/nouveau_gun.erl | 162 +
src/nouveau/src/nouveau_index_manager.erl | 33 -
src/nouveau/src/nouveau_index_updater.erl | 46 +-
src/nouveau/src/nouveau_rpc.erl | 76 +-
src/nouveau/src/nouveau_sup.erl | 1 +
src/nouveau/src/nouveau_util.erl | 30 +-
src/rexi/src/rexi.erl | 2 +-
src/rexi/src/rexi_monitor.erl | 2 +-
src/rexi/src/rexi_server.erl | 2 +-
src/rexi/src/rexi_server_mon.erl | 9 +-
src/rexi/src/rexi_utils.erl | 2 +-
src/rexi/test/rexi_tests.erl | 4 +-
src/setup/src/setup.erl | 2 +-
src/setup/test/t-frontend-setup.sh | 4 +-
src/smoosh/src/smoosh.erl | 9 +-
src/smoosh/src/smoosh_channel.erl | 14 +-
src/smoosh/src/smoosh_persist.erl | 4 +-
src/smoosh/test/smoosh_tests.erl | 16 +-
.../src/weatherreport_check_mem3_sync.erl | 2 +-
.../src/weatherreport_check_node_stats.erl | 2 +-
.../src/weatherreport_check_nodes_connected.erl | 2 +-
.../src/weatherreport_check_process_calls.erl | 2 +-
src/weatherreport/src/weatherreport_getopt.erl | 2 +-
src/weatherreport/src/weatherreport_node.erl | 2 +-
src/weatherreport/src/weatherreport_util.erl | 2 +-
test/elixir/lib/asserts.ex | 20 +
test/elixir/test/changes_async_test.exs | 2 +-
test/elixir/test/config/nouveau.elixir | 3 +-
test/elixir/test/nouveau_test.exs | 17 +
test/elixir/test/partition_search_test.exs | 47 +-
test/elixir/test/search_test.exs | 83 +-
332 files changed, 15261 insertions(+), 6806 deletions(-)
diff --git a/.asf.yaml b/.asf.yaml
index 92afea9e4..3e9abc121 100644
--- a/.asf.yaml
+++ b/.asf.yaml
@@ -40,6 +40,9 @@ github:
strict: true
contexts:
- continuous-integration/jenkins/pr-merge
+ 3.5.x:
+ required_status_checks:
+ strict: true
3.4.x:
required_status_checks:
strict: true
diff --git a/.elp.toml b/.elp.toml
new file mode 100644
index 000000000..e28ee26ae
--- /dev/null
+++ b/.elp.toml
@@ -0,0 +1,38 @@
+[build_info]
+apps = ["src/*"]
+# 3rd party dependencies (not type-checked), defaults to [] (see rebar.config.script)
+deps = [
+ "src/erlfmt",
+ "src/rebar",
+ "src/rebar3",
+ "src/meck",
+ "src/cowlib",
+ "src/gun",
+ "src/recon",
+ "src/proper",
+ "src/fauxton",
+ "src/docs",
+ "src/meck",
+ "src/jiffy",
+ "src/ibrowse",
+ "src/mochiweb",
+ "src/snappy"
+]
+# List of OTP application names to exclude from indexing. This can help improve performance by not loading rarely used OTP apps.
+[otp]
+exclude_apps = [
+ "megaco",
+ "common_test",
+ "edoc",
+ "eldap",
+ "erl_docgen",
+ "et",
+ "ftp",
+ "mnesia",
+ "odbc",
+ "observer",
+ "snmp",
+ "tftp",
+ "wx",
+ "xmerl"
+]
diff --git a/.gitignore b/.gitignore
index 080a7dd6f..d46777512 100644
--- a/.gitignore
+++ b/.gitignore
@@ -53,10 +53,12 @@ src/couch/priv/couchspawnkillable
src/couch/priv/couch_ejson_compare/couch_ejson_compare.d
src/couch/priv/couch_js/**/*.d
src/couch/priv/icu_driver/couch_icu_driver.d
+src/cowlib/
src/mango/src/mango_cursor_text.nocompile
src/excoveralls/
src/fauxton/
src/folsom/
+src/gun/
src/hackney/
src/hqueue/
src/ibrowse/
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 0ba7276ba..f229fc106 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -302,6 +302,19 @@ hub checkout link-to-pull-request
meaning that you will automatically check out the branch for the pull request,
without needing any other steps like setting git upstreams! :sparkles:
+## Artificial Intelligence and Large Language Models Contributions Policy
+
+The CouchDB project has a long-standing focus on license compatibility, and
+appropriate attribution of source code. AI and LLMs, by their nature, are unable
+to provide the necessary assurance, that the generated material is compatible
+with the Apache 2 license, or that the material has been appropriately
+attributed to the original authors.
+
+Thus, it is expressly forbidden to contribute material generated by AI, LLMs,
+and similar technologies, to the CouchDB project. This includes, but is not
+limited to, source code, documentation, commit messages, or any other areas of
+the project.
+
## Thanks
Special thanks to [Hoodie][#gh_hoodie] for the great
diff --git a/INSTALL.Unix.md b/INSTALL.Unix.md
index a07889798..a27ff626a 100644
--- a/INSTALL.Unix.md
+++ b/INSTALL.Unix.md
@@ -1,6 +1,6 @@
# Apache CouchDB INSTALL.Unix
-A high-level guide to Unix-like systems, inc. Mac OS X and Ubuntu.
+A high-level guide to Unix-like systems, inc. macOS and Ubuntu.
Community installation guides are available on the wiki:
@@ -84,9 +84,9 @@ You can install the dependencies by running:
You can install Node.JS via [NodeSource](https://github.com/nodesource/distributions#rpminstall).
-### Mac OS X
+### macOS
-To build CouchDB from source on Mac OS X, you will need to install
+To build CouchDB from source on macOS, you will need to install
the Command Line Tools:
xcode-select --install
@@ -96,6 +96,12 @@ You can then install the other dependencies by running:
brew install autoconf autoconf-archive automake libtool \
erlang icu4c spidermonkey pkg-config
+Note that newer versions of Homebrew install `icu4c` as “keg-only”.
+That means the CouchDB build system can’t find it. Either follow
+the instructions presented by Homebrew or run
+
+ brew link icu4c
+
You can install Node.JS via the
[official Macintosh installer](https://nodejs.org/en/download/).
@@ -103,9 +109,9 @@ You will need Homebrew installed to use the `brew` command.
Learn more about Homebrew at:
- http://mxcl.github.com/homebrew/
+ https://brew.sh
-Some versions of Mac OS X ship a problematic OpenSSL library. If
+Some versions of macOS ship a problematic OpenSSL library. If
you're experiencing troubles with CouchDB crashing intermittently with
a segmentation fault or a bus error, you will need to install your own
version of OpenSSL. See the wiki, mentioned above, for more information.
@@ -169,7 +175,7 @@ On many Unix-like systems you can run:
--group --gecos \
"CouchDB Administrator" couchdb
-On Mac OS X you can use the Workgroup Manager to create users up to version
+On macOS you can use the Workgroup Manager to create users up to version
10.9, and dscl or sysadminctl after version 10.9. Search Apple's support
site to find the documentation appropriate for your system. As of recent
versions of OS X, this functionality is also included in Server.app,
diff --git a/Makefile b/Makefile
index 8b1df51e6..6847037df 100644
--- a/Makefile
+++ b/Makefile
@@ -95,6 +95,10 @@ EXUNIT_OPTS=$(subst $(comma),$(space),$(tests))
TEST_OPTS="-c 'startup_jitter=0' -c 'default_security=admin_local' -c 'iterations=9'"
+ifneq ($(ERLANG_COOKIE),)
+TEST_OPTS+=" --erlang-cookie=$(ERLANG_COOKIE)"
+endif
+
################################################################################
# Main commands
################################################################################
@@ -350,6 +354,12 @@ weatherreport-test: devclean escriptize
@dev/run "$(TEST_OPTS)" -n 1 -a adm:pass --no-eval \
'bin/weatherreport --etc dev/lib/node1/etc --level error'
+.PHONY: quickjs-test262
+# target: quickjs-javascript-tests - Run QuickJS JS conformance tests
+quickjs-test262: couch
+ make -C src/couch_quickjs/quickjs test2-bootstrap
+ make -C src/couch_quickjs/quickjs test2
+
################################################################################
# Developing
################################################################################
@@ -474,7 +484,12 @@ clean:
@rm -rf .rebar/
@rm -f bin/couchjs
@rm -f bin/weatherreport
- @rm -rf src/*/ebin
+ @find src/*/ebin \
+ -not -path 'src/cowlib/ebin/cowlib.app' \
+ -not -path 'src/cowlib/ebin' \
+ -not -path 'src/gun/ebin/gun.app' \
+ -not -path 'src/gun/ebin' \
+ -delete
@rm -rf src/*/.rebar
@rm -rf src/*/priv/*.so
@rm -rf share/server/main.js share/server/main-ast-bypass.js share/server/main-coffee.js
@@ -482,7 +497,7 @@ clean:
@rm -rf src/mango/.venv
@rm -f src/couch/priv/couch_js/config.h
@rm -f dev/*.beam dev/devnode.* dev/pbkdf2.pyc log/crash.log
- @rm -f src/couch_dist/certs/out
+ @rm -rf src/couch_dist/certs/out
@rm -rf src/docs/build src/docs/.venv
ifeq ($(with_nouveau), true)
@cd nouveau && $(GRADLE) clean
diff --git a/Makefile.win b/Makefile.win
index 000874b70..d510ee51d 100644
--- a/Makefile.win
+++ b/Makefile.win
@@ -93,6 +93,10 @@ EXUNIT_OPTS=$(subst $(comma),$(space),$(tests))
TEST_OPTS="-c startup_jitter=0 -c default_security=admin_local -c iterations=9"
+ifneq ($(ERLANG_COOKIE),)
+TEST_OPTS+=" --erlang-cookie=$(ERLANG_COOKIE)"
+endif
+
################################################################################
# Main commands
################################################################################
diff --git a/README-DEV.rst b/README-DEV.rst
index 1f0711b4a..d6dcc4a55 100644
--- a/README-DEV.rst
+++ b/README-DEV.rst
@@ -111,8 +111,8 @@ Centos 7 and RHEL 7
python-pygments gnupg nodejs npm
-Mac OS X
-~~~~~~~~
+macOS
+~~~~~
Install `Homebrew <https://brew.sh/>`_, if you do not have it already.
@@ -120,7 +120,7 @@ Unless you want to install the optional dependencies, skip to the next section.
Install what else we can with Homebrew::
- brew install help2man gnupg md5sha1sum node python
+ brew install help2man gnupg md5sha1sum node python elixir
If you don't already have pip installed, install it::
@@ -311,9 +311,9 @@ follows::
dev/run --with-clouseau
-When a specific Erlang cookie string is set in
-``rel/overlay/etc/vm.args``, the ``--erlang-cookie`` flag could be
-used to configure Clouseau to work with that::
+When a specific Erlang cookie string is needed, the
+``--erlang-cookie`` flag could be used to configure CouchDB and
+Clouseau to work with that::
dev/run --with-clouseau --erlang-cookie=brumbrum
diff --git a/build-aux/Jenkinsfile.full b/build-aux/Jenkinsfile
similarity index 65%
rename from build-aux/Jenkinsfile.full
rename to build-aux/Jenkinsfile
index 479aec7ea..dfba236c7 100644
--- a/build-aux/Jenkinsfile.full
+++ b/build-aux/Jenkinsfile
@@ -13,12 +13,24 @@
// License for the specific language governing permissions and limitations under
// the License.
-// Erlang version embedded in binary packages
-ERLANG_VERSION = '26.2.5.11'
+// This is image used to build the tarball, check source formatting and build
+// the docs
+DOCKER_IMAGE_BASE = 'apache/couchdbci-debian:bookworm-erlang'
+
+// Erlang version embedded in binary packages. Also the version most builds
+// will run.
+ERLANG_VERSION = '26.2.5.15'
// Erlang version used for rebar in release process. CouchDB will not build from
// the release tarball on Erlang versions older than this
-MINIMUM_ERLANG_VERSION = '25.3.2.20'
+MINIMUM_ERLANG_VERSION = '26.2.5.15'
+
+// Highest support Erlang version.
+MAXIMUM_ERLANG_VERSION = '28.0.4'
+
+// Use these to detect if just documents changed
+docs_changed = "git diff --name-only origin/${env.CHANGE_TARGET} | grep -q '^src/docs/'"
+other_changes = "git diff --name-only origin/${env.CHANGE_TARGET} | grep -q -v '^src/docs/'"
// We create parallel build / test / package stages for each OS using the metadata
// in this map. Adding a new OS should ideally only involve adding a new entry here.
@@ -28,6 +40,7 @@ meta = [
spidermonkey_vsn: '60',
with_nouveau: true,
with_clouseau: true,
+ quickjs_test262: true,
image: "apache/couchdbci-centos:8-erlang-${ERLANG_VERSION}"
],
@@ -36,22 +49,16 @@ meta = [
spidermonkey_vsn: '78',
with_nouveau: true,
with_clouseau: true,
+ quickjs_test262: true,
image: "apache/couchdbci-centos:9-erlang-${ERLANG_VERSION}"
],
- 'focal': [
- name: 'Ubuntu 20.04',
- spidermonkey_vsn: '68',
- with_nouveau: true,
- with_clouseau: true,
- image: "apache/couchdbci-ubuntu:focal-erlang-${ERLANG_VERSION}"
- ],
-
'jammy': [
name: 'Ubuntu 22.04',
spidermonkey_vsn: '91',
with_nouveau: true,
with_clouseau: true,
+ quickjs_test262: true,
image: "apache/couchdbci-ubuntu:jammy-erlang-${ERLANG_VERSION}"
],
@@ -60,48 +67,106 @@ meta = [
spidermonkey_vsn: '115',
with_nouveau: true,
with_clouseau: true,
+ quickjs_test262: true,
image: "apache/couchdbci-ubuntu:noble-erlang-${ERLANG_VERSION}"
],
- 'bookworm-ppc64': [
- name: 'Debian POWER',
+ 'bullseye': [
+ name: 'Debian x86_64',
spidermonkey_vsn: '78',
with_nouveau: true,
with_clouseau: true,
- image: "apache/couchdbci-debian:bookworm-erlang-${ERLANG_VERSION}",
- node_label: 'ppc64le'
+ quickjs_test262: true,
+ image: "apache/couchdbci-debian:bullseye-erlang-${ERLANG_VERSION}"
],
- 'bookworm-s390x': [
- name: 'Debian s390x',
+ // Sometimes we "pick up" ppc64le workers from the asf jenkins intance That
+ // seems like a good thing, however, those workers allow running multiple
+ // agents at a time and often time out even with retries. The build times
+ // take close to an hour, which is at least x2 as long as it takes to run
+ // other arch CI jobs and they still time out often and fail. Disable for
+ // now. This is a low demand arch distro, maybe remove support altogether?
+ //
+ // 'base-ppc64': [
+ // name: 'Debian POWER',
+ // spidermonkey_vsn: '78',
+ // with_nouveau: true,
+ // with_clouseau: true,
+ // quickjs_test262: true,
+ // image: "${DOCKER_IMAGE_BASE}-${ERLANG_VERSION}",
+ // node_label: 'ppc64le'
+ // ],
+
+ // Just like in the ppc64le case we sometimes "pick up" built-in s390x workers added to
+ // our jenkins, but since those are managed by us, our .mix/.venv/.hex packaging
+ // cache hack in /home/jenkins doesn't work, and so elixir tests fail. Skip this arch build
+ // until we figure out caching (probably need to use a proper caching plugin).
+ //
+ // 'base-s390x': [
+ // name: 'Debian s390x',
+ // spidermonkey_vsn: '78',
+ // with_nouveau: true,
+ // // QuickJS test262 shows a discrepancy typedarray-arg-set-values-same-buffer-other-type.js
+ // // Test262Error: 51539607552,42,0,4,5,6,7,8
+ // quickjs_test262: false,
+ // image: "${DOCKER_IMAGE_BASE}-${ERLANG_VERSION}",
+ // node_label: 's390x'
+ // ],
+
+ 'base': [
+ name: 'Debian x86_64',
spidermonkey_vsn: '78',
with_nouveau: true,
- image: "apache/couchdbci-debian:bookworm-erlang-${ERLANG_VERSION}",
- node_label: 's390x'
+ with_clouseau: true,
+ // Test this in in the bookworm-quickjs variant
+ quickjs_test262: false,
+ image: "${DOCKER_IMAGE_BASE}-${ERLANG_VERSION}"
],
- 'bullseye': [
+ 'base-max-erlang': [
name: 'Debian x86_64',
spidermonkey_vsn: '78',
with_nouveau: true,
with_clouseau: true,
- image: "apache/couchdbci-debian:bullseye-erlang-${ERLANG_VERSION}"
+ quickjs_test262: false,
+ image: "${DOCKER_IMAGE_BASE}-${MAXIMUM_ERLANG_VERSION}"
],
- 'bookworm': [
- name: 'Debian x86_64',
+ 'base-quickjs': [
+ name: 'Debian 12 with QuickJS',
+ disable_spidermonkey: true,
+ with_nouveau: true,
+ with_clouseau: true,
+ quickjs_test262: true,
+ image: "${DOCKER_IMAGE_BASE}-${ERLANG_VERSION}"
+ ],
+
+ // This runs on a docker ARM64 host. Normally we should be able to run all
+ // ubuntu and centos containers on top any docker host, however spidermonkey
+ // 60 from CentOS cannot build on ARM64 so we're forced to separate it as a
+ // separate build usable for ubuntu/debian only and isolated it from other
+ // builds. At some point when we remove CentOS 8 or switch to QuickJS only,
+ // remove the docker-arm64 label on ubuntu-nc-arm64-12 node in Jenkins and
+ // remove this flavor
+ //
+ 'base-arm64': [
+ name: 'Debian ARM64',
spidermonkey_vsn: '78',
with_nouveau: true,
with_clouseau: true,
- image: "apache/couchdbci-debian:bookworm-erlang-${ERLANG_VERSION}"
+ // Test this in in the bookworm-quickjs variant
+ quickjs_test262: false,
+ image: "${DOCKER_IMAGE_BASE}-${ERLANG_VERSION}",
+ node_label: 'docker-arm64'
],
- 'bookworm-quickjs': [
- name: 'Debian 12 with QuickJS',
- disable_spidermonkey: true,
+ 'trixie': [
+ name: 'Debian x86_64',
+ spidermonkey_vsn: '128',
with_nouveau: true,
with_clouseau: true,
- image: "apache/couchdbci-debian:bookworm-erlang-${ERLANG_VERSION}"
+ quickjs_test262: true,
+ image: "apache/couchdbci-debian:trixie-erlang-${ERLANG_VERSION}"
],
'freebsd-x86_64': [
@@ -109,6 +174,7 @@ meta = [
spidermonkey_vsn: '91',
with_clouseau: true,
clouseau_java_home: '/usr/local/openjdk8-jre',
+ quickjs_test262: false,
gnu_make: 'gmake'
],
@@ -119,21 +185,27 @@ meta = [
disable_spidermonkey: true,
with_clouseau: true,
clouseau_java_home: '/usr/local/openjdk8-jre',
+ quickjs_test262: false,
gnu_make: 'gmake'
],
- 'macos': [
- name: 'macOS',
- spidermonkey_vsn: '128',
- with_nouveau: false,
- with_clouseau: true,
- clouseau_java_home: '/opt/java/openjdk8/zulu-8.jre/Contents/Home',
- gnu_make: 'make'
- ],
+ // Disable temporarily. Forks / shell execs seem to fail there currently
+ //
+ //
+ // 'macos': [
+ // name: 'macOS',
+ // spidermonkey_vsn: '128',
+ // with_nouveau: false,
+ // with_clouseau: true,
+ // clouseau_java_home: '/opt/java/openjdk8/zulu-8.jre/Contents/Home',
+ // gnu_make: 'make'
+ // ],
'win2022': [
name: 'Windows 2022',
spidermonkey_vsn: '128',
+ with_clouseau: true,
+ quickjs_test262: false,
node_label: 'win'
]
]
@@ -170,7 +242,7 @@ def generateNativeStage(platform) {
return {
stage(platform) {
node(platform) {
- timeout(time: 90, unit: "MINUTES") {
+ timeout(time: 180, unit: "MINUTES") {
// Steps to configure and build CouchDB on *nix platforms
if (isUnix()) {
try {
@@ -190,12 +262,13 @@ def generateNativeStage(platform) {
dir( "${platform}/build" ) {
sh "${configure(meta[platform])}"
sh '$MAKE'
- sh '$MAKE eunit'
- sh '$MAKE elixir'
- sh '$MAKE elixir-search'
- sh '$MAKE mango-test'
- sh '$MAKE weatherreport-test'
- sh '$MAKE nouveau-test'
+ retry (3) {sh '$MAKE eunit'}
+ if (meta[platform].quickjs_test262) {retry(3) {sh 'make quickjs-test262'}}
+ retry (3) {sh '$MAKE elixir'}
+ retry (3) {sh '$MAKE elixir-search'}
+ retry (3) {sh '$MAKE mango-test'}
+ retry (3) {sh '$MAKE weatherreport-test'}
+ retry (3) {sh '$MAKE nouveau-test'}
}
}
}
@@ -229,9 +302,11 @@ def generateNativeStage(platform) {
powershell( script: "New-Item -ItemType Directory -Path '${platform}/build' -Force", label: 'Create build directories' )
powershell( script: "tar -xf (Get-Item apache-couchdb-*.tar.gz) -C '${platform}/build' --strip-components=1", label: 'Unpack release' )
dir( "${platform}/build" ) {
+ withClouseau = meta[platform].with_clouseau ? '-WithClouseau' : ''
+
powershell( script: """
.\\..\\..\\couchdb-glazier\\bin\\shell.ps1
- .\\configure.ps1 -SkipDeps -WithNouveau -SpiderMonkeyVersion ${meta[platform].spidermonkey_vsn}
+ .\\configure.ps1 -SkipDeps -WithNouveau ${withClouseau} -SpiderMonkeyVersion ${meta[platform].spidermonkey_vsn}
Set-Item -Path env:GRADLE_OPTS -Value '-Dorg.gradle.daemon=false'
make -f Makefile.win release
""", label: 'Configure and Build')
@@ -239,13 +314,17 @@ def generateNativeStage(platform) {
//powershell( script: ".\\..\\..\\couchdb-glazier\\bin\\shell.ps1; make -f Makefile.win eunit", label: 'EUnit tests')
//powershell( script: ".\\..\\..\\couchdb-glazier\\bin\\shell.ps1; make -f Makefile.win elixir", label: 'Elixir tests')
- powershell( script: '& .\\..\\..\\couchdb-glazier\\bin\\shell.ps1; Write-Host "NOT AVAILABLE: make -f Makefile.win elixir-search"', label: 'N/A Clouseau tests')
-
powershell( script: """
.\\..\\..\\couchdb-glazier\\bin\\shell.ps1
Set-Item -Path env:GRADLE_OPTS -Value '-Dorg.gradle.daemon=false'
- make -f Makefile.win mango-test
- """, label: 'Mango tests')
+ make -f Makefile.win elixir-search ERLANG_COOKIE=crumbles
+ """, label: 'Clouseau tests')
+
+ powershell( script: """
+ .\\..\\..\\couchdb-glazier\\bin\\shell.ps1
+ Set-Item -Path env:GRADLE_OPTS -Value '-Dorg.gradle.daemon=false'
+ make -f Makefile.win mango-test ERLANG_COOKIE=crumbles
+ """, label: 'Mango tests')
powershell( script: '.\\..\\..\\couchdb-glazier\\bin\\shell.ps1; Write-Host "NOT AVAILABLE: make -f Makefile.win weatherreport-test"', label: 'N/A Weatherreport tests')
@@ -295,17 +374,19 @@ def generateContainerStage(platform) {
node(meta[platform].get('node_label', 'docker')) {
docker.withRegistry('https://docker.io/', 'dockerhub_creds') {
docker.image(meta[platform].image).inside("${DOCKER_ARGS}") {
- timeout(time: 90, unit: "MINUTES") {
+ timeout(time: 180, unit: "MINUTES") {
stage("${meta[platform].name} - build & test") {
try {
sh( script: "rm -rf ${platform} apache-couchdb-*", label: 'Clean workspace' )
unstash 'tarball'
sh( script: "mkdir -p ${platform}/build", label: 'Create build directories' )
sh( script: "tar -xf apache-couchdb-*.tar.gz -C ${platform}/build --strip-components=1", label: 'Unpack release' )
+ quickjs_tests262 = meta[platform].quickjs_test262
dir( "${platform}/build" ) {
sh "${configure(meta[platform])}"
sh 'make'
retry(3) {sh 'make eunit'}
+ if (meta[platform].quickjs_test262) {retry(3) {sh 'make quickjs-test262'}}
retry(3) {sh 'make elixir'}
retry(3) {sh 'make elixir-search'}
retry(3) {sh 'make mango-test'}
@@ -383,23 +464,161 @@ pipeline {
options {
buildDiscarder(logRotator(numToKeepStr: '10', artifactNumToKeepStr: '10'))
preserveStashes(buildCount: 10)
- timeout(time: 3, unit: 'HOURS')
+ timeout(time: 4, unit: 'HOURS')
timestamps()
}
stages {
+
+ stage('Setup Env') {
+ agent {
+ docker {
+ image "${DOCKER_IMAGE_BASE}-${MINIMUM_ERLANG_VERSION}"
+ label 'docker'
+ args "${DOCKER_ARGS}"
+ registryUrl 'https://docker.io/'
+ registryCredentialsId 'dockerhub_creds'
+ }
+ }
+ options {
+ timeout(time: 10, unit: 'MINUTES')
+ }
+ steps {
+ script {
+ env.DOCS_CHANGED = '0'
+ env.ONLY_DOCS_CHANGED = '0'
+ if ( sh(returnStatus: true, script: docs_changed) == 0 ) {
+ env.DOCS_CHANGED = '1'
+ if (sh(returnStatus: true, script: other_changes) == 1) {
+ env.ONLY_DOCS_CHANGED = '1'
+ }
+ }
+ }
+ }
+ post {
+ cleanup {
+ // UGH see https://issues.jenkins-ci.org/browse/JENKINS-41894
+ sh 'rm -rf ${WORKSPACE}/*'
+ }
+ }
+ } // stage 'Setup Environment'
+
+ stage('Docs Check') {
+ // Run docs `make check` stage if any docs changed
+ when {
+ beforeOptions true
+ expression { DOCS_CHANGED == '1' }
+ }
+ agent {
+ docker {
+ image "${DOCKER_IMAGE_BASE}-${MINIMUM_ERLANG_VERSION}"
+ label 'docker'
+ args "${DOCKER_ARGS}"
+ registryUrl 'https://docker.io/'
+ registryCredentialsId 'dockerhub_creds'
+ }
+ }
+ options {
+ timeout(time: 15, unit: 'MINUTES')
+ }
+ steps {
+ sh '''
+ make python-black
+ '''
+ sh '''
+ (cd src/docs && make check)
+ '''
+ }
+ post {
+ cleanup {
+ // UGH see https://issues.jenkins-ci.org/browse/JENKINS-41894
+ sh 'rm -rf ${WORKSPACE}/*'
+ }
+ }
+ } // stage Docs Check
+
+ stage('Build Docs') {
+ // Build docs separately if only docs changed. If there are other changes, docs are
+ // already built as part of `make dist`
+ when {
+ beforeOptions true
+ expression { ONLY_DOCS_CHANGED == '1' }
+ }
+ agent {
+ docker {
+ image "${DOCKER_IMAGE_BASE}-${MINIMUM_ERLANG_VERSION}"
+ label 'docker'
+ args "${DOCKER_ARGS}"
+ registryUrl 'https://docker.io/'
+ registryCredentialsId 'dockerhub_creds'
+ }
+ }
+ options {
+ timeout(time: 30, unit: 'MINUTES')
+ }
+ steps {
+ sh '''
+ (cd src/docs && ./setup.sh ; make html)
+ '''
+ }
+ post {
+ cleanup {
+ // UGH see https://issues.jenkins-ci.org/browse/JENKINS-41894
+ sh 'rm -rf ${WORKSPACE}/*'
+ }
+ }
+ } // stage Build Docs
+
+ stage('Source Format Checks') {
+ when {
+ beforeOptions true
+ expression { ONLY_DOCS_CHANGED == '0' }
+ }
+ agent {
+ docker {
+ image "${DOCKER_IMAGE_BASE}-${MINIMUM_ERLANG_VERSION}"
+ label 'docker'
+ args "${DOCKER_ARGS}"
+ registryUrl 'https://docker.io/'
+ registryCredentialsId 'dockerhub_creds'
+ }
+ }
+ options {
+ timeout(time: 15, unit: "MINUTES")
+ }
+ steps {
+ sh '''
+ rm -rf apache-couchdb-*
+ ./configure --skip-deps --spidermonkey-version 78
+ make erlfmt-check
+ make elixir-source-checks
+ make python-black
+ '''
+ }
+ post {
+ cleanup {
+ // UGH see https://issues.jenkins-ci.org/browse/JENKINS-41894
+ sh 'rm -rf ${WORKSPACE}/*'
+ }
+ }
+ } // stage Erlfmt
+
stage('Build Release Tarball') {
+ when {
+ beforeOptions true
+ expression { ONLY_DOCS_CHANGED == '0' }
+ }
agent {
docker {
label 'docker'
- image "apache/couchdbci-debian:bookworm-erlang-${MINIMUM_ERLANG_VERSION}"
+ image "${DOCKER_IMAGE_BASE}-${MINIMUM_ERLANG_VERSION}"
args "${DOCKER_ARGS}"
registryUrl 'https://docker.io/'
registryCredentialsId 'dockerhub_creds'
}
}
steps {
- timeout(time: 15, unit: "MINUTES") {
+ timeout(time: 30, unit: "MINUTES") {
sh (script: 'rm -rf apache-couchdb-*', label: 'Clean workspace of any previous release artifacts' )
sh "./configure --spidermonkey-version 78 --with-nouveau"
sh 'make dist'
@@ -421,10 +640,14 @@ pipeline {
} // stage Build Release Tarball
stage('Test and Package') {
+ when {
+ beforeOptions true
+ expression { ONLY_DOCS_CHANGED == '0' }
+ }
steps {
script {
// Including failFast: true in map fails the build immediately if any parallel step fails
- parallelStagesMap = meta.collectEntries( [failFast: false] ) { key, values ->
+ parallelStagesMap = meta.collectEntries( [failFast: true] ) { key, values ->
if (values.image) {
["${key}": generateContainerStage(key)]
}
@@ -436,64 +659,6 @@ pipeline {
}
}
}
-
- stage('Publish') {
-
- when {
- expression { return env.BRANCH_NAME ==~ /main|2.*.x|3.*.x|4.*.x|jenkins-.*/ }
- }
-
- agent {
- docker {
- image "apache/couchdbci-debian:bullseye-erlang-${ERLANG_VERSION}"
- label 'docker'
- args "${DOCKER_ARGS}"
- registryUrl 'https://docker.io/'
- registryCredentialsId 'dockerhub_creds'
- }
- }
- options {
- skipDefaultCheckout()
- timeout(time: 90, unit: "MINUTES")
- }
-
- steps {
- sh 'rm -rf ${WORKSPACE}/*'
- unstash 'tarball'
- unarchive mapping: ['pkgs/' : '.']
-
- sh( label: 'Setup repo dirs', script: '''
- mkdir -p $BRANCH_NAME/debian $BRANCH_NAME/el8 $BRANCH_NAME/el9 $BRANCH_NAME/source
- git clone https://github.com/apache/couchdb-pkg
- ''' )
-
- sh( label: 'Build Debian repo', script: '''
- for plat in bullseye bookworm focal
- do
- reprepro -b couchdb-pkg/repo includedeb $plat pkgs/$plat/*.deb
- done
- ''' )
-
- sh( label: 'Build CentOS 8', script: '''
- (cd pkgs/centos8 && createrepo_c --database .)
- ''' )
-
- sh( label: 'Build CentOS 9', script: '''
- (cd pkgs/centos9 && createrepo_c --database .)
- ''' )
-
- sh( label: 'Build unified repo', script: '''
- mv couchdb-pkg/repo/pool $BRANCH_NAME/debian
- mv couchdb-pkg/repo/dists $BRANCH_NAME/debian
- mv pkgs/centos8/* $BRANCH_NAME/el8
- mv pkgs/centos9/* $BRANCH_NAME/el9
- mv apache-couchdb-*.tar.gz $BRANCH_NAME/source
- cd $BRANCH_NAME/source
- ls -1tr | head -n -10 | xargs -d '\n' rm -f --
- cd ../..
- ''' )
- } // steps
- } // stage
} // stages
post {
diff --git a/build-aux/Jenkinsfile.pr b/build-aux/Jenkinsfile.pr
deleted file mode 100644
index 09180b17a..000000000
--- a/build-aux/Jenkinsfile.pr
+++ /dev/null
@@ -1,293 +0,0 @@
-#!groovy
-//
-//
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-build = '''
-mkdir -p ${ERLANG_VERSION}
-cd ${ERLANG_VERSION}
-rm -rf build
-mkdir build
-cd build
-tar -xf ${WORKSPACE}/apache-couchdb-*.tar.gz
-cd apache-couchdb-*
-./configure --with-nouveau --with-clouseau --js-engine=${JS_ENGINE}
-'''
-
-docs_changed = "git diff --name-only origin/${env.CHANGE_TARGET} | grep -q '^src/docs/'"
-other_changes = "git diff --name-only origin/${env.CHANGE_TARGET} | grep -q -v '^src/docs/'"
-
-pipeline {
-
- // no top-level agent; agents must be declared for each stage
- agent none
-
- environment {
- recipient = 'notifications@couchdb.apache.org'
- // Following fix an issue with git <= 2.6.5 where no committer
- // name or email are present for reflog, required for git clone
- GIT_COMMITTER_NAME = 'Jenkins User'
- GIT_COMMITTER_EMAIL = 'couchdb@apache.org'
- // Parameters for the matrix build
- DOCKER_IMAGE_BASE = 'apache/couchdbci-debian:bookworm-erlang'
- // https://github.com/jenkins-infra/jenkins.io/blob/master/Jenkinsfile#64
- // We need the jenkins user mapped inside of the image
- // npm config cache below deals with /home/jenkins not mapping correctly
- // inside the image
- DOCKER_ARGS = '-e npm_config_cache=/home/jenkins/.npm -e HOME=. -e MIX_HOME=/home/jenkins/.mix -e HEX_HOME=/home/jenkins/.hex -e PIP_CACHE_DIR=/home/jenkins/.cache/pip -v=/etc/passwd:/etc/passwd -v /etc/group:/etc/group -v /home/jenkins/.gradle:/home/jenkins/.gradle:rw,z -v /home/jenkins/.hex:/home/jenkins/.hex:rw,z -v /home/jenkins/.npm:/home/jenkins/.npm:rw,z -v /home/jenkins/.cache/pip:/home/jenkins/.cache/pip:rw,z -v /home/jenkins/.mix:/home/jenkins/.mix:rw,z'
-
- // *** BE SURE TO ALSO CHANGE THE ERLANG VERSIONS FARTHER DOWN ***
- // Search for ERLANG_VERSION
- // see https://issues.jenkins.io/browse/JENKINS-61047 for why this cannot
- // be done parametrically
- LOW_ERLANG_VER = '25.3.2.20'
- }
-
- options {
- buildDiscarder(logRotator(numToKeepStr: '10', artifactNumToKeepStr: '10'))
- // This fails the build immediately if any parallel step fails
- parallelsAlwaysFailFast()
- preserveStashes(buildCount: 10)
- timeout(time: 3, unit: 'HOURS')
- timestamps()
- }
-
- stages {
-
- stage('Setup Env') {
- agent {
- docker {
- image "${DOCKER_IMAGE_BASE}-${LOW_ERLANG_VER}"
- label 'docker'
- args "${DOCKER_ARGS}"
- registryUrl 'https://docker.io/'
- registryCredentialsId 'dockerhub_creds'
- }
- }
- options {
- timeout(time: 10, unit: 'MINUTES')
- }
- steps {
- script {
- env.DOCS_CHANGED = '0'
- env.ONLY_DOCS_CHANGED = '0'
- if ( sh(returnStatus: true, script: docs_changed) == 0 ) {
- env.DOCS_CHANGED = '1'
- if (sh(returnStatus: true, script: other_changes) == 1) {
- env.ONLY_DOCS_CHANGED = '1'
- }
- }
- }
- }
- post {
- cleanup {
- // UGH see https://issues.jenkins-ci.org/browse/JENKINS-41894
- sh 'rm -rf ${WORKSPACE}/*'
- }
- }
- } // stage 'Setup Environment'
-
- stage('Docs Check') {
- // Run docs `make check` stage if any docs changed
- when {
- beforeOptions true
- expression { DOCS_CHANGED == '1' }
- }
- agent {
- docker {
- image "${DOCKER_IMAGE_BASE}-${LOW_ERLANG_VER}"
- label 'docker'
- args "${DOCKER_ARGS}"
- registryUrl 'https://docker.io/'
- registryCredentialsId 'dockerhub_creds'
- }
- }
- options {
- timeout(time: 15, unit: 'MINUTES')
- }
- steps {
- sh '''
- make python-black
- '''
- sh '''
- (cd src/docs && make check)
- '''
- }
- post {
- cleanup {
- // UGH see https://issues.jenkins-ci.org/browse/JENKINS-41894
- sh 'rm -rf ${WORKSPACE}/*'
- }
- }
- } // stage Docs Check
-
- stage('Build Docs') {
- // Build docs separately if only docs changed. If there are other changes, docs are
- // already built as part of `make dist`
- when {
- beforeOptions true
- expression { ONLY_DOCS_CHANGED == '1' }
- }
- agent {
- docker {
- image "${DOCKER_IMAGE_BASE}-${LOW_ERLANG_VER}"
- label 'docker'
- args "${DOCKER_ARGS}"
- registryUrl 'https://docker.io/'
- registryCredentialsId 'dockerhub_creds'
- }
- }
- options {
- timeout(time: 30, unit: 'MINUTES')
- }
- steps {
- sh '''
- (cd src/docs && ./setup.sh ; make html)
- '''
- }
- post {
- cleanup {
- // UGH see https://issues.jenkins-ci.org/browse/JENKINS-41894
- sh 'rm -rf ${WORKSPACE}/*'
- }
- }
- } // stage Build Docs
-
- stage('Source Format Checks') {
- when {
- beforeOptions true
- expression { ONLY_DOCS_CHANGED == '0' }
- }
- agent {
- docker {
- image "${DOCKER_IMAGE_BASE}-${LOW_ERLANG_VER}"
- label 'docker'
- args "${DOCKER_ARGS}"
- registryUrl 'https://docker.io/'
- registryCredentialsId 'dockerhub_creds'
- }
- }
- options {
- timeout(time: 15, unit: "MINUTES")
- }
- steps {
- sh '''
- rm -rf apache-couchdb-*
- ./configure --skip-deps --spidermonkey-version 78
- make erlfmt-check
- make elixir-source-checks
- make python-black
- '''
- }
- post {
- cleanup {
- // UGH see https://issues.jenkins-ci.org/browse/JENKINS-41894
- sh 'rm -rf ${WORKSPACE}/*'
- }
- }
- } // stage Erlfmt
-
-
- stage('Make Dist') {
- when {
- beforeOptions true
- expression { ONLY_DOCS_CHANGED == '0' }
- }
- agent {
- docker {
- image "${DOCKER_IMAGE_BASE}-${LOW_ERLANG_VER}"
- label 'docker'
- args "${DOCKER_ARGS}"
- registryUrl 'https://docker.io/'
- registryCredentialsId 'dockerhub_creds'
- }
- }
- options {
- timeout(time: 15, unit: "MINUTES")
- }
- steps {
- sh '''
- rm -rf apache-couchdb-*
- ./configure --spidermonkey-version 78 --with-nouveau --with-clouseau
- make dist
- chmod -R a+w * .
- '''
- }
- post {
- success {
- stash includes: 'apache-couchdb-*.tar.gz', name: 'tarball'
- }
- cleanup {
- // UGH see https://issues.jenkins-ci.org/browse/JENKINS-41894
- sh 'rm -rf ${WORKSPACE}/*'
- }
- }
- } // stage Make Dist
-
- // TODO Rework once Improved Docker Pipeline Engine is released
- // https://issues.jenkins-ci.org/browse/JENKINS-47962
- // https://issues.jenkins-ci.org/browse/JENKINS-48050
-
- stage('Make Check') {
- when {
- beforeOptions true
- expression { ONLY_DOCS_CHANGED == '0' }
- }
- matrix {
- axes {
- axis {
- name 'ERLANG_VERSION'
- values '25.3.2.20', '26.2.5.11', '27.3.3'
- }
- axis {
- name 'SM_VSN'
- values '78'
- }
- axis {
- name 'JS_ENGINE'
- values 'quickjs', 'spidermonkey'
- }
- }
-
- stages {
- stage('Build and Test') {
- agent {
- docker {
- image "${DOCKER_IMAGE_BASE}-${ERLANG_VERSION}"
- label 'docker'
- args "${DOCKER_ARGS}"
- }
- }
- options {
- skipDefaultCheckout()
- timeout(time: 90, unit: "MINUTES")
- }
- steps {
- unstash 'tarball'
- sh( script: build )
- retry(3) {sh 'cd ${ERLANG_VERSION}/build/apache-couchdb-* && make check || (make build-report && false)'}
- }
- post {
- always {
- junit '**/.eunit/*.xml, **/_build/*/lib/couchdbtest/*.xml, **/src/mango/nosetests.xml, **/test/javascript/junit.xml'
- }
- cleanup {
- sh 'rm -rf ${WORKSPACE}/*'
- }
- }
- } // stage
- } // stages
- } // matrix
- } // stage "Make Check"
- } // stages
-} // pipeline
diff --git a/build-aux/xref-helper.sh b/build-aux/xref-helper.sh
index 5e1c3ed1a..2b83c74f3 100755
--- a/build-aux/xref-helper.sh
+++ b/build-aux/xref-helper.sh
@@ -9,7 +9,6 @@ mkdir -p ./tmp
$REBAR --keep-going --recursive xref $DIALYZE_OPTS | \
grep -v '==>' | \
grep -v 'WARN' | \
- grep -v hastings | \
sort > ./tmp/xref-output.txt
# compare result against known allowed output
diff --git a/configure b/configure
index 70350a07b..30ad40c24 100755
--- a/configure
+++ b/configure
@@ -21,8 +21,8 @@ basename=`basename $0`
PACKAGE_AUTHOR_NAME="The Apache Software Foundation"
-REBAR3_BRANCH="3.23.0"
-ERLFMT_VERSION="v1.3.0"
+REBAR3_BRANCH="3.25.1"
+ERLFMT_VERSION="v1.7.0"
# TEST=0
WITH_PROPER="true"
@@ -43,9 +43,10 @@ JS_ENGINE=${JS_ENGINE:-"spidermonkey"}
SM_VSN=${SM_VSN:-"91"}
CLOUSEAU_MTH=${CLOUSEAU_MTH:-"dist"}
CLOUSEAU_URI=${CLOUSEAU_URI:-"https://github.com/cloudant-labs/clouseau/releases/download/%s/clouseau-%s-dist.zip"}
-CLOUSEAU_VSN=${CLOUSEAU_VSN:-"2.23.1"}
+CLOUSEAU_VSN=${CLOUSEAU_VSN:-"2.25.0"}
CLOUSEAU_DIR="$(pwd)"/clouseau
ARCH="$(uname -m)"
+MULTIARCH_NAME="$(command -v dpkg-architecture > /dev/null && dpkg-architecture -q DEB_HOST_MULTIARCH || true)"
ERLANG_VER="$(run_erlang 'io:put_chars(erlang:system_info(otp_release)).')"
ERLANG_OS="$(run_erlang 'case os:type() of {OS, _} -> io:format("~s~n", [OS]) end.')"
@@ -126,6 +127,7 @@ parse_opts() {
--dev)
WITH_DOCS="false"
WITH_FAUXTON="false"
+ WITH_SPIDERMONKEY="false"
shift
continue
;;
@@ -134,6 +136,7 @@ parse_opts() {
WITH_DOCS="false"
WITH_FAUXTON="false"
WITH_NOUVEAU="true"
+ WITH_SPIDERMONKEY="false"
shift
continue
;;
@@ -327,6 +330,7 @@ if [ "${WITH_SPIDERMONKEY}" = "true" ] && [ "${ERLANG_OS}" = "unix" ]; then
# This list is taken from src/couch/rebar.config.script, please keep them in sync.
if [ ! -d "/usr/include/${SM_HEADERS}" ] && \
+ [ -n "${MULTIARCH_NAME}" -a ! -d "/usr/include/${MULTIARCH_NAME}/${SM_HEADERS}" ] && \
[ ! -d "/usr/local/include/${SM_HEADERS}" ] && \
[ ! -d "/opt/homebrew/include/${SM_HEADERS}" ]; then
echo "ERROR: SpiderMonkey ${SM_VSN} is not found. Please specify with --spidermonkey-version."
diff --git a/configure.ps1 b/configure.ps1
index faf3669ec..c7c730c70 100644
--- a/configure.ps1
+++ b/configure.ps1
@@ -14,9 +14,9 @@
-CouchDBUser USER set the username to run as (defaults to current user)
-SpiderMonkeyVersion VSN select the version of SpiderMonkey to use (default 91)
-JSEngine ENGINE select JS engine to use (spidermonkey or quickjs) (default spidermonkey)
- -ClouseauVersion VSN select the version of Clouseau to use (default 2.23.1)
+ -ClouseauVersion VSN select the version of Clouseau to use (default 2.25.0)
-ClouseauMethod MTH method for Clouseau to deploy: git or dist (default dist)
- -ClouseauUri URI location for retrieving Clouseau (default https://github.com/cloudant-labs/clouseau/releases/download/2.23.1/clouseau-2.23.1-dist.zip)
+ -ClouseauUri URI location for retrieving Clouseau (default https://github.com/cloudant-labs/clouseau/releases/download/2.25.0/clouseau-2.25.0-dist.zip)
Installation directories:
-Prefix PREFIX install architecture-independent files in PREFIX
@@ -66,9 +66,9 @@ Param(
[ValidateNotNullOrEmpty()]
[string]$ClouseauMethod = "dist", # method for Clouseau to deploy: git or dist (default dist)
[ValidateNotNullOrEmpty()]
- [string]$ClouseauVersion = "2.23.1", # select the version of Clouseau to use (default 2.23.1)
+ [string]$ClouseauVersion = "2.25.0", # select the version of Clouseau to use (default 2.25.0)
[ValidateNotNullOrEmpty()]
- [string]$ClouseauUri = "https://github.com/cloudant-labs/clouseau/releases/download/{0}/clouseau-{0}-dist.zip", # location for retrieving Clouseau (default https://github.com/cloudant-labs/clouseau/releases/download/2.23.1/clouseau-2.23.1-dist.zip)
+ [string]$ClouseauUri = "https://github.com/cloudant-labs/clouseau/releases/download/{0}/clouseau-{0}-dist.zip", # location for retrieving Clouseau (default https://github.com/cloudant-labs/clouseau/releases/download/2.25.0/clouseau-2.25.0-dist.zip)
[ValidateNotNullOrEmpty()]
[string]$Prefix = "C:\Program Files\Apache\CouchDB", # install architecture-independent file location (default C:\Program Files\Apache\CouchDB)
[ValidateNotNullOrEmpty()]
diff --git a/dev/run b/dev/run
index 85ea9622d..478fb2ae9 100755
--- a/dev/run
+++ b/dev/run
@@ -515,7 +515,7 @@ def write_config(ctx, node, env):
content = apply_config_overrides(ctx, content)
elif base == "local.ini":
content = hack_local_ini(ctx, content)
- elif ctx["enable_tls"] and base == "vm.args":
+ elif base == "vm.args":
content = hack_vm_args(ctx, node, content)
with open(tgt, "w") as handle:
@@ -839,16 +839,23 @@ def hack_local_ini(ctx, contents):
def hack_vm_args(ctx, node, contents):
- contents += f"""
+ if ctx["enable_tls"]:
+ contents += f"""
-proto_dist couch
-couch_dist no_tls '"clouseau{node[-1]}@127.0.0.1"'
-ssl_dist_optfile {ctx["rootdir"]}/src/couch_dist/certs/out/couch_dist.conf
- """
- if ctx["no_tls"]:
- no_tls_nodes = ctx["no_tls"].split(",")
- for node_name in no_tls_nodes:
- node_name = node_name if "@" in node_name else f"{node_name}@127.0.0.1"
- contents += f"""\n-couch_dist no_tls '"{node_name}"'"""
+"""
+ if ctx["no_tls"]:
+ no_tls_nodes = ctx["no_tls"].split(",")
+ for node_name in no_tls_nodes:
+ node_name = node_name if "@" in node_name else f"{node_name}@127.0.0.1"
+ contents += f"""
+-couch_dist no_tls '"{node_name}"'
+"""
+ if ctx["erlang_cookie"]:
+ contents += f"""
+-setcookie {ctx["erlang_cookie"]}
+"""
return contents
diff --git a/nouveau/src/main/java/org/apache/couchdb/nouveau/api/Ok.java b/nouveau/src/main/java/org/apache/couchdb/nouveau/api/Ok.java
new file mode 100644
index 000000000..b393e1978
--- /dev/null
+++ b/nouveau/src/main/java/org/apache/couchdb/nouveau/api/Ok.java
@@ -0,0 +1,26 @@
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package org.apache.couchdb.nouveau.api;
+
+import com.fasterxml.jackson.annotation.JsonProperty;
+
+public class Ok {
+
+ public static final Ok INSTANCE = new Ok();
+
+ @JsonProperty
+ public boolean ok() {
+ return true;
+ }
+}
diff --git a/nouveau/src/main/java/org/apache/couchdb/nouveau/core/IndexManager.java b/nouveau/src/main/java/org/apache/couchdb/nouveau/core/IndexManager.java
index 85230d322..c4f59f7a1 100644
--- a/nouveau/src/main/java/org/apache/couchdb/nouveau/core/IndexManager.java
+++ b/nouveau/src/main/java/org/apache/couchdb/nouveau/core/IndexManager.java
@@ -33,7 +33,6 @@ import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
-import java.util.stream.Stream;
import org.apache.couchdb.nouveau.api.IndexDefinition;
import org.apache.couchdb.nouveau.lucene9.Lucene9AnalyzerFactory;
import org.apache.couchdb.nouveau.lucene9.Lucene9Index;
@@ -250,35 +249,49 @@ public final class IndexManager implements Managed {
}
public void deleteAll(final String path, final List<String> exclusions) throws IOException {
- LOGGER.info("deleting indexes below {} (excluding {})", path, exclusions == null ? "nothing" : exclusions);
+ LOGGER.info(
+ "deleting indexes matching {} (excluding {})",
+ path,
+ exclusions == null || exclusions.isEmpty() ? "nothing" : exclusions);
+ var parts = path.split("/");
+ deleteAll(rootDir, parts, 0, exclusions);
+ }
- final Path indexRootPath = indexRootPath(path);
- if (!indexRootPath.toFile().exists()) {
+ private void deleteAll(final Path path, final String[] parts, final int index, final List<String> exclusions)
+ throws IOException {
+ // End of the path
+ if (index == parts.length - 1) {
+ try (var stream = Files.newDirectoryStream(path, parts[index])) {
+ stream.forEach(p -> {
+ if (exclusions != null && exclusions.indexOf(p.getFileName().toString()) != -1) {
+ return;
+ }
+ final String relativeName = rootDir.relativize(p).toString();
+ try {
+ deleteIndex(relativeName);
+ } catch (final IOException | InterruptedException e) {
+ LOGGER.error("Exception deleting {}", p, e);
+ }
+ // Clean any newly empty directories.
+ do {
+ final File f = p.toFile();
+ if (f.isDirectory() && f.list().length == 0) {
+ f.delete();
+ }
+ } while ((p = p.getParent()) != null && !rootDir.equals(p));
+ });
+ }
return;
}
- Stream<Path> stream = Files.find(indexRootPath, 100, (p, attr) -> attr.isDirectory() && isIndex(p));
- try {
- stream.forEach((p) -> {
- final String relativeToExclusions = indexRootPath.relativize(p).toString();
- if (exclusions != null && exclusions.indexOf(relativeToExclusions) != -1) {
- return;
- }
- final String relativeName = rootDir.relativize(p).toString();
+ // Recurse
+ try (var stream = Files.newDirectoryStream(path, parts[index])) {
+ stream.forEach(p -> {
try {
- deleteIndex(relativeName);
- } catch (final IOException | InterruptedException e) {
- LOGGER.error("Exception deleting {}", p, e);
+ deleteAll(p, parts, index + 1, exclusions);
+ } catch (IOException e) {
+ LOGGER.warn("Exception during delete of " + rootDir.relativize(p), e);
}
- // Clean any newly empty directories.
- do {
- final File f = p.toFile();
- if (f.isDirectory() && f.list().length == 0) {
- f.delete();
- }
- } while ((p = p.getParent()) != null && !rootDir.equals(p));
});
- } finally {
- stream.close();
}
}
diff --git a/nouveau/src/main/java/org/apache/couchdb/nouveau/resources/IndexResource.java b/nouveau/src/main/java/org/apache/couchdb/nouveau/resources/IndexResource.java
index a6ca2c47b..a52e00da9 100644
--- a/nouveau/src/main/java/org/apache/couchdb/nouveau/resources/IndexResource.java
+++ b/nouveau/src/main/java/org/apache/couchdb/nouveau/resources/IndexResource.java
@@ -35,6 +35,7 @@ import org.apache.couchdb.nouveau.api.DocumentUpdateRequest;
import org.apache.couchdb.nouveau.api.IndexDefinition;
import org.apache.couchdb.nouveau.api.IndexInfo;
import org.apache.couchdb.nouveau.api.IndexInfoRequest;
+import org.apache.couchdb.nouveau.api.Ok;
import org.apache.couchdb.nouveau.api.SearchRequest;
import org.apache.couchdb.nouveau.api.SearchResults;
import org.apache.couchdb.nouveau.core.IndexManager;
@@ -54,27 +55,29 @@ public final class IndexResource {
}
@PUT
- public void createIndex(@PathParam("name") String name, @NotNull @Valid IndexDefinition indexDefinition)
+ public Ok createIndex(@PathParam("name") String name, @NotNull @Valid IndexDefinition indexDefinition)
throws IOException {
indexManager.create(name, indexDefinition);
+ return Ok.INSTANCE;
}
@DELETE
@Path("/doc/{docId}")
- public void deleteDoc(
+ public Ok deleteDoc(
@PathParam("name") String name,
@PathParam("docId") String docId,
@NotNull @Valid DocumentDeleteRequest request)
throws Exception {
- indexManager.with(name, (index) -> {
+ return indexManager.with(name, (index) -> {
index.delete(docId, request);
- return null;
+ return Ok.INSTANCE;
});
}
@DELETE
- public void deletePath(@PathParam("name") String path, @Valid final List<String> exclusions) throws IOException {
+ public Ok deletePath(@PathParam("name") String path, @Valid final List<String> exclusions) throws IOException {
indexManager.deleteAll(path, exclusions);
+ return Ok.INSTANCE;
}
@GET
@@ -85,9 +88,8 @@ public final class IndexResource {
}
@POST
- public void setIndexInfo(@PathParam("name") String name, @NotNull @Valid IndexInfoRequest request)
- throws Exception {
- indexManager.with(name, (index) -> {
+ public Ok setIndexInfo(@PathParam("name") String name, @NotNull @Valid IndexInfoRequest request) throws Exception {
+ return indexManager.with(name, (index) -> {
if (request.getMatchUpdateSeq().isPresent()
&& request.getUpdateSeq().isPresent()) {
index.setUpdateSeq(
@@ -99,7 +101,7 @@ public final class IndexResource {
request.getMatchPurgeSeq().getAsLong(),
request.getPurgeSeq().getAsLong());
}
- return null;
+ return Ok.INSTANCE;
});
}
@@ -114,14 +116,14 @@ public final class IndexResource {
@PUT
@Path("/doc/{docId}")
- public void updateDoc(
+ public Ok updateDoc(
@PathParam("name") String name,
@PathParam("docId") String docId,
@NotNull @Valid DocumentUpdateRequest request)
throws Exception {
- indexManager.with(name, (index) -> {
+ return indexManager.with(name, (index) -> {
index.update(docId, request);
- return null;
+ return Ok.INSTANCE;
});
}
}
diff --git a/nouveau/src/test/java/org/apache/couchdb/nouveau/core/IndexManagerTest.java b/nouveau/src/test/java/org/apache/couchdb/nouveau/core/IndexManagerTest.java
index a994cdd0c..bb8f0b647 100644
--- a/nouveau/src/test/java/org/apache/couchdb/nouveau/core/IndexManagerTest.java
+++ b/nouveau/src/test/java/org/apache/couchdb/nouveau/core/IndexManagerTest.java
@@ -16,7 +16,10 @@ package org.apache.couchdb.nouveau.core;
import static org.assertj.core.api.Assertions.assertThat;
import com.fasterxml.jackson.databind.ObjectMapper;
+import java.io.IOException;
+import java.nio.file.Files;
import java.nio.file.Path;
+import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ScheduledExecutorService;
@@ -24,19 +27,21 @@ import java.util.concurrent.TimeUnit;
import org.apache.couchdb.nouveau.api.IndexDefinition;
import org.apache.couchdb.nouveau.api.SearchRequest;
import org.apache.couchdb.nouveau.lucene9.ParallelSearcherFactory;
-import org.junit.jupiter.api.AfterAll;
-import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
public class IndexManagerTest {
- private static IndexManager manager;
- private static ScheduledExecutorService executorService;
+ private Path rootDir;
+ private IndexManager manager;
+ private ScheduledExecutorService executorService;
- @BeforeAll
- public static void setupManager(@TempDir Path path) throws Exception {
+ @BeforeEach
+ public void setupManager(@TempDir Path path) throws Exception {
executorService = Executors.newScheduledThreadPool(2);
+ rootDir = path;
manager = new IndexManager();
manager.setRootDir(path);
@@ -47,8 +52,8 @@ public class IndexManagerTest {
manager.start();
}
- @AfterAll
- public static void cleanup() throws Exception {
+ @AfterEach
+ public void cleanup() throws Exception {
executorService.shutdownNow();
executorService.awaitTermination(5, TimeUnit.SECONDS);
manager.stop();
@@ -82,4 +87,60 @@ public class IndexManagerTest {
});
assertThat(isOpen);
}
+
+ @Test
+ public void deleteAllRemovesIndexByName() throws Exception {
+ final IndexDefinition indexDefinition = new IndexDefinition();
+ indexDefinition.setDefaultAnalyzer("standard");
+
+ assertThat(countIndexes()).isEqualTo(0);
+ manager.create("bar", indexDefinition);
+ assertThat(countIndexes()).isEqualTo(1);
+ manager.deleteAll("bar", null);
+ assertThat(countIndexes()).isEqualTo(0);
+ }
+
+ @Test
+ public void deleteAllRemovesIndexByPath() throws Exception {
+ final IndexDefinition indexDefinition = new IndexDefinition();
+ indexDefinition.setDefaultAnalyzer("standard");
+
+ assertThat(countIndexes()).isEqualTo(0);
+ manager.create("foo/bar", indexDefinition);
+ assertThat(countIndexes()).isEqualTo(1);
+ manager.deleteAll("foo/bar", null);
+ assertThat(countIndexes()).isEqualTo(0);
+ }
+
+ @Test
+ public void deleteAllRemovesIndexByGlob() throws Exception {
+ final IndexDefinition indexDefinition = new IndexDefinition();
+ indexDefinition.setDefaultAnalyzer("standard");
+
+ assertThat(countIndexes()).isEqualTo(0);
+ manager.create("foo/bar", indexDefinition);
+ assertThat(countIndexes()).isEqualTo(1);
+ manager.deleteAll("foo/*", null);
+ assertThat(countIndexes()).isEqualTo(0);
+ }
+
+ @Test
+ public void deleteAllRemovesIndexByGlobExceptExclusions() throws Exception {
+ final IndexDefinition indexDefinition = new IndexDefinition();
+ indexDefinition.setDefaultAnalyzer("standard");
+
+ assertThat(countIndexes()).isEqualTo(0);
+ manager.create("foo/bar", indexDefinition);
+ manager.create("foo/baz", indexDefinition);
+ assertThat(countIndexes()).isEqualTo(2);
+ manager.deleteAll("foo/*", List.of("bar"));
+ assertThat(countIndexes()).isEqualTo(1);
+ }
+
+ private long countIndexes() throws IOException {
+ try (var stream =
+ Files.find(rootDir, 10, (p, attr) -> p.getFileName().toString().equals("index_definition.json"))) {
+ return stream.count();
+ }
+ }
}
diff --git a/rebar.config.script b/rebar.config.script
index 57fa8fae6..efc03a35e 100644
--- a/rebar.config.script
+++ b/rebar.config.script
@@ -150,17 +150,20 @@ SubDirs = [
"rel"
].
+% Try to keep deps in sync with .elp.toml deps
+
DepDescs = [
%% Independent Apps
{snappy, "snappy", {tag, "CouchDB-1.0.9"}},
%% %% Non-Erlang deps
{fauxton, {url, "https://github.com/apache/couchdb-fauxton"},
- {tag, "v1.3.4"}, [raw]},
+ {tag, "v1.3.5"}, [raw]},
{ibrowse, "ibrowse", {tag, "CouchDB-4.4.2-6"}},
+{gun, "gun", {tag, "2.2.0-couchdb"}},
{jiffy, "jiffy", {tag, "1.1.2"}},
-{mochiweb, "mochiweb", {tag, "v3.2.2"}},
-{meck, "meck", {tag, "1.0.0"}},
+{mochiweb, "mochiweb", {tag, "v3.3.0"}},
+{meck, "meck", {tag, "v1.1.0"}},
{recon, "recon", {tag, "2.5.6"}}
].
@@ -168,7 +171,7 @@ WithProper = lists:keyfind(with_proper, 1, CouchConfig) == {with_proper, true}.
OptionalDeps = case WithProper of
true ->
- [{proper, {url, "https://github.com/proper-testing/proper"}, "f2a44ee11a238c84403e72ee8ec68e6f65fd7e42"}];
+ [{proper, {url, "https://github.com/proper-testing/proper"}, "v1.5.0"}];
false ->
[]
end.
@@ -191,7 +194,7 @@ end.
AddConfig = [
{cover_enabled, true},
{cover_print_enabled, true},
- {require_otp_vsn, "25|26|27|28"},
+ {require_otp_vsn, "26|27|28"},
{deps_dir, "src"},
{deps, lists:map(MakeDep, DepDescs ++ OptionalDeps)},
{sub_dirs, SubDirs},
diff --git a/rel/nouveau.yaml b/rel/nouveau.yaml
index 40837f12c..0f33d5f25 100644
--- a/rel/nouveau.yaml
+++ b/rel/nouveau.yaml
@@ -8,12 +8,12 @@ logging:
server:
applicationConnectors:
- - type: http
+ - type: h2c
bindHost: 127.0.0.1
port: {{nouveau_port}}
useDateHeader: false
adminConnectors:
- - type: http
+ - type: h2c
bindHost: 127.0.0.1
port: {{nouveau_admin_port}}
useDateHeader: false
diff --git a/rel/overlay/etc/default.ini b/rel/overlay/etc/default.ini
index dfefa62dc..00d92bafe 100644
--- a/rel/overlay/etc/default.ini
+++ b/rel/overlay/etc/default.ini
@@ -71,11 +71,18 @@ view_index_dir = {{view_index_dir}}
;default_engine = couch
; Enable this to only "soft-delete" databases when DELETE /{db} requests are
-; made. This will place a .recovery directory in your data directory and
-; move deleted databases/shards there instead. You can then manually delete
-; these files later, as desired.
+; made. This will add `.deleted.couch` extension to the database shard files
+; in the data directory. You can then manually delete these files later, as
+; desired.
;enable_database_recovery = false
+; Applies only when `enable_database_recovery = false`.
+; When DELETE /{db} requests are made:
+; - If `true`, delete the database shard files from the `data` directory.
+; - If `false`, rename the database shard files and move them to the `.delete`
+; directory.
+;delete_after_rename = true
+
; Set the maximum size allowed for a partition. This helps users avoid
; inadvertently abusing partitions resulting in hot shards. The default
; is 10GiB. A value of 0 or less will disable partition size checks.
@@ -116,16 +123,43 @@ view_index_dir = {{view_index_dir}}
; When enabled, use cfile parallel reads for all the requests. By default the
; setting is "false", so only requests which are configured to bypass the IOQ
; would use the cfile parallel reads. If there is enough RAM available for a
-; large file cache and the disks have enough IO bandwith, consider enabling
+; large file cache and the disks have enough IO bandwidth, consider enabling
; this setting.
;cfile_skip_ioq = false
-[purge]
-; Allowed maximum number of documents in one purge request
-;max_document_id_number = 100
+; CouchDB will not normally allow a database downgrade to a previous version if
+; the new version added new fields to the database file header structure. You
+; can disable this protection by setting this to false. We recommend
+; re-enabling the protection after you have performed the downgrade but it is
+; not mandatory to do so.
+; Note that some future versions of CouchDB might not support downgrade at all,
+; whatever value this is set to. In those cases CouchDB will refuse to
+; downgrade or even open the databases in question.
+;prohibit_downgrade = true
+
+[bt_engine_cache]
+; Memory used for btree engine cache. This is a cache for top levels of
+; database btrees (id tree, seq tree) and a few terms from the db header. Value
+; is in bytes.
+;max_size = 67108864
+;
+; Items not accessed in a while are eventually evicted. However, if the memory
+; used is below this percentage, then even the unused items are left in the
+; cache. The trade-off here is when a new workload starts, it may find the
+; cache with some stale items during the first few seconds and not be able to
+; insert its entries in.
+;leave_percent = 30
+;
+; Cache database btree nodes up to this depth only. Depth starts at 1 at root,
+; then at 2 the next level down, and so on. Only intermediate (pointer) nodes
+; will be cached, those are the nodes which point to other nodes, as opposed to
+; leaf key-value nodes, which hold revision trees. To disable db btree node
+; caching set the value to 0
+;db_btree_cache_depth = 3
+[purge]
; Allowed maximum number of accumulated revisions in one purge request
-;max_revisions_number = 1000
+;max_revisions_number = infinity
; Allowed durations when index is not updated for local purge checkpoint
; document. Default is 24 hours.
@@ -217,7 +251,7 @@ bind_address = 127.0.0.1
; Set to false to revert to a previous _bulk_get implementation using single
; doc fetches internally. Using batches should be faster, however there may be
-; bugs in the new new implemention, so expose this option to allow reverting to
+; bugs in the new implementation, so expose this option to allow reverting to
; the old behavior.
;bulk_get_use_batches = true
@@ -401,7 +435,8 @@ hash_algorithms = sha256, sha
;uuid_prefix_len = 7
;request_timeout = 60000
;all_docs_timeout = 10000
-;attachments_timeout = 60000
+;all_docs_view_permsg_timeout = 5000
+;attachments_timeout = 600000
;view_timeout = infinity
;view_permsg_timeout = 3600000
;partition_view_timeout = infinity
@@ -428,6 +463,16 @@ hash_algorithms = sha256, sha
;update_db = true
;[view_updater]
+; Configure the queue capacity used during indexing. These settings apply to
+; both the queue between the changes feed and the JS mapper, and between the
+; JS mapper and the disk writer.
+; Whichever limit happens to be hit first is the one that takes effect.
+
+; The maximum queue memory size
+;queue_memory_cap = 100000
+; The maximum queue length
+;queue_item_cap = 500
+
;min_writer_items = 100
;min_writer_size = 16777216
@@ -500,12 +545,19 @@ authentication_db = _users
; Erlang Query Server
;enable_erlang_query_server = false
-; Changing reduce_limit to false will disable reduce_limit.
-; If you think you're hitting reduce_limit with a "good" reduce function,
-; please let us know on the mailing list so we can fine tune the heuristic.
+
[query_server_config]
;commit_freq = 5
+; Changing reduce_limit to false will disable reduce_limit. Setting the reduce
+; limit to log will only log a warning instead of crashing the view. If you
+; think you're hitting reduce_limit with a "good" reduce function, please let
+; us know on the mailing list so we can fine tune the heuristic.
;reduce_limit = true
+; Don't log/crash a reduce if the result is less than this number of bytes;
+;reduce_limit_threshold = 5000
+; Don't log/crash a reduce if the result is less than the ratio multiplied
+; by input size
+;reduce_limit_ratio = 2.0
;os_process_limit = 100
;os_process_idle_limit = 300
;os_process_soft_limit = 100
@@ -659,13 +711,17 @@ partitioned||* = true
; Maximum peer certificate depth (must be set even if certificate validation is off).
;ssl_certificate_max_depth = 3
+; How often to reload operating system CA certificates (in hours). The default
+; is 24 hours.
+;cacert_reload_interval_hours = 24
+
; Maximum document ID length for replication.
;max_document_id_length = infinity
; How much time to wait before retrying after a missing doc exception. This
; exception happens if the document was seen in the changes feed, but internal
; replication hasn't caught up yet, and fetching document's revisions
-; fails. This a common scenario when source is updated while continuous
+; fails. This is a common scenario when source is updated while continuous
; replication is running. The retry period would depend on how quickly internal
; replication is expected to catch up. In general this is an optimisation to
; avoid crashing the whole replication job, which would consume more resources
@@ -684,7 +740,7 @@ partitioned||* = true
; couch_replicator_auth_session - use _session cookie authentication
; couch_replicator_auth_noop - use basic authentication (previous default)
; Currently, the new _session cookie authentication is tried first, before
-; falling back to the old basic authenticaion default:
+; falling back to the old basic authentication default:
;auth_plugins = couch_replicator_auth_session,couch_replicator_auth_noop
; To restore the old behaviour, use the following value:
@@ -712,7 +768,7 @@ partitioned||* = true
; priority 0, and would render this algorithm useless. The default value of
; 0.98 is picked such that if a job ran for one scheduler cycle, then didn't
; get to run for 7 hours, it would still have priority > 0. 7 hours was picked
-; as it was close enought to 8 hours which is the default maximum error backoff
+; as it was close enough to 8 hours which is the default maximum error backoff
; interval.
;priority_coeff = 0.98
@@ -925,12 +981,11 @@ port = {{prometheus_port}}
[custodian]
; When set to `true`, force using `[cluster] n` values as the expected n value
-; of of shard copies. In cases where the application prevents creating
-; non-default n databases, this could help detect case where the shard map was
-; altered by hand, or via an external tools, such that it doesn't have the
-; necessary number of copies for some ranges. By default, when the setting is
-; `false`, the expected n value is based on the number of available copies in
-; the shard map.
+; of shard copies. In cases where the application prevents creating non-default
+; n databases, this could help detect case where the shard map was altered by
+; hand, or via an external tools, such that it doesn't have the necessary number
+; of copies for some ranges. By default, when the setting is `false`, the
+; expected n value is based on the number of available copies in the shard map.
;use_cluster_n_as_expected_n = false
[nouveau]
@@ -1001,6 +1056,17 @@ url = {{nouveau_url}}
; is shared across all running plugins.
;doc_rate_limit = 1000
+; Limit the rate per second at which plugins write/update documents. The rate
+; is shared across all running plugins. Unlike other rate limit which are
+; applied automatically by the plugin backend this rate assume the plugins will
+; explicitly use the couch_scanner_rate_limiter API when performing writes.
+;doc_write_rate_limit = 500
+
+; Batch size to use when fetching design documents. For lots of small design
+; documents this value could be increased to 500 or 1000. If design documents
+; are large (100KB+) it could make sense to decrease it a bit to 25 or 10.
+;ddoc_batch_size = 100
+
[couch_scanner_plugins]
;couch_scanner_plugin_ddoc_features = false
;couch_scanner_plugin_find = false
diff --git a/rel/overlay/etc/vm.args b/rel/overlay/etc/vm.args
index d762c33bf..b4167be7b 100644
--- a/rel/overlay/etc/vm.args
+++ b/rel/overlay/etc/vm.args
@@ -57,6 +57,17 @@
#
-kernel prevent_overlapping_partitions false
+# Set Erlang process limit. If not set in Erlang 27 and greater versions it
+# defaults to 1048576. In Erlang versions less than 27 it defaulted to 262144.
+# When a cluster reaches this limit it will emit "Too many processes" error in
+# the log. That could be a time to bump it up. The actual value set will be a
+# larger power of 2 number. To check the actual limit call
+# `erlang:system_info(process_limit).` in remsh.
+#
+# For additional info see
+# https://www.erlang.org/doc/apps/erts/erl_cmd.html#emulator-flags
++P 1048576
+
# Increase the pool of dirty IO schedulers from 10 to 16
# Dirty IO schedulers are used for file IO.
+SDio 16
diff --git a/rel/reltool.config b/rel/reltool.config
index c1f0ea070..b85bd49b6 100644
--- a/rel/reltool.config
+++ b/rel/reltool.config
@@ -48,6 +48,8 @@
ets_lru,
fabric,
global_changes,
+ gun,
+ cowlib,
ibrowse,
ioq,
jiffy,
@@ -111,6 +113,8 @@
{app, ets_lru, [{incl_cond, include}]},
{app, fabric, [{incl_cond, include}]},
{app, global_changes, [{incl_cond, include}]},
+ {app, gun, [{incl_cond, include}]},
+ {app, cowlib, [{incl_cond, include}]},
{app, ibrowse, [{incl_cond, include}]},
{app, ioq, [{incl_cond, include}]},
{app, jiffy, [{incl_cond, include}]},
diff --git a/share/server/views.js b/share/server/views.js
index b59c9912e..623b5c4b5 100644
--- a/share/server/views.js
+++ b/share/server/views.js
@@ -36,9 +36,9 @@ var Views = (function() {
var reduce_line = JSON.stringify(reductions);
var reduce_length = reduce_line.length;
var input_length = State.line_length - code_size
- // TODO make reduce_limit config into a number
if (State.query_config && State.query_config.reduce_limit &&
- reduce_length > 4096 && ((reduce_length * 2) > input_length)) {
+ reduce_length > State.query_config.reduce_limit_threshold &&
+ ((reduce_length * State.query_config.reduce_limit_ratio) > input_length)) {
var log_message = [
"Reduce output must shrink more rapidly:",
"input size:", input_length,
diff --git a/src/chttpd/src/chttpd_db.erl b/src/chttpd/src/chttpd_db.erl
index a43baeae4..d0f5e0111 100644
--- a/src/chttpd/src/chttpd_db.erl
+++ b/src/chttpd/src/chttpd_db.erl
@@ -454,8 +454,7 @@ delete_db_req(#httpd{} = Req, DbName) ->
end.
do_db_req(#httpd{path_parts = [DbName | _], user_ctx = Ctx} = Req, Fun) ->
- Shard = hd(mem3:shards(DbName)),
- Props = couch_util:get_value(props, Shard#shard.opts, []),
+ Props = mem3:props(DbName),
Opts =
case Ctx of
undefined ->
@@ -695,22 +694,17 @@ db_req(#httpd{method = 'POST', path_parts = [_, <<"_purge">>]} = Req, Db) ->
Options = [{user_ctx, Req#httpd.user_ctx}, {w, W}],
{IdsRevs} = chttpd:json_body_obj(Req),
IdsRevs2 = [{Id, couch_doc:parse_revs(Revs)} || {Id, Revs} <- IdsRevs],
- MaxIds = config:get_integer("purge", "max_document_id_number", 100),
- case length(IdsRevs2) =< MaxIds of
- false -> throw({bad_request, "Exceeded maximum number of documents."});
- true -> ok
- end,
- RevsLen = lists:foldl(
- fun({_Id, Revs}, Acc) ->
- length(Revs) + Acc
- end,
- 0,
- IdsRevs2
- ),
- MaxRevs = config:get_integer("purge", "max_revisions_number", 1000),
- case RevsLen =< MaxRevs of
- false -> throw({bad_request, "Exceeded maximum number of revisions."});
- true -> ok
+ case config:get("purge", "max_revisions_number", "infinity") of
+ "infinity" ->
+ ok;
+ Val ->
+ MaxRevs = list_to_integer(Val),
+ SumFun = fun({_Id, Revs}, Acc) -> length(Revs) + Acc end,
+ RevsLen = lists:foldl(SumFun, 0, IdsRevs2),
+ case RevsLen =< MaxRevs of
+ false -> throw({bad_request, "Exceeded maximum number of revisions."});
+ true -> ok
+ end
end,
couch_stats:increment_counter([couchdb, document_purges, total], length(IdsRevs2)),
Results2 =
@@ -1419,7 +1413,7 @@ receive_request_data(Req, Len) when Len == chunked ->
GetChunk
};
receive_request_data(Req, LenLeft) when LenLeft > 0 ->
- Len = erlang:min(4096, LenLeft),
+ Len = min(4096, LenLeft),
Data = chttpd:recv(Req, Len),
{Data, fun() -> receive_request_data(Req, LenLeft - iolist_size(Data)) end};
receive_request_data(_Req, _) ->
@@ -1460,13 +1454,13 @@ purge_results_to_json([{DocId, _Revs} | RIn], [{accepted, PRevs} | ROut]) ->
{Code, Results} = purge_results_to_json(RIn, ROut),
couch_stats:increment_counter([couchdb, document_purges, success]),
NewResults = [{DocId, couch_doc:revs_to_strs(PRevs)} | Results],
- {erlang:max(Code, 202), NewResults};
+ {max(Code, 202), NewResults};
purge_results_to_json([{DocId, _Revs} | RIn], [Error | ROut]) ->
{Code, Results} = purge_results_to_json(RIn, ROut),
{NewCode, ErrorStr, Reason} = chttpd:error_info(Error),
couch_stats:increment_counter([couchdb, document_purges, failure]),
NewResults = [{DocId, {[{error, ErrorStr}, {reason, Reason}]}} | Results],
- {erlang:max(NewCode, Code), NewResults}.
+ {max(NewCode, Code), NewResults}.
send_updated_doc(Req, Db, DocId, Json) ->
send_updated_doc(Req, Db, DocId, Json, []).
@@ -1526,9 +1520,9 @@ update_doc(Db, DocId, #doc{deleted = Deleted, body = DocBody} = Doc, Options) ->
{'DOWN', Ref, _, _, {exit_throw, Reason}} ->
throw(Reason);
{'DOWN', Ref, _, _, {exit_error, Reason}} ->
- erlang:error(Reason);
+ error(Reason);
{'DOWN', Ref, _, _, {exit_exit, Reason}} ->
- erlang:exit(Reason)
+ exit(Reason)
end,
case Result of
diff --git a/src/chttpd/src/chttpd_external.erl b/src/chttpd/src/chttpd_external.erl
index 4cd1d996f..fe63de3b2 100644
--- a/src/chttpd/src/chttpd_external.erl
+++ b/src/chttpd/src/chttpd_external.erl
@@ -139,7 +139,7 @@ to_json_terms(Data) ->
to_json_terms([], Acc) ->
{lists:reverse(Acc)};
to_json_terms([{Key, Value} | Rest], Acc) when is_atom(Key) ->
- to_json_terms(Rest, [{list_to_binary(atom_to_list(Key)), list_to_binary(Value)} | Acc]);
+ to_json_terms(Rest, [{atom_to_binary(Key), list_to_binary(Value)} | Acc]);
to_json_terms([{Key, Value} | Rest], Acc) ->
to_json_terms(Rest, [{list_to_binary(Key), list_to_binary(Value)} | Acc]).
diff --git a/src/chttpd/src/chttpd_misc.erl b/src/chttpd/src/chttpd_misc.erl
index d0bf363f3..c22a27b98 100644
--- a/src/chttpd/src/chttpd_misc.erl
+++ b/src/chttpd/src/chttpd_misc.erl
@@ -252,7 +252,7 @@ replicate({Props} = PostBody, Ctx) ->
]),
case rpc:call(Node, couch_replicator, replicate, [PostBody, Ctx]) of
{badrpc, Reason} ->
- erlang:error(Reason);
+ error(Reason);
Res ->
Res
end
@@ -281,7 +281,7 @@ cancel_replication(PostBody, Ctx) ->
choose_node(Key) when is_binary(Key) ->
Checksum = erlang:crc32(Key),
- Nodes = lists:sort([node() | erlang:nodes()]),
+ Nodes = lists:sort([node() | nodes()]),
lists:nth(1 + Checksum rem length(Nodes), Nodes);
choose_node(Key) ->
choose_node(?term_to_bin(Key)).
diff --git a/src/chttpd/src/chttpd_node.erl b/src/chttpd/src/chttpd_node.erl
index 2a67da9e3..b0ea3686c 100644
--- a/src/chttpd/src/chttpd_node.erl
+++ b/src/chttpd/src/chttpd_node.erl
@@ -191,7 +191,7 @@ handle_node_req(#httpd{
"max_http_request_size", 4294967296
),
NewOpts = [{body, MochiReq0:recv_body(MaxSize)} | MochiReq0:get(opts)],
- Ref = erlang:make_ref(),
+ Ref = make_ref(),
MochiReq = mochiweb_request:new(
{remote, self(), Ref},
NewOpts,
@@ -286,6 +286,7 @@ get_stats() ->
{run_queue, SQ},
{run_queue_dirty_cpu, DCQ},
{ets_table_count, length(ets:all())},
+ {bt_engine_cache, couch_bt_engine_cache:info()},
{context_switches, element(1, statistics(context_switches))},
{reductions, element(1, statistics(reductions))},
{garbage_collection_count, NumberOfGCs},
diff --git a/src/chttpd/test/eunit/chttpd_auth_hash_algorithms_tests.erl b/src/chttpd/test/eunit/chttpd_auth_hash_algorithms_tests.erl
index 3085079ad..554da524e 100644
--- a/src/chttpd/test/eunit/chttpd_auth_hash_algorithms_tests.erl
+++ b/src/chttpd/test/eunit/chttpd_auth_hash_algorithms_tests.erl
@@ -64,7 +64,7 @@ base_url() ->
"http://" ++ Addr ++ ":" ++ Port.
make_auth_session_string(HashAlgorithm, User, Secret, TimeStamp) ->
- SessionData = User ++ ":" ++ erlang:integer_to_list(TimeStamp, 16),
+ SessionData = User ++ ":" ++ integer_to_list(TimeStamp, 16),
Hash = couch_util:hmac(HashAlgorithm, Secret, SessionData),
"AuthSession=" ++ couch_util:encodeBase64Url(SessionData ++ ":" ++ ?b2l(Hash)).
diff --git a/src/chttpd/test/eunit/chttpd_purge_tests.erl b/src/chttpd/test/eunit/chttpd_purge_tests.erl
index ef8af6971..3b91571ee 100644
--- a/src/chttpd/test/eunit/chttpd_purge_tests.erl
+++ b/src/chttpd/test/eunit/chttpd_purge_tests.erl
@@ -49,7 +49,6 @@ purge_test_() ->
?TDEF_FE(t_purge_only_post_allowed),
?TDEF_FE(t_empty_purge_request),
?TDEF_FE(t_ok_purge_request),
- ?TDEF_FE(t_ok_purge_with_max_document_id_number),
?TDEF_FE(t_accepted_purge_request),
?TDEF_FE(t_partial_purge_request),
?TDEF_FE(t_mixed_purge_request),
@@ -85,23 +84,6 @@ t_ok_purge_request(DbUrl) ->
?assertMatch(#{<<"purge_seq">> := null, <<"purged">> := IdsRevs}, Response2),
?assert(Status =:= 201 orelse Status =:= 202).
-t_ok_purge_with_max_document_id_number(DbUrl) ->
- PurgedDocsNum = 101,
- {201, Response1} = create_docs(DbUrl, docs(PurgedDocsNum)),
- IdsRevs = ids_revs(Response1),
-
- {400, #{<<"reason">> := Error}} = req(post, url(DbUrl, "_purge"), IdsRevs),
- ?assertEqual(<<"Exceeded maximum number of documents.">>, Error),
-
- ok = config:set("purge", "max_document_id_number", "101", _Persist = false),
- try
- {Status, Response2} = req(post, url(DbUrl, "_purge"), IdsRevs),
- ?assertMatch(#{<<"purge_seq">> := null, <<"purged">> := IdsRevs}, Response2),
- ?assert(Status =:= 201 orelse Status =:= 202)
- after
- ok = config:delete("purge", "max_document_id_number", _Persist)
- end.
-
t_accepted_purge_request(DbUrl) ->
try
meck:new(fabric, [passthrough]),
@@ -173,24 +155,14 @@ t_over_many_ids_or_revs_purge_request(DbUrl) ->
<<"doc3">> => [Rev3]
},
- % Ids larger than expected
- config:set("purge", "max_document_id_number", "1", _Persist = false),
- try
- {Status1, #{<<"reason">> := Error1}} = req(post, url(DbUrl, "_purge"), IdsRevs),
- ?assertEqual(<<"Exceeded maximum number of documents.">>, Error1),
- ?assertEqual(400, Status1)
- after
- config:delete("purge", "max_document_id_number", _Persist)
- end,
-
% Revs larger than expected
- config:set("purge", "max_revisions_number", "1", _Persist),
+ config:set("purge", "max_revisions_number", "1", false),
try
{Status2, #{<<"reason">> := Error2}} = req(post, url(DbUrl, "_purge"), IdsRevs),
?assertEqual(<<"Exceeded maximum number of revisions.">>, Error2),
?assertEqual(400, Status2)
after
- config:delete("purge", "max_revisions_number", _Persist)
+ config:delete("purge", "max_revisions_number", false)
end.
t_purged_infos_limit_only_get_put_allowed(DbUrl) ->
@@ -316,7 +288,7 @@ create_docs(Url, Docs) ->
docs(Counter) ->
lists:foldl(
fun(I, Acc) ->
- Id = ?l2b(integer_to_list(I)),
+ Id = integer_to_binary(I),
Doc = #{<<"_id">> => Id, <<"val">> => I},
[Doc | Acc]
end,
diff --git a/src/config/src/config.erl b/src/config/src/config.erl
index 695bc40b9..70b8883f9 100644
--- a/src/config/src/config.erl
+++ b/src/config/src/config.erl
@@ -100,7 +100,7 @@ to_integer(Int) when is_integer(Int) ->
to_integer(List) when is_list(List) ->
list_to_integer(List);
to_integer(Bin) when is_binary(Bin) ->
- list_to_integer(binary_to_list(Bin)).
+ binary_to_integer(Bin).
get_float(Section, Key, Default) when is_float(Default) ->
try
@@ -125,7 +125,7 @@ to_float(List) when is_list(List) ->
to_float(Int) when is_integer(Int) ->
list_to_float(integer_to_list(Int) ++ ".0");
to_float(Bin) when is_binary(Bin) ->
- list_to_float(binary_to_list(Bin)).
+ binary_to_float(Bin).
get_boolean(Section, Key, Default) when is_boolean(Default) ->
try
diff --git a/src/config/src/config_listener_mon.erl b/src/config/src/config_listener_mon.erl
index b74a61306..d794e37ce 100644
--- a/src/config/src/config_listener_mon.erl
+++ b/src/config/src/config_listener_mon.erl
@@ -40,7 +40,7 @@ subscribe(Module, InitSt) ->
end.
init({Pid, Mod, InitSt}) ->
- Ref = erlang:monitor(process, Pid),
+ Ref = monitor(process, Pid),
case config_listener:start(Mod, {Mod, Pid}, {Pid, InitSt}) of
ok ->
proc_lib:init_ack({ok, self()}),
diff --git a/src/config/test/config_tests.erl b/src/config/test/config_tests.erl
index 1775e4f39..4e3bf60f7 100644
--- a/src/config/test/config_tests.erl
+++ b/src/config/test/config_tests.erl
@@ -700,15 +700,15 @@ should_remove_handler_when_pid_exits({_Apps, Pid}) ->
% Monitor the config_listener_mon process
{monitored_by, [Mon]} = process_info(Pid, monitored_by),
- MonRef = erlang:monitor(process, Mon),
+ MonRef = monitor(process, Mon),
% Kill the process synchronously
- PidRef = erlang:monitor(process, Pid),
+ PidRef = monitor(process, Pid),
exit(Pid, kill),
receive
{'DOWN', PidRef, _, _, _} -> ok
after ?TIMEOUT ->
- erlang:error({timeout, config_listener_death})
+ error({timeout, config_listener_death})
end,
% Wait for the config_listener_mon process to
@@ -716,7 +716,7 @@ should_remove_handler_when_pid_exits({_Apps, Pid}) ->
receive
{'DOWN', MonRef, _, _, normal} -> ok
after ?TIMEOUT ->
- erlang:error({timeout, config_listener_mon_death})
+ error({timeout, config_listener_mon_death})
end,
?assertEqual(0, n_handlers())
@@ -728,7 +728,7 @@ should_stop_monitor_on_error({_Apps, Pid}) ->
% Monitor the config_listener_mon process
{monitored_by, [Mon]} = process_info(Pid, monitored_by),
- MonRef = erlang:monitor(process, Mon),
+ MonRef = monitor(process, Mon),
% Have the process throw an error
?assertEqual(ok, config:set("throw_error", "foo", "bar", false)),
@@ -742,7 +742,7 @@ should_stop_monitor_on_error({_Apps, Pid}) ->
receive
{'DOWN', MonRef, _, _, shutdown} -> ok
after ?TIMEOUT ->
- erlang:error({timeout, config_listener_mon_shutdown})
+ error({timeout, config_listener_mon_shutdown})
end,
?assertEqual(0, n_handlers())
@@ -784,7 +784,7 @@ should_unsubscribe_when_subscriber_gone(_Subscription, {_Apps, Pid}) ->
?assert(is_process_alive(Pid)),
% Monitor subscriber process
- MonRef = erlang:monitor(process, Pid),
+ MonRef = monitor(process, Pid),
exit(Pid, kill),
@@ -792,7 +792,7 @@ should_unsubscribe_when_subscriber_gone(_Subscription, {_Apps, Pid}) ->
receive
{'DOWN', MonRef, _, _, _} -> ok
after ?TIMEOUT ->
- erlang:error({timeout, config_notifier_shutdown})
+ error({timeout, config_notifier_shutdown})
end,
?assertNot(is_process_alive(Pid)),
@@ -1015,7 +1015,7 @@ wait_config_get(Sec, Key, Val) ->
spawn_config_listener() ->
Self = self(),
- Pid = erlang:spawn(fun() ->
+ Pid = spawn(fun() ->
ok = config:listen_for_changes(?MODULE, {self(), undefined}),
Self ! registered,
loop(undefined)
@@ -1023,13 +1023,13 @@ spawn_config_listener() ->
receive
registered -> ok
after ?TIMEOUT ->
- erlang:error({timeout, config_handler_register})
+ error({timeout, config_handler_register})
end,
Pid.
spawn_config_notifier(Subscription) ->
Self = self(),
- Pid = erlang:spawn(fun() ->
+ Pid = spawn(fun() ->
ok = config:subscribe_for_changes(Subscription),
Self ! registered,
loop(undefined)
@@ -1037,7 +1037,7 @@ spawn_config_notifier(Subscription) ->
receive
registered -> ok
after ?TIMEOUT ->
- erlang:error({timeout, config_handler_register})
+ error({timeout, config_handler_register})
end,
Pid.
@@ -1050,7 +1050,7 @@ loop(undefined) ->
{get_msg, _, _} = Msg ->
loop(Msg);
Msg ->
- erlang:error({invalid_message, Msg})
+ error({invalid_message, Msg})
end;
loop({get_msg, From, Ref}) ->
receive
@@ -1059,7 +1059,7 @@ loop({get_msg, From, Ref}) ->
{config_change, _, _, _, _} = Msg ->
From ! {Ref, Msg};
Msg ->
- erlang:error({invalid_message, Msg})
+ error({invalid_message, Msg})
end,
loop(undefined);
loop({config_msg, _} = Msg) ->
@@ -1067,17 +1067,17 @@ loop({config_msg, _} = Msg) ->
{get_msg, From, Ref} ->
From ! {Ref, Msg};
Msg ->
- erlang:error({invalid_message, Msg})
+ error({invalid_message, Msg})
end,
loop(undefined).
getmsg(Pid) ->
- Ref = erlang:make_ref(),
+ Ref = make_ref(),
Pid ! {get_msg, self(), Ref},
receive
{Ref, {config_msg, Msg}} -> Msg
after ?TIMEOUT ->
- erlang:error({timeout, config_msg})
+ error({timeout, config_msg})
end.
n_handlers() ->
@@ -1112,7 +1112,7 @@ wait_process_restart(Name, Timeout, Delay, Started, _Prev) ->
end.
stop_sync(Pid, Timeout) when is_pid(Pid) ->
- MRef = erlang:monitor(process, Pid),
+ MRef = monitor(process, Pid),
try
begin
catch unlink(Pid),
@@ -1125,7 +1125,7 @@ stop_sync(Pid, Timeout) when is_pid(Pid) ->
end
end
after
- erlang:demonitor(MRef, [flush])
+ demonitor(MRef, [flush])
end;
stop_sync(_, _) ->
error(badarg).
diff --git a/src/couch/include/couch_db.hrl b/src/couch/include/couch_db.hrl
index 9c1df21b6..138c202d5 100644
--- a/src/couch/include/couch_db.hrl
+++ b/src/couch/include/couch_db.hrl
@@ -182,16 +182,6 @@
db_open_options = []
}).
--record(btree, {
- fd,
- root,
- extract_kv,
- assemble_kv,
- less,
- reduce = nil,
- compression = ?DEFAULT_COMPRESSION
-}).
-
-record(proc, {
pid,
lang,
diff --git a/src/couch/include/couch_eunit.hrl b/src/couch/include/couch_eunit.hrl
index 3ffa0506f..2c10e257d 100644
--- a/src/couch/include/couch_eunit.hrl
+++ b/src/couch/include/couch_eunit.hrl
@@ -68,7 +68,7 @@
((fun (__X) ->
case (Expr) of
__V when __V == __X -> ok;
- __Y -> erlang:error({assertEquiv_failed,
+ __Y -> error({assertEquiv_failed,
[{module, ?MODULE},
{line, ?LINE},
{expression, (??Expr)},
diff --git a/src/couch/include/couch_eunit_proper.hrl b/src/couch/include/couch_eunit_proper.hrl
index dcf07701a..75172bfb8 100644
--- a/src/couch/include/couch_eunit_proper.hrl
+++ b/src/couch/include/couch_eunit_proper.hrl
@@ -18,12 +18,12 @@
{
atom_to_list(F),
{timeout, QuickcheckTimeout,
- ?_assert(proper:quickcheck(?MODULE:F(), [
+ ?_test(?assertMatch(true, proper:quickcheck(?MODULE:F(), [
{to_file, user},
{start_size, 2},
{numtests, NumTests},
long_result
- ]))}
+ ]), "Failed property test '" ++ atom_to_list(F) ++ "'"))}
}
|| {F, 0} <- ?MODULE:module_info(exports), F > 'prop_', F < 'prop`'
]).
diff --git a/src/couch/priv/couch_cfile/couch_cfile.c b/src/couch/priv/couch_cfile/couch_cfile.c
index 06328b069..c7e6f16f0 100644
--- a/src/couch/priv/couch_cfile/couch_cfile.c
+++ b/src/couch/priv/couch_cfile/couch_cfile.c
@@ -11,7 +11,15 @@
// the License.
-#ifndef _WIN32
+// Not supported on Windows or 32 bit architectures. When not supported the NIF
+// will still build, but the API functions will return {error, einval}, and
+// we'd fallback to the regular file API then
+//
+#if !defined(_WIN32) && defined(__LP64__)
+#define COUCH_CFILE_SUPPORTED 1
+#endif
+
+#ifdef COUCH_CFILE_SUPPORTED
#include <errno.h>
#include <limits.h>
@@ -225,7 +233,7 @@ int efile_datasync(int fd, posix_errno_t* res_errno) {
//
static ERL_NIF_TERM dup_nif(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[])
{
-#ifndef _WIN32
+#ifdef COUCH_CFILE_SUPPORTED
int fd, newfd;
handle_t* hdl;
ErlNifRWLock *lock;
@@ -293,7 +301,7 @@ static ERL_NIF_TERM dup_nif(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[])
static ERL_NIF_TERM close_nif(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[])
{
-#ifndef _WIN32
+#ifdef COUCH_CFILE_SUPPORTED
handle_t* hdl;
if (argc != 1 || !get_handle(env, argv[0], &hdl)) {
@@ -326,7 +334,7 @@ static ERL_NIF_TERM close_nif(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[
//
static ERL_NIF_TERM close_fd_nif(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[])
{
-#ifndef _WIN32
+#ifdef COUCH_CFILE_SUPPORTED
int fd;
if (argc != 1 || !enif_is_number(env, argv[0])) {
@@ -351,7 +359,7 @@ static ERL_NIF_TERM close_fd_nif(ErlNifEnv *env, int argc, const ERL_NIF_TERM ar
//
static ERL_NIF_TERM pread_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
-#ifndef _WIN32
+#ifdef COUCH_CFILE_SUPPORTED
handle_t* hdl;
long offset, block_size, bytes_read;
SysIOVec io_vec[1];
@@ -413,7 +421,7 @@ static ERL_NIF_TERM pread_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[
// Follows implementation from prim_file_nif.c
//
static ERL_NIF_TERM write_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) {
-#ifndef _WIN32
+#ifdef COUCH_CFILE_SUPPORTED
handle_t* hdl;
ErlNifIOVec vec, *input = &vec;
posix_errno_t res_errno = 0;
@@ -452,7 +460,7 @@ static ERL_NIF_TERM write_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[
}
static ERL_NIF_TERM seek_nif(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]) {
-#ifndef _WIN32
+#ifdef COUCH_CFILE_SUPPORTED
handle_t* hdl;
long result, offset;
int whence;
@@ -502,7 +510,7 @@ static ERL_NIF_TERM seek_nif(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]
}
static ERL_NIF_TERM datasync_nif(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]) {
-#ifndef _WIN32
+#ifdef COUCH_CFILE_SUPPORTED
handle_t* hdl;
posix_errno_t res_errno = 0;
@@ -530,7 +538,7 @@ static ERL_NIF_TERM datasync_nif(ErlNifEnv *env, int argc, const ERL_NIF_TERM ar
}
static ERL_NIF_TERM truncate_nif(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]) {
-#ifndef _WIN32
+#ifdef COUCH_CFILE_SUPPORTED
handle_t* hdl;
off_t offset;
@@ -568,7 +576,7 @@ static ERL_NIF_TERM truncate_nif(ErlNifEnv *env, int argc, const ERL_NIF_TERM ar
//
static ERL_NIF_TERM info_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
-#ifndef _WIN32
+#ifdef COUCH_CFILE_SUPPORTED
handle_t* hdl;
int fd, old_fd;
@@ -601,7 +609,7 @@ static ERL_NIF_TERM info_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]
//
static ERL_NIF_TERM eof_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
-#ifndef _WIN32
+#ifdef COUCH_CFILE_SUPPORTED
handle_t* hdl;
struct stat data;
diff --git a/src/couch/priv/stats_descriptions.cfg b/src/couch/priv/stats_descriptions.cfg
index 6a7120f87..18f32a47a 100644
--- a/src/couch/priv/stats_descriptions.cfg
+++ b/src/couch/priv/stats_descriptions.cfg
@@ -474,3 +474,15 @@
{type, counter},
{desc, <<"number of mango selector evaluations">>}
]}.
+{[couchdb, bt_engine_cache, hits], [
+ {type, counter},
+ {desc, <<"number of bt_engine cache hits">>}
+]}.
+{[couchdb, bt_engine_cache, misses], [
+ {type, counter},
+ {desc, <<"number of bt_engine cache misses">>}
+]}.
+{[couchdb, bt_engine_cache, full], [
+ {type, counter},
+ {desc, <<"number of times bt_engine cache was full">>}
+]}.
diff --git a/src/couch/rebar.config.script b/src/couch/rebar.config.script
index c4e0b7a7e..1c9809902 100644
--- a/src/couch/rebar.config.script
+++ b/src/couch/rebar.config.script
@@ -36,16 +36,16 @@ end.
CouchJSPath = filename:join(["priv", CouchJSName]).
Version = case os:getenv("COUCHDB_VERSION") of
false ->
- string:strip(os:cmd("git describe --always"), right, $\n);
+ string:trim(os:cmd("git describe --always"));
Version0 ->
- string:strip(Version0, right)
+ string:trim(Version0)
end.
GitSha = case os:getenv("COUCHDB_GIT_SHA") of
false ->
""; % release builds won\'t get a fallback
GitSha0 ->
- string:strip(GitSha0, right)
+ string:trim(GitSha0)
end.
CouchConfig = case filelib:is_file(os:getenv("COUCHDB_CONFIG")) of
@@ -151,6 +151,25 @@ ProperConfig = case code:lib_dir(proper) of
_ -> [{d, 'WITH_PROPER'}]
end.
+DpkgArchitectureCmd = "dpkg-architecture -q DEB_HOST_MULTIARCH".
+GenericMozJSIncludePaths = "-I/usr/include/mozjs-" ++ SMVsn ++ " -I/usr/local/include/mozjs-" ++ SMVsn.
+GenericMozJSLibPaths = "-L/usr/local/lib".
+
+WithDpkgArchitecture = os:find_executable("dpkg-architecture") /= false.
+WithHomebrew = os:find_executable("brew") /= false.
+
+MozJSIncludePath = case {WithDpkgArchitecture, WithHomebrew} of
+ {false, false} -> GenericMozJSIncludePaths;
+ {true, false} -> GenericMozJSIncludePaths ++ " -I/usr/include/" ++ string:trim(os:cmd(DpkgArchitectureCmd)) ++ "/mozjs-" ++ SMVsn;
+ {false, true} -> GenericMozJSIncludePaths ++ " -I/opt/homebrew/include/mozjs-" ++ SMVsn
+end.
+
+MozJSLibPath = case {WithDpkgArchitecture, WithHomebrew} of
+ {false, false} -> GenericMozJSLibPaths;
+ {true, false} -> GenericMozJSLibPaths ++ " -L/usr/lib/" ++ string:trim(os:cmd(DpkgArchitectureCmd));
+ {false, true} -> GenericMozJSLibPaths ++ " -L/opt/homebrew/lib"
+end.
+
% The include directories (parameters for the `-I` C compiler flag) are
% considered in the `configure` script as a pre-check for their existence.
% Please keep them in sync.
@@ -195,45 +214,20 @@ end.
"-DXP_UNIX -I/usr/include/mozjs-86 -I/usr/local/include/mozjs-86 -I/opt/homebrew/include/mozjs-86/ -std=c++17 -Wno-invalid-offsetof",
"-L/usr/local/lib -L /opt/homebrew/lib/ -std=c++17 -lmozjs-86 -lm"
};
- {unix, _} when SMVsn == "91" ->
- {
- "$CFLAGS -DXP_UNIX -I/usr/include/mozjs-91 -I/usr/local/include/mozjs-91 -I/opt/homebrew/include/mozjs-91/ -std=c++17 -Wno-invalid-offsetof",
- "$LDFLAGS -L/usr/local/lib -L /opt/homebrew/lib/ -std=c++17 -lmozjs-91 -lm"
- };
- {unix, _} when SMVsn == "102" ->
+ {unix, _} when SMVsn == "91"; SMVsn == "102"; SMVsn == "115"; SMVsn == "128" ->
{
- "$CFLAGS -DXP_UNIX -I/usr/include/mozjs-102 -I/usr/local/include/mozjs-102 -I/opt/homebrew/include/mozjs-102/ -std=c++17 -Wno-invalid-offsetof",
- "$LDFLAGS -L/usr/local/lib -L /opt/homebrew/lib/ -std=c++17 -lmozjs-102 -lm"
- };
- {unix, _} when SMVsn == "115" ->
- {
- "$CFLAGS -DXP_UNIX -I/usr/include/mozjs-115 -I/usr/local/include/mozjs-115 -I/opt/homebrew/include/mozjs-115/ -std=c++17 -Wno-invalid-offsetof",
- "$LDFLAGS -L/usr/local/lib -L /opt/homebrew/lib/ -std=c++17 -lmozjs-115 -lm"
- };
- {unix, _} when SMVsn == "128" ->
- {
- "$CFLAGS -DXP_UNIX -I/usr/include/mozjs-128 -I/usr/local/include/mozjs-128 -I/opt/homebrew/include/mozjs-128/ -std=c++17 -Wno-invalid-offsetof",
- "$LDFLAGS -L/usr/local/lib -L /opt/homebrew/lib/ -std=c++17 -lmozjs-128 -lm"
+ "$CFLAGS -DXP_UNIX " ++ MozJSIncludePath ++ " -std=c++17 -Wno-invalid-offsetof",
+ "$LDFLAGS " ++ MozJSLibPath ++ " -std=c++17 -lm -lmozjs-" ++ SMVsn
};
{win32, _} when SMVsn == "91" ->
{
"/std:c++17 /DXP_WIN",
"$LDFLAGS mozjs-91.lib"
};
- {win32, _} when SMVsn == "102" ->
- {
- "/std:c++17 /DXP_WIN /Zc:preprocessor /utf-8",
- "$LDFLAGS mozjs-102.lib"
- };
- {win32, _} when SMVsn == "115" ->
- {
- "/std:c++17 /DXP_WIN /Zc:preprocessor /utf-8",
- "$LDFLAGS mozjs-115.lib"
- };
- {win32, _} when SMVsn == "128" ->
+ {win32, _} when SMVsn == "102"; SMVsn == "115"; SMVsn == "128" ->
{
"/std:c++17 /DXP_WIN /Zc:preprocessor /utf-8",
- "$LDFLAGS mozjs-128.lib"
+ "$LDFLAGS mozjs-" ++ SMVsn ++ ".lib"
}
end.
@@ -273,12 +267,12 @@ end.
IcuIncludePath = case WithBrew of
false -> GenericIcuIncludePaths;
- true -> "-I" ++ string:strip(os:cmd(BrewIcuPrefixCmd), right, $\n) ++ "/include"
+ true -> "-I" ++ string:trim(os:cmd(BrewIcuPrefixCmd)) ++ "/include"
end.
IcuLibPath = case WithBrew of
false -> GenericIcuLibPaths;
- true -> "-L" ++ string:strip(os:cmd(BrewIcuPrefixCmd), right, $\n) ++ "/lib"
+ true -> "-L" ++ string:trim(os:cmd(BrewIcuPrefixCmd)) ++ "/lib"
end.
IcuEnv = [{"DRV_CFLAGS", "$DRV_CFLAGS -DPIC -O2 -fno-common"},
diff --git a/src/couch/src/couch_att.erl b/src/couch/src/couch_att.erl
index 5ca3927e7..c7e051a28 100644
--- a/src/couch/src/couch_att.erl
+++ b/src/couch/src/couch_att.erl
@@ -491,7 +491,7 @@ encoded_lengths_from_json(Props) ->
EncodedLen = Len;
EncodingValue ->
EncodedLen = couch_util:get_value(<<"encoded_length">>, Props, Len),
- Encoding = list_to_existing_atom(binary_to_list(EncodingValue))
+ Encoding = binary_to_existing_atom(EncodingValue)
end,
{Len, EncodedLen, Encoding}.
@@ -585,7 +585,7 @@ flush_data(Db, Fun, Att) when is_function(Fun) ->
end)
end;
flush_data(Db, {follows, Parser, Ref}, Att) ->
- ParserRef = erlang:monitor(process, Parser),
+ ParserRef = monitor(process, Parser),
Fun = fun() ->
Parser ! {get_bytes, Ref, self()},
receive
@@ -600,7 +600,7 @@ flush_data(Db, {follows, Parser, Ref}, Att) ->
try
flush_data(Db, Fun, store(data, Fun, Att))
after
- erlang:demonitor(ParserRef, [flush])
+ demonitor(ParserRef, [flush])
end;
flush_data(Db, {stream, StreamEngine}, Att) ->
case couch_db:is_active_stream(Db, StreamEngine) of
@@ -645,7 +645,7 @@ foldl(DataFun, Att, Fun, Acc) when is_function(DataFun) ->
Len = fetch(att_len, Att),
fold_streamed_data(DataFun, Len, Fun, Acc);
foldl({follows, Parser, Ref}, Att, Fun, Acc) ->
- ParserRef = erlang:monitor(process, Parser),
+ ParserRef = monitor(process, Parser),
DataFun = fun() ->
Parser ! {get_bytes, Ref, self()},
receive
@@ -660,7 +660,7 @@ foldl({follows, Parser, Ref}, Att, Fun, Acc) ->
try
foldl(DataFun, store(data, DataFun, Att), Fun, Acc)
after
- erlang:demonitor(ParserRef, [flush])
+ demonitor(ParserRef, [flush])
end.
range_foldl(Att, From, To, Fun, Acc) ->
@@ -781,7 +781,7 @@ open_stream(StreamSrc, Data) ->
true ->
StreamSrc(Data);
false ->
- erlang:error({invalid_stream_source, StreamSrc})
+ error({invalid_stream_source, StreamSrc})
end
end.
diff --git a/src/couch/src/couch_base32.erl b/src/couch/src/couch_base32.erl
index 776fe773d..03267ced0 100644
--- a/src/couch/src/couch_base32.erl
+++ b/src/couch/src/couch_base32.erl
@@ -150,7 +150,7 @@ decode(Encoded, ByteOffset, Acc) ->
find_in_set(Char) ->
case binary:match(?SET, Char) of
nomatch ->
- erlang:error(not_base32);
+ error(not_base32);
{Offset, _} ->
Offset
end.
diff --git a/src/couch/src/couch_bt_engine.erl b/src/couch/src/couch_bt_engine.erl
index ad84e0db8..8f99926ca 100644
--- a/src/couch/src/couch_bt_engine.erl
+++ b/src/couch/src/couch_bt_engine.erl
@@ -114,6 +114,19 @@
-include_lib("couch/include/couch_db.hrl").
-include("couch_bt_engine.hrl").
+% Commonly used header fields (used more than once in this module)
+-define(UPDATE_SEQ, update_seq).
+-define(SECURITY_PTR, security_ptr).
+-define(PROPS_PTR, props_ptr).
+-define(REVS_LIMIT, revs_limit).
+-define(PURGE_INFOS_LIMIT, purge_infos_limit).
+-define(COMPACTED_SEQ, compacted_seq).
+
+-define(DEFAULT_BTREE_CACHE_DEPTH, 3).
+% Priority is about how long the entry will survive in the cache initially. A
+% period is about 2 seconds and each period the value is halved.
+-define(HEADER_CACHE_PRIORITY, 16).
+
exists(FilePath) ->
case is_file(FilePath) of
true ->
@@ -196,14 +209,14 @@ handle_db_updater_info({'DOWN', Ref, _, _, _}, #st{fd_monitor = Ref} = St) ->
{stop, normal, St#st{fd = undefined, fd_monitor = closed}}.
incref(St) ->
- {ok, St#st{fd_monitor = erlang:monitor(process, St#st.fd)}}.
+ {ok, St#st{fd_monitor = monitor(process, St#st.fd)}}.
decref(St) ->
- true = erlang:demonitor(St#st.fd_monitor, [flush]),
+ true = demonitor(St#st.fd_monitor, [flush]),
ok.
monitored_by(St) ->
- case erlang:process_info(St#st.fd, monitored_by) of
+ case process_info(St#st.fd, monitored_by) of
{monitored_by, Pids} ->
lists:filter(fun is_pid/1, Pids);
_ ->
@@ -211,7 +224,7 @@ monitored_by(St) ->
end.
get_compacted_seq(#st{header = Header}) ->
- couch_bt_engine_header:get(Header, compacted_seq).
+ couch_bt_engine_header:get(Header, ?COMPACTED_SEQ).
get_del_doc_count(#st{} = St) ->
{ok, Reds} = couch_btree:full_reduce(St#st.id_tree),
@@ -242,10 +255,10 @@ get_oldest_purge_seq(#st{purge_seq_tree = PurgeSeqTree}) ->
PurgeSeq.
get_purge_infos_limit(#st{header = Header}) ->
- couch_bt_engine_header:get(Header, purge_infos_limit).
+ couch_bt_engine_header:get(Header, ?PURGE_INFOS_LIMIT).
get_revs_limit(#st{header = Header}) ->
- couch_bt_engine_header:get(Header, revs_limit).
+ couch_bt_engine_header:get(Header, ?REVS_LIMIT).
get_size_info(#st{} = St) ->
{ok, FileSize} = couch_file:bytes(St#st.fd),
@@ -305,26 +318,14 @@ get_partition_info(#st{} = St, Partition) ->
]}
].
-get_security(#st{header = Header} = St) ->
- case couch_bt_engine_header:get(Header, security_ptr) of
- undefined ->
- [];
- Pointer ->
- {ok, SecProps} = couch_file:pread_term(St#st.fd, Pointer),
- SecProps
- end.
+get_security(#st{} = St) ->
+ get_header_term(St, ?SECURITY_PTR, []).
-get_props(#st{header = Header} = St) ->
- case couch_bt_engine_header:get(Header, props_ptr) of
- undefined ->
- [];
- Pointer ->
- {ok, Props} = couch_file:pread_term(St#st.fd, Pointer),
- Props
- end.
+get_props(#st{} = St) ->
+ get_header_term(St, ?PROPS_PTR, []).
get_update_seq(#st{header = Header}) ->
- couch_bt_engine_header:get(Header, update_seq).
+ couch_bt_engine_header:get(Header, ?UPDATE_SEQ).
get_uuid(#st{header = Header}) ->
couch_bt_engine_header:get(Header, uuid).
@@ -332,7 +333,7 @@ get_uuid(#st{header = Header}) ->
set_revs_limit(#st{header = Header} = St, RevsLimit) ->
NewSt = St#st{
header = couch_bt_engine_header:set(Header, [
- {revs_limit, RevsLimit}
+ {?REVS_LIMIT, RevsLimit}
]),
needs_commit = true
},
@@ -341,33 +342,17 @@ set_revs_limit(#st{header = Header} = St, RevsLimit) ->
set_purge_infos_limit(#st{header = Header} = St, PurgeInfosLimit) ->
NewSt = St#st{
header = couch_bt_engine_header:set(Header, [
- {purge_infos_limit, PurgeInfosLimit}
+ {?PURGE_INFOS_LIMIT, PurgeInfosLimit}
]),
needs_commit = true
},
{ok, increment_update_seq(NewSt)}.
-set_security(#st{header = Header} = St, NewSecurity) ->
- Options = [{compression, St#st.compression}],
- {ok, Ptr, _} = couch_file:append_term(St#st.fd, NewSecurity, Options),
- NewSt = St#st{
- header = couch_bt_engine_header:set(Header, [
- {security_ptr, Ptr}
- ]),
- needs_commit = true
- },
- {ok, increment_update_seq(NewSt)}.
+set_security(#st{} = St, NewSecurity) ->
+ {ok, increment_update_seq(set_header_term(St, ?SECURITY_PTR, NewSecurity))}.
-set_props(#st{header = Header} = St, Props) ->
- Options = [{compression, St#st.compression}],
- {ok, Ptr, _} = couch_file:append_term(St#st.fd, Props, Options),
- NewSt = St#st{
- header = couch_bt_engine_header:set(Header, [
- {props_ptr, Ptr}
- ]),
- needs_commit = true
- },
- {ok, increment_update_seq(NewSt)}.
+set_props(#st{} = St, Props) ->
+ {ok, increment_update_seq(set_header_term(St, ?PROPS_PTR, Props))}.
open_docs(#st{} = St, DocIds) ->
Results = couch_btree:lookup(St#st.id_tree, DocIds),
@@ -480,14 +465,14 @@ write_doc_infos(#st{} = St, Pairs, LocalDocs) ->
NewUpdateSeq = lists:foldl(
fun(#full_doc_info{update_seq = Seq}, Acc) ->
- erlang:max(Seq, Acc)
+ max(Seq, Acc)
end,
get_update_seq(St),
Add
),
NewHeader = couch_bt_engine_header:set(St#st.header, [
- {update_seq, NewUpdateSeq}
+ {?UPDATE_SEQ, NewUpdateSeq}
]),
{ok, St#st{
@@ -509,7 +494,7 @@ purge_docs(#st{} = St, Pairs, PurgeInfos) ->
RemDocIds = [Old#full_doc_info.id || {Old, not_found} <- Pairs],
RemSeqs = [Old#full_doc_info.update_seq || {Old, _} <- Pairs],
DocsToAdd = [New || {_, New} <- Pairs, New /= not_found],
- CurrSeq = couch_bt_engine_header:get(St#st.header, update_seq),
+ CurrSeq = couch_bt_engine_header:get(St#st.header, ?UPDATE_SEQ),
Seqs = [FDI#full_doc_info.update_seq || FDI <- DocsToAdd],
NewSeq = lists:max([CurrSeq | Seqs]),
@@ -522,7 +507,7 @@ purge_docs(#st{} = St, Pairs, PurgeInfos) ->
false -> NewSeq
end,
Header = couch_bt_engine_header:set(St#st.header, [
- {update_seq, UpdateSeq}
+ {?UPDATE_SEQ, UpdateSeq}
]),
{ok, IdTree2} = couch_btree:add_remove(IdTree, DocsToAdd, RemDocIds),
@@ -562,9 +547,7 @@ commit_data(St) ->
case NewHeader /= OldHeader orelse NeedsCommit of
true ->
- couch_file:sync(Fd),
- ok = couch_file:write_header(Fd, NewHeader),
- couch_file:sync(Fd),
+ ok = couch_file:write_header(Fd, NewHeader, [sync]),
couch_stats:increment_counter([couchdb, commits]),
{ok, St#st{
header = NewHeader,
@@ -615,7 +598,7 @@ fold_purge_infos(St, StartSeq0, UserFun, UserAcc, Options) ->
% automatically.
if
MinSeq =< StartSeq -> ok;
- true -> erlang:error({invalid_start_purge_seq, StartSeq0, MinSeq})
+ true -> error({invalid_start_purge_seq, StartSeq0, MinSeq})
end,
Wrapper = fun(Info, _Reds, UAcc) ->
UserFun(Info, UAcc)
@@ -804,30 +787,16 @@ purge_tree_reduce(rereduce, Reds) ->
set_update_seq(#st{header = Header} = St, UpdateSeq) ->
{ok, St#st{
header = couch_bt_engine_header:set(Header, [
- {update_seq, UpdateSeq}
+ {?UPDATE_SEQ, UpdateSeq}
]),
needs_commit = true
}}.
-copy_security(#st{header = Header} = St, SecProps) ->
- Options = [{compression, St#st.compression}],
- {ok, Ptr, _} = couch_file:append_term(St#st.fd, SecProps, Options),
- {ok, St#st{
- header = couch_bt_engine_header:set(Header, [
- {security_ptr, Ptr}
- ]),
- needs_commit = true
- }}.
+copy_security(#st{} = St, SecProps) ->
+ {ok, set_header_term(St, ?SECURITY_PTR, SecProps)}.
-copy_props(#st{header = Header} = St, Props) ->
- Options = [{compression, St#st.compression}],
- {ok, Ptr, _} = couch_file:append_term(St#st.fd, Props, Options),
- {ok, St#st{
- header = couch_bt_engine_header:set(Header, [
- {props_ptr, Ptr}
- ]),
- needs_commit = true
- }}.
+copy_props(#st{} = St, Props) ->
+ {ok, set_header_term(St, ?PROPS_PTR, Props)}.
open_db_file(FilePath, Options) ->
case couch_file:open(FilePath, Options) of
@@ -864,7 +833,8 @@ init_state(FilePath, Fd, Header0, Options) ->
{split, fun ?MODULE:id_tree_split/1},
{join, fun ?MODULE:id_tree_join/2},
{reduce, fun ?MODULE:id_tree_reduce/2},
- {compression, Compression}
+ {compression, Compression},
+ {cache_depth, btree_cache_depth()}
]),
SeqTreeState = couch_bt_engine_header:seq_tree_state(Header),
@@ -872,28 +842,32 @@ init_state(FilePath, Fd, Header0, Options) ->
{split, fun ?MODULE:seq_tree_split/1},
{join, fun ?MODULE:seq_tree_join/2},
{reduce, fun ?MODULE:seq_tree_reduce/2},
- {compression, Compression}
+ {compression, Compression},
+ {cache_depth, btree_cache_depth()}
]),
LocalTreeState = couch_bt_engine_header:local_tree_state(Header),
{ok, LocalTree} = couch_btree:open(LocalTreeState, Fd, [
{split, fun ?MODULE:local_tree_split/1},
{join, fun ?MODULE:local_tree_join/2},
- {compression, Compression}
+ {compression, Compression},
+ {cache_depth, btree_cache_depth()}
]),
PurgeTreeState = couch_bt_engine_header:purge_tree_state(Header),
{ok, PurgeTree} = couch_btree:open(PurgeTreeState, Fd, [
{split, fun ?MODULE:purge_tree_split/1},
{join, fun ?MODULE:purge_tree_join/2},
- {reduce, fun ?MODULE:purge_tree_reduce/2}
+ {reduce, fun ?MODULE:purge_tree_reduce/2},
+ {cache_depth, btree_cache_depth()}
]),
PurgeSeqTreeState = couch_bt_engine_header:purge_seq_tree_state(Header),
{ok, PurgeSeqTree} = couch_btree:open(PurgeSeqTreeState, Fd, [
{split, fun ?MODULE:purge_seq_tree_split/1},
{join, fun ?MODULE:purge_seq_tree_join/2},
- {reduce, fun ?MODULE:purge_tree_reduce/2}
+ {reduce, fun ?MODULE:purge_tree_reduce/2},
+ {cache_depth, btree_cache_depth()}
]),
ok = couch_file:set_db_pid(Fd, self()),
@@ -901,7 +875,7 @@ init_state(FilePath, Fd, Header0, Options) ->
St = #st{
filepath = FilePath,
fd = Fd,
- fd_monitor = erlang:monitor(process, Fd),
+ fd_monitor = monitor(process, Fd),
header = Header,
needs_commit = false,
id_tree = IdTree,
@@ -933,22 +907,20 @@ update_header(St, Header) ->
]).
increment_update_seq(#st{header = Header} = St) ->
- UpdateSeq = couch_bt_engine_header:get(Header, update_seq),
+ UpdateSeq = couch_bt_engine_header:get(Header, ?UPDATE_SEQ),
St#st{
header = couch_bt_engine_header:set(Header, [
- {update_seq, UpdateSeq + 1}
+ {?UPDATE_SEQ, UpdateSeq + 1}
])
}.
set_default_security_object(Fd, Header, Compression, Options) ->
- case couch_bt_engine_header:get(Header, security_ptr) of
+ case couch_bt_engine_header:get(Header, ?SECURITY_PTR) of
Pointer when is_integer(Pointer) ->
Header;
_ ->
Default = couch_util:get_value(default_security_object, Options),
- AppendOpts = [{compression, Compression}],
- {ok, Ptr, _} = couch_file:append_term(Fd, Default, AppendOpts),
- couch_bt_engine_header:set(Header, security_ptr, Ptr)
+ set_header_term(Fd, Header, ?SECURITY_PTR, Default, Compression)
end.
% This function is here, and not in couch_bt_engine_header
@@ -1015,9 +987,7 @@ init_set_props(Fd, Header, Options) ->
Header;
InitialProps ->
Compression = couch_compress:get_compression_method(),
- AppendOpts = [{compression, Compression}],
- {ok, Ptr, _} = couch_file:append_term(Fd, InitialProps, AppendOpts),
- couch_bt_engine_header:set(Header, props_ptr, Ptr)
+ set_header_term(Fd, Header, ?PROPS_PTR, InitialProps, Compression)
end.
delete_compaction_files(FilePath) ->
@@ -1190,9 +1160,9 @@ finish_compaction_int(#st{} = OldSt, #st{} = NewSt1) ->
{ok, NewSt2} = commit_data(NewSt1#st{
header = couch_bt_engine_header:set(Header, [
- {compacted_seq, get_update_seq(OldSt)},
- {revs_limit, get_revs_limit(OldSt)},
- {purge_infos_limit, get_purge_infos_limit(OldSt)}
+ {?COMPACTED_SEQ, get_update_seq(OldSt)},
+ {?REVS_LIMIT, get_revs_limit(OldSt)},
+ {?PURGE_INFOS_LIMIT, get_purge_infos_limit(OldSt)}
]),
local_tree = NewLocal2
}),
@@ -1229,3 +1199,44 @@ is_file(Path) ->
{ok, #file_info{type = directory}} -> true;
_ -> false
end.
+
+get_header_term(#st{header = Header} = St, Key, Default) when is_atom(Key) ->
+ case couch_bt_engine_header:get(Header, Key) of
+ undefined ->
+ Default;
+ Pointer when is_integer(Pointer) ->
+ case couch_bt_engine_cache:lookup({St#st.fd, Pointer}) of
+ undefined ->
+ {ok, Term} = couch_file:pread_term(St#st.fd, Pointer),
+ couch_bt_engine_cache:insert({St#st.fd, Pointer}, Term, ?HEADER_CACHE_PRIORITY),
+ Term;
+ Term ->
+ Term
+ end
+ end.
+
+set_header_term(#st{} = St, Key, Term) when is_atom(Key) ->
+ #st{fd = Fd, header = Header, compression = Compression} = St,
+ St#st{
+ header = set_header_term(Fd, Header, Key, Term, Compression),
+ needs_commit = true
+ }.
+
+set_header_term(Fd, Header, Key, Term, Compression) when is_atom(Key) ->
+ case couch_bt_engine_header:get(Header, Key) of
+ Pointer when is_integer(Pointer) ->
+ % Reset old one to 0 usage. Some old snapshot may still
+ % see it and use. But it will only survive only one more
+ % interval at most otherwise
+ couch_bt_engine_cache:reset({Fd, Pointer});
+ _ ->
+ ok
+ end,
+ TermOpts = [{compression, Compression}],
+ {ok, Ptr, _} = couch_file:append_term(Fd, Term, TermOpts),
+ Result = couch_bt_engine_header:set(Header, Key, Ptr),
+ couch_bt_engine_cache:insert({Fd, Ptr}, Term, ?HEADER_CACHE_PRIORITY),
+ Result.
+
+btree_cache_depth() ->
+ config:get_integer("bt_engine_cache", "db_btree_cache_depth", ?DEFAULT_BTREE_CACHE_DEPTH).
diff --git a/src/couch/src/couch_bt_engine_cache.erl b/src/couch/src/couch_bt_engine_cache.erl
new file mode 100644
index 000000000..a39564957
--- /dev/null
+++ b/src/couch/src/couch_bt_engine_cache.erl
@@ -0,0 +1,292 @@
+% Licensed under the Apache License, Version 2.0 (the "License"); you may not
+% use this file except in compliance with the License. You may obtain a copy of
+% the License at
+%
+% http://www.apache.org/licenses/LICENSE-2.0
+%
+% Unless required by applicable law or agreed to in writing, software
+% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+% License for the specific language governing permissions and limitations under
+% the License.
+
+-module(couch_bt_engine_cache).
+
+-include_lib("stdlib/include/ms_transform.hrl").
+
+% Main API
+%
+-export([
+ insert/2,
+ insert/3,
+ reset/1,
+ lookup/1,
+ info/0,
+ tables/0
+]).
+
+% Supervision and start API
+%
+-export([
+ create_tables/0,
+ sup_children/0,
+ start_link/1,
+ init/1
+]).
+
+-define(DEFAULT_SIZE, 67108864).
+-define(DEFAULT_LEAVE_PERCENT, 30).
+-define(INTERVAL_MSEC, 3000).
+% How often cleaners check if the ets size increases. This is used in cases
+% when initially, at the start the cleaning interval, ets table size is below
+% "leave percent". Then we skip cleaning all the 0 usage entries. However, if a
+% new set of requests come in soon after, but before the next clean-up interval
+% they'll fail since the cache would be full. To be able to react quicker and
+% make room, cleaners poll table sizes a bit more often.
+-define(CLEANUP_INTERVAL_MSEC, 100).
+% 1 bsl 58, power of 2 that's still an immediate integer
+-define(MAX_PRIORITY, 288230376151711744).
+-define(PTERM_KEY, {?MODULE, caches}).
+% Metrics
+-define(HITS, hits).
+-define(MISSES, misses).
+-define(FULL, full).
+
+-record(cache, {tid, max_size}).
+
+% Main API
+
+insert(Key, Term) ->
+ insert(Key, Term, 1).
+
+insert(Key, Term, Priority) when is_integer(Priority) ->
+ Priority1 = min(?MAX_PRIORITY, max(0, Priority)),
+ case get_cache(Key) of
+ #cache{tid = Tid, max_size = Max} ->
+ case ets:info(Tid, memory) < Max of
+ true ->
+ case ets:insert_new(Tid, {Key, Priority1, Term}) of
+ true ->
+ true;
+ false ->
+ bump_usage(Tid, Key),
+ false
+ end;
+ false ->
+ bump_metric(?FULL),
+ false
+ end;
+ undefined ->
+ false
+ end.
+
+reset(Key) ->
+ case get_cache(Key) of
+ #cache{tid = Tid} -> reset_usage(Tid, Key);
+ undefined -> true
+ end.
+
+lookup(Key) ->
+ case get_cache(Key) of
+ #cache{tid = Tid} ->
+ case ets:lookup_element(Tid, Key, 3, undefined) of
+ undefined ->
+ bump_metric(?MISSES),
+ undefined;
+ Term ->
+ bump_usage(Tid, Key),
+ bump_metric(?HITS),
+ Term
+ end;
+ undefined ->
+ undefined
+ end.
+
+info() ->
+ case persistent_term:get(?PTERM_KEY, undefined) of
+ Caches when is_tuple(Caches) ->
+ SizeMem = [info(C) || C <- tuple_to_list(Caches)],
+ MaxMem = [Max || #cache{max_size = Max} <- tuple_to_list(Caches)],
+ {Sizes, Mem} = lists:unzip(SizeMem),
+ #{
+ size => lists:sum(Sizes),
+ memory => lists:sum(Mem),
+ max_memory => lists:sum(MaxMem) * wordsize(),
+ full => sample_metric(?FULL),
+ hits => sample_metric(?HITS),
+ misses => sample_metric(?MISSES),
+ shard_count => shard_count()
+ };
+ undefined ->
+ #{}
+ end.
+
+tables() ->
+ case persistent_term:get(?PTERM_KEY, undefined) of
+ Caches when is_tuple(Caches) ->
+ [Tid || #cache{tid = Tid} <- tuple_to_list(Caches)];
+ undefined ->
+ []
+ end.
+
+% Supervisor helper functions
+
+create_tables() ->
+ BtCaches = [new() || _ <- lists:seq(1, shard_count())],
+ persistent_term:put(?PTERM_KEY, list_to_tuple(BtCaches)).
+
+sup_children() ->
+ [sup_child(I) || I <- lists:seq(1, shard_count())].
+
+sup_child(N) ->
+ Name = list_to_atom("couch_bt_engine_cache_" ++ integer_to_list(N)),
+ #{id => Name, start => {?MODULE, start_link, [N]}, shutdown => brutal_kill}.
+
+% Process start and main loop
+
+start_link(N) when is_integer(N) ->
+ {ok, proc_lib:spawn_link(?MODULE, init, [N])}.
+
+init(N) ->
+ Caches = persistent_term:get(?PTERM_KEY),
+ Cache = #cache{tid = Tid} = element(N, Caches),
+ ets:delete_all_objects(Tid),
+ loop(Cache).
+
+loop(#cache{tid = Tid} = Cache) ->
+ decay(Tid),
+ Next = now_msec() + wait_interval(?INTERVAL_MSEC),
+ clean(Cache, Next - ?CLEANUP_INTERVAL_MSEC),
+ remove_dead(Cache),
+ WaitLeft = max(10, Next - now_msec()),
+ timer:sleep(WaitLeft),
+ loop(Cache).
+
+% Clean unused procs. If we haven't cleaned any keep polling at a higher
+% rate so we react quicker if a new set of entries are added.
+%
+clean(#cache{tid = Tid} = Cache, Until) ->
+ case now_msec() < Until of
+ true ->
+ case should_clean(Cache) of
+ true ->
+ ets:match_delete(Tid, {'_', 0, '_'});
+ false ->
+ timer:sleep(wait_interval(?CLEANUP_INTERVAL_MSEC)),
+ clean(Cache, Until)
+ end;
+ false ->
+ false
+ end.
+
+should_clean(#cache{tid = Tid, max_size = Max}) ->
+ ets:info(Tid, memory) >= Max * leave_percent() / 100.
+
+remove_dead(#cache{tid = Tid}) ->
+ All = pids(Tid),
+ Alive = sets:filter(fun is_process_alive/1, All),
+ Dead = sets:subtract(All, Alive),
+ % In OTP 27+ use sets:map/2
+ Fun = fun(Pid, _) -> ets:match_delete(Tid, {{Pid, '_'}, '_', '_'}) end,
+ sets:fold(Fun, true, Dead).
+
+pids(Tid) ->
+ Acc = couch_util:new_set(),
+ try
+ ets:foldl(fun pids_fold/2, Acc, Tid)
+ catch
+ error:badarg -> Acc
+ end.
+
+pids_fold({{Pid, _}, _, _}, Acc) when is_pid(Pid) ->
+ sets:add_element(Pid, Acc);
+pids_fold({_, _, _}, Acc) ->
+ Acc.
+
+new() ->
+ Opts = [public, {write_concurrency, true}, {read_concurrency, true}],
+ Max0 = round(max_size() / wordsize() / shard_count()),
+ % Some per-table overhead for the table metadata
+ Max = Max0 + round(250 * 1024 / wordsize()),
+ #cache{tid = ets:new(?MODULE, Opts), max_size = Max}.
+
+get_cache(Term) ->
+ case persistent_term:get(?PTERM_KEY, undefined) of
+ Caches when is_tuple(Caches) ->
+ Index = erlang:phash2(Term, tuple_size(Caches)),
+ #cache{} = element(1 + Index, Caches);
+ undefined ->
+ undefined
+ end.
+
+bump_usage(Tid, Key) ->
+ % We're updating the second field incrementing it by 1 and clamping it
+ % at ?MAX_PRIORITY. We don't set the default for the update_counter
+ % specifically to avoid creating bogus entries just from updating the
+ % counter, so expect the error:badarg here sometimes.
+ UpdateOp = {2, 1, ?MAX_PRIORITY, ?MAX_PRIORITY},
+ try
+ ets:update_counter(Tid, Key, UpdateOp)
+ catch
+ error:badarg -> ok
+ end.
+
+reset_usage(Tid, Key) ->
+ % Reset the value of the usage to 0. Since max value is ?MAX_PRIORITY,
+ % subtract that and clamp it at 0. Do not provide a default since if an
+ % entry is missing we don't want to create a bogus one from this operation.
+ UpdateOp = {2, -?MAX_PRIORITY, 0, 0},
+ try
+ ets:update_counter(Tid, Key, UpdateOp)
+ catch
+ error:badarg -> ok
+ end.
+
+info(#cache{tid = Tid}) ->
+ Memory = ets:info(Tid, memory) * wordsize(),
+ Size = ets:info(Tid, size),
+ {Size, Memory}.
+
+decay(Tid) ->
+ MatchSpec = ets:fun2ms(
+ fun({Key, Usage, Term}) when Usage > 0 ->
+ {Key, Usage bsr 1, Term}
+ end
+ ),
+ ets:select_replace(Tid, MatchSpec).
+
+shard_count() ->
+ % Use a minimum size of 16 even for there are less than 16 schedulers
+ % to keep the total tables size a bit smaller
+ max(16, erlang:system_info(schedulers)).
+
+wait_interval(Interval) ->
+ Jitter = rand:uniform(max(1, Interval bsr 1)),
+ Interval + Jitter.
+
+max_size() ->
+ config:get_integer("bt_engine_cache", "max_size", ?DEFAULT_SIZE).
+
+leave_percent() ->
+ Val = config:get_integer("bt_engine_cache", "leave_percent", ?DEFAULT_LEAVE_PERCENT),
+ max(0, min(90, Val)).
+
+now_msec() ->
+ erlang:monotonic_time(millisecond).
+
+bump_metric(Metric) when is_atom(Metric) ->
+ couch_stats:increment_counter([couchdb, bt_engine_cache, Metric]).
+
+sample_metric(Metric) when is_atom(Metric) ->
+ try
+ couch_stats:sample([couchdb, bt_engine_cache, Metric])
+ catch
+ throw:unknown_metric ->
+ 0
+ end.
+
+% ETS sizes are expressed in "words". To get the byte size need to multiply
+% memory sizes by the wordsize. On 64 bit systems this should be 8
+%
+wordsize() ->
+ erlang:system_info(wordsize).
diff --git a/src/couch/src/couch_bt_engine_compactor.erl b/src/couch/src/couch_bt_engine_compactor.erl
index 8ed55b5c3..37295cb16 100644
--- a/src/couch/src/couch_bt_engine_compactor.erl
+++ b/src/couch/src/couch_bt_engine_compactor.erl
@@ -147,7 +147,7 @@ open_compaction_files(DbName, OldSt, Options) ->
}
end,
unlink(DataFd),
- erlang:monitor(process, MetaFd),
+ monitor(process, MetaFd),
{ok, CompSt}.
copy_purge_info(#comp_st{} = CompSt) ->
@@ -381,7 +381,7 @@ copy_compact(#comp_st{} = CompSt) ->
% Copy general properties over
Props = couch_bt_engine:get_props(St),
- {ok, NewSt5} = couch_bt_engine:set_props(NewSt4, Props),
+ {ok, NewSt5} = couch_bt_engine:copy_props(NewSt4, Props),
FinalUpdateSeq = couch_bt_engine:get_update_seq(St),
{ok, NewSt6} = couch_bt_engine:set_update_seq(NewSt5, FinalUpdateSeq),
@@ -693,7 +693,7 @@ merge_lookups([#doc_info{} = DI | RestInfos], [{ok, FDI} | RestLookups]) ->
% Assert we've matched our lookups
if
DI#doc_info.id == FDI#full_doc_info.id -> ok;
- true -> erlang:error({mismatched_doc_infos, DI#doc_info.id})
+ true -> error({mismatched_doc_infos, DI#doc_info.id})
end,
[FDI | merge_lookups(RestInfos, RestLookups)];
merge_lookups([FDI | RestInfos], Lookups) ->
diff --git a/src/couch/src/couch_bt_engine_header.erl b/src/couch/src/couch_bt_engine_header.erl
index 3581b1e39..e6e211de3 100644
--- a/src/couch/src/couch_bt_engine_header.erl
+++ b/src/couch/src/couch_bt_engine_header.erl
@@ -204,20 +204,19 @@ upgrade_tuple(Old) when is_record(Old, db_header) ->
Old;
upgrade_tuple(Old) when is_tuple(Old) ->
NewSize = record_info(size, db_header),
- if
- tuple_size(Old) < NewSize -> ok;
- true -> erlang:error({invalid_header_size, Old})
- end,
- {_, New} = lists:foldl(
- fun(Val, {Idx, Hdr}) ->
- {Idx + 1, setelement(Idx, Hdr, Val)}
+ Upgrade = tuple_size(Old) < NewSize,
+ ProhibitDowngrade = config:get_boolean("couchdb", "prohibit_downgrade", true),
+ OldKVs =
+ case {Upgrade, ProhibitDowngrade} of
+ {true, AnyBool} when is_boolean(AnyBool) -> tuple_to_list(Old);
+ {false, true} -> error({invalid_header_size, Old});
+ {false, false} -> lists:sublist(tuple_to_list(Old), NewSize)
end,
- {1, #db_header{}},
- tuple_to_list(Old)
- ),
+ FoldFun = fun(Val, {Idx, Hdr}) -> {Idx + 1, setelement(Idx, Hdr, Val)} end,
+ {_, New} = lists:foldl(FoldFun, {1, #db_header{}}, OldKVs),
if
is_record(New, db_header) -> ok;
- true -> erlang:error({invalid_header_extension, {Old, New}})
+ true -> error({invalid_header_extension, {Old, New}})
end,
New.
@@ -338,7 +337,7 @@ latest(_Else) ->
undefined.
-ifdef(TEST).
--include_lib("eunit/include/eunit.hrl").
+-include_lib("couch/include/couch_eunit.hrl").
mk_header(Vsn) ->
{
@@ -478,4 +477,61 @@ get_epochs_from_old_header_test() ->
Vsn5Header = mk_header(5),
?assertEqual(undefined, epochs(Vsn5Header)).
+tuple_uprade_test_() ->
+ {
+ foreach,
+ fun() ->
+ Ctx = test_util:start_couch(),
+ config:set("couchdb", "prohibit_downgrade", "true", false),
+ Ctx
+ end,
+ fun(Ctx) ->
+ config:delete("couchdb", "prohibit_downgrade", false),
+ test_util:stop_couch(Ctx)
+ end,
+ [
+ ?TDEF_FE(t_upgrade_tuple_same_size),
+ ?TDEF_FE(t_upgrade_tuple),
+ ?TDEF_FE(t_downgrade_default),
+ ?TDEF_FE(t_downgrade_allowed)
+ ]
+ }.
+
+t_upgrade_tuple_same_size(_) ->
+ Hdr = #db_header{disk_version = ?LATEST_DISK_VERSION},
+ Hdr1 = upgrade_tuple(Hdr),
+ ?assertEqual(Hdr, Hdr1).
+
+t_upgrade_tuple(_) ->
+ Hdr = {db_header, ?LATEST_DISK_VERSION, 101},
+ Hdr1 = upgrade_tuple(Hdr),
+ ?assertMatch(
+ #db_header{
+ disk_version = ?LATEST_DISK_VERSION,
+ update_seq = 101,
+ purge_infos_limit = 1000
+ },
+ Hdr1
+ ).
+
+t_downgrade_default(_) ->
+ Junk = lists:duplicate(50, x),
+ Hdr = list_to_tuple([db_header, ?LATEST_DISK_VERSION] ++ Junk),
+ % Not allowed by default
+ ?assertError({invalid_header_size, _}, upgrade_tuple(Hdr)).
+
+t_downgrade_allowed(_) ->
+ Junk = lists:duplicate(50, x),
+ Hdr = list_to_tuple([db_header, ?LATEST_DISK_VERSION, 42] ++ Junk),
+ config:set("couchdb", "prohibit_downgrade", "false", false),
+ Hdr1 = upgrade_tuple(Hdr),
+ ?assert(is_record(Hdr1, db_header)),
+ ?assertMatch(
+ #db_header{
+ disk_version = ?LATEST_DISK_VERSION,
+ update_seq = 42
+ },
+ Hdr1
+ ).
+
-endif.
diff --git a/src/couch/src/couch_btree.erl b/src/couch/src/couch_btree.erl
index b974a22ee..1519b1fbc 100644
--- a/src/couch/src/couch_btree.erl
+++ b/src/couch/src/couch_btree.erl
@@ -14,11 +14,30 @@
-export([open/2, open/3, query_modify/4, add/2, add_remove/3]).
-export([fold/4, full_reduce/1, final_reduce/2, size/1, foldl/3, foldl/4]).
--export([fold_reduce/4, lookup/2, get_state/1, set_options/2]).
+-export([fold_reduce/4, lookup/2, set_options/2]).
+-export([is_btree/1, get_state/1, get_fd/1, get_reduce_fun/1]).
-export([extract/2, assemble/3, less/3]).
-include_lib("couch/include/couch_db.hrl").
+-define(DEFAULT_CHUNK_SIZE, 1279).
+
+% For the btree cache, the priority of the root node will be
+% this value. The priority is roughly how many cleanup interval
+% (second) they'll survive without any updates in the cache
+-define(ROOT_NODE_CACHE_PRIORITY, 8).
+
+-record(btree, {
+ fd,
+ root,
+ extract_kv,
+ assemble_kv,
+ less,
+ reduce = nil,
+ compression = ?DEFAULT_COMPRESSION,
+ cache_depth = 0
+}).
+
-define(FILL_RATIO, 0.5).
extract(#btree{extract_kv = undefined}, Value) ->
@@ -31,11 +50,18 @@ assemble(#btree{assemble_kv = undefined}, Key, Value) ->
assemble(#btree{assemble_kv = Assemble}, Key, Value) ->
Assemble(Key, Value).
+-compile({inline, [less/3]}).
less(#btree{less = undefined}, A, B) ->
A < B;
less(#btree{less = Less}, A, B) ->
Less(A, B).
+-compile({inline, [less_eq/3]}).
+less_eq(#btree{less = undefined}, A, B) ->
+ A =< B;
+less_eq(#btree{less = Less}, A, B) ->
+ Less(A, B) orelse not Less(B, A).
+
% pass in 'nil' for State if a new Btree.
open(State, Fd) ->
{ok, #btree{root = State, fd = Fd}}.
@@ -51,14 +77,27 @@ set_options(Bt, [{less, Less} | Rest]) ->
set_options(Bt, [{reduce, Reduce} | Rest]) ->
set_options(Bt#btree{reduce = Reduce}, Rest);
set_options(Bt, [{compression, Comp} | Rest]) ->
- set_options(Bt#btree{compression = Comp}, Rest).
+ set_options(Bt#btree{compression = Comp}, Rest);
+set_options(Bt, [{cache_depth, Depth} | Rest]) when is_integer(Depth) ->
+ set_options(Bt#btree{cache_depth = Depth}, Rest).
open(State, Fd, Options) ->
{ok, set_options(#btree{root = State, fd = Fd}, Options)}.
+is_btree(#btree{}) ->
+ true;
+is_btree(_) ->
+ false.
+
get_state(#btree{root = Root}) ->
Root.
+get_fd(#btree{fd = Fd}) ->
+ Fd.
+
+get_reduce_fun(#btree{reduce = Reduce}) ->
+ Reduce.
+
final_reduce(#btree{reduce = Reduce}, Val) ->
final_reduce(Reduce, Val);
final_reduce(Reduce, {[], []}) ->
@@ -89,7 +128,8 @@ fold_reduce(#btree{root = Root} = Bt, Fun, Acc, Options) ->
[],
KeyGroupFun,
Fun,
- Acc
+ Acc,
+ 0
),
if
GroupedKey2 == undefined ->
@@ -236,7 +276,8 @@ fold(#btree{root = Root} = Bt, Fun, Acc, Options) ->
InRange,
Dir,
convert_fun_arity(Fun),
- Acc
+ Acc,
+ 0
);
StartKey ->
stream_node(
@@ -247,7 +288,8 @@ fold(#btree{root = Root} = Bt, Fun, Acc, Options) ->
InRange,
Dir,
convert_fun_arity(Fun),
- Acc
+ Acc,
+ 0
)
end,
case Result of
@@ -276,6 +318,11 @@ query_modify(Bt, LookupKeys, InsertValues, RemoveKeys) ->
),
RemoveActions = [{remove, Key, nil} || Key <- RemoveKeys],
FetchActions = [{fetch, Key, nil} || Key <- LookupKeys],
+
+ UniqueFun = fun({Op, A, _}, {Op, B, _}) -> less_eq(Bt, A, B) end,
+ InsertActions1 = lists:usort(UniqueFun, InsertActions),
+ RemoveActions1 = lists:usort(UniqueFun, RemoveActions),
+
SortFun =
fun({OpA, A, _}, {OpB, B, _}) ->
case A == B of
@@ -284,8 +331,8 @@ query_modify(Bt, LookupKeys, InsertValues, RemoveKeys) ->
false -> less(Bt, A, B)
end
end,
- Actions = lists:sort(SortFun, lists:append([InsertActions, RemoveActions, FetchActions])),
- {ok, KeyPointers, QueryResults} = modify_node(Bt, Root, Actions, []),
+ Actions = lists:sort(SortFun, lists:append([InsertActions1, RemoveActions1, FetchActions])),
+ {ok, KeyPointers, QueryResults} = modify_node(Bt, Root, Actions, [], 0),
{ok, NewRoot} = complete_root(Bt, KeyPointers),
{ok, QueryResults, Bt#btree{root = NewRoot}}.
@@ -301,64 +348,87 @@ lookup(#btree{root = Root, less = Less} = Bt, Keys) ->
undefined -> lists:sort(Keys);
_ -> lists:sort(Less, Keys)
end,
- {ok, SortedResults} = lookup(Bt, Root, SortedKeys),
+ {ok, SortedResults} = lookup(Bt, Root, SortedKeys, 0),
% We want to return the results in the same order as the keys were input
% but we may have changed the order when we sorted. So we need to put the
% order back into the results.
couch_util:reorder_results(Keys, SortedResults).
-lookup(_Bt, nil, Keys) ->
+lookup(_Bt, nil, Keys, _Depth) ->
{ok, [{Key, not_found} || Key <- Keys]};
-lookup(Bt, Node, Keys) ->
+lookup(Bt, Node, Keys, Depth0) ->
+ Depth = Depth0 + 1,
Pointer = element(1, Node),
- {NodeType, NodeList} = get_node(Bt, Pointer),
+ {NodeType, NodeList} = get_node(Bt, Pointer, Depth),
case NodeType of
kp_node ->
- lookup_kpnode(Bt, list_to_tuple(NodeList), 1, Keys, []);
+ lookup_kpnode(Bt, list_to_tuple(NodeList), 1, Keys, [], Depth);
kv_node ->
- lookup_kvnode(Bt, list_to_tuple(NodeList), 1, Keys, [])
+ lookup_kvnode(Bt, list_to_tuple(NodeList), 1, Keys, [], Depth)
end.
-lookup_kpnode(_Bt, _NodeTuple, _LowerBound, [], Output) ->
+lookup_kpnode(_Bt, _NodeTuple, _LowerBound, [], Output, _Depth) ->
{ok, lists:reverse(Output)};
-lookup_kpnode(_Bt, NodeTuple, LowerBound, Keys, Output) when tuple_size(NodeTuple) < LowerBound ->
+lookup_kpnode(_Bt, NodeTuple, LowerBound, Keys, Output, _Depth) when
+ tuple_size(NodeTuple) < LowerBound
+->
{ok, lists:reverse(Output, [{Key, not_found} || Key <- Keys])};
-lookup_kpnode(Bt, NodeTuple, LowerBound, [FirstLookupKey | _] = LookupKeys, Output) ->
+lookup_kpnode(Bt, NodeTuple, LowerBound, [FirstLookupKey | _] = LookupKeys, Output, Depth) ->
N = find_first_gteq(Bt, NodeTuple, LowerBound, tuple_size(NodeTuple), FirstLookupKey),
{Key, PointerInfo} = element(N, NodeTuple),
SplitFun = fun(LookupKey) -> not less(Bt, Key, LookupKey) end,
case lists:splitwith(SplitFun, LookupKeys) of
{[], GreaterQueries} ->
- lookup_kpnode(Bt, NodeTuple, N + 1, GreaterQueries, Output);
+ lookup_kpnode(Bt, NodeTuple, N + 1, GreaterQueries, Output, Depth);
{LessEqQueries, GreaterQueries} ->
- {ok, Results} = lookup(Bt, PointerInfo, LessEqQueries),
- lookup_kpnode(Bt, NodeTuple, N + 1, GreaterQueries, lists:reverse(Results, Output))
+ {ok, Results} = lookup(Bt, PointerInfo, LessEqQueries, Depth),
+ lookup_kpnode(
+ Bt, NodeTuple, N + 1, GreaterQueries, lists:reverse(Results, Output), Depth
+ )
end.
-lookup_kvnode(_Bt, _NodeTuple, _LowerBound, [], Output) ->
+lookup_kvnode(_Bt, _NodeTuple, _LowerBound, [], Output, _Depth) ->
{ok, lists:reverse(Output)};
-lookup_kvnode(_Bt, NodeTuple, LowerBound, Keys, Output) when tuple_size(NodeTuple) < LowerBound ->
+lookup_kvnode(_Bt, NodeTuple, LowerBound, Keys, Output, _Depth) when
+ tuple_size(NodeTuple) < LowerBound
+->
% keys not found
{ok, lists:reverse(Output, [{Key, not_found} || Key <- Keys])};
-lookup_kvnode(Bt, NodeTuple, LowerBound, [LookupKey | RestLookupKeys], Output) ->
+lookup_kvnode(Bt, NodeTuple, LowerBound, [LookupKey | RestLookupKeys], Output, Depth) ->
N = find_first_gteq(Bt, NodeTuple, LowerBound, tuple_size(NodeTuple), LookupKey),
{Key, Value} = element(N, NodeTuple),
case less(Bt, LookupKey, Key) of
true ->
% LookupKey is less than Key
- lookup_kvnode(Bt, NodeTuple, N, RestLookupKeys, [{LookupKey, not_found} | Output]);
+ lookup_kvnode(
+ Bt, NodeTuple, N, RestLookupKeys, [{LookupKey, not_found} | Output], Depth
+ );
false ->
case less(Bt, Key, LookupKey) of
true ->
% LookupKey is greater than Key
- lookup_kvnode(Bt, NodeTuple, N + 1, RestLookupKeys, [
- {LookupKey, not_found} | Output
- ]);
+ lookup_kvnode(
+ Bt,
+ NodeTuple,
+ N + 1,
+ RestLookupKeys,
+ [
+ {LookupKey, not_found} | Output
+ ],
+ Depth
+ );
false ->
% LookupKey is equal to Key
- lookup_kvnode(Bt, NodeTuple, N, RestLookupKeys, [
- {LookupKey, {ok, assemble(Bt, LookupKey, Value)}} | Output
- ])
+ lookup_kvnode(
+ Bt,
+ NodeTuple,
+ N,
+ RestLookupKeys,
+ [
+ {LookupKey, {ok, assemble(Bt, LookupKey, Value)}} | Output
+ ],
+ Depth
+ )
end
end.
@@ -407,32 +477,29 @@ chunkify([InElement | RestInList], ChunkThreshold, OutList, OutListSize, OutputC
-compile({inline, [get_chunk_size/0]}).
get_chunk_size() ->
- try
- list_to_integer(config:get("couchdb", "btree_chunk_size", "1279"))
- catch
- error:badarg ->
- 1279
- end.
+ config:get_integer("couchdb", "btree_chunk_size", ?DEFAULT_CHUNK_SIZE).
-modify_node(Bt, RootPointerInfo, Actions, QueryOutput) ->
+modify_node(Bt, RootPointerInfo, Actions, QueryOutput, Depth0) ->
+ Depth = Depth0 + 1,
{NodeType, NodeList} =
case RootPointerInfo of
nil ->
{kv_node, []};
_Tuple ->
Pointer = element(1, RootPointerInfo),
- get_node(Bt, Pointer)
+ get_node(Bt, Pointer, Depth)
end,
NodeTuple = list_to_tuple(NodeList),
{ok, NewNodeList, QueryOutput2} =
case NodeType of
- kp_node -> modify_kpnode(Bt, NodeTuple, 1, Actions, [], QueryOutput);
- kv_node -> modify_kvnode(Bt, NodeTuple, 1, Actions, [], QueryOutput)
+ kp_node -> modify_kpnode(Bt, NodeTuple, 1, Actions, [], QueryOutput, Depth);
+ kv_node -> modify_kvnode(Bt, NodeTuple, 1, Actions, [], QueryOutput, Depth)
end,
case NewNodeList of
% no nodes remain
[] ->
+ reset_cache_usage(Bt, RootPointerInfo, Depth),
{ok, [], QueryOutput2};
% nothing changed
NodeList ->
@@ -444,6 +511,7 @@ modify_node(Bt, RootPointerInfo, Actions, QueryOutput) ->
nil ->
write_node(Bt, NodeType, NewNodeList);
_ ->
+ reset_cache_usage(Bt, RootPointerInfo, Depth),
{LastKey, _LastValue} = element(tuple_size(NodeTuple), NodeTuple),
OldNode = {LastKey, RootPointerInfo},
write_node(Bt, OldNode, NodeType, NodeList, NewNodeList)
@@ -470,7 +538,30 @@ reduce_tree_size(kp_node, _NodeSize, [{_K, {_P, _Red, nil}} | _]) ->
reduce_tree_size(kp_node, NodeSize, [{_K, {_P, _Red, Sz}} | NodeList]) ->
reduce_tree_size(kp_node, NodeSize + Sz, NodeList).
-get_node(#btree{fd = Fd}, NodePos) ->
+reset_cache_usage(_, nil, _Depth) ->
+ ok;
+reset_cache_usage(#btree{cache_depth = Max}, _, Depth) when Depth > Max ->
+ ok;
+reset_cache_usage(#btree{fd = Fd}, RootPointerInfo, _Depth) ->
+ Pointer = element(1, RootPointerInfo),
+ couch_bt_engine_cache:reset({Fd, Pointer}).
+
+get_node(#btree{fd = Fd, cache_depth = Max}, NodePos, Depth) when Depth =< Max ->
+ case couch_bt_engine_cache:lookup({Fd, NodePos}) of
+ undefined ->
+ {ok, {NodeType, NodeList}} = couch_file:pread_term(Fd, NodePos),
+ case NodeType of
+ kp_node ->
+ Priority = max(1, ?ROOT_NODE_CACHE_PRIORITY - Depth),
+ couch_bt_engine_cache:insert({Fd, NodePos}, NodeList, Priority);
+ kv_node ->
+ ok
+ end,
+ {NodeType, NodeList};
+ NodeList ->
+ {kp_node, NodeList}
+ end;
+get_node(#btree{fd = Fd}, NodePos, _Depth) ->
{ok, {NodeType, NodeList}} = couch_file:pread_term(Fd, NodePos),
{NodeType, NodeList}.
@@ -546,9 +637,9 @@ old_list_is_prefix([KV | Rest1], [KV | Rest2], Acc) ->
old_list_is_prefix(_OldList, _NewList, _Acc) ->
false.
-modify_kpnode(Bt, {}, _LowerBound, Actions, [], QueryOutput) ->
- modify_node(Bt, nil, Actions, QueryOutput);
-modify_kpnode(_Bt, NodeTuple, LowerBound, [], ResultNode, QueryOutput) ->
+modify_kpnode(Bt, {}, _LowerBound, Actions, [], QueryOutput, Depth) ->
+ modify_node(Bt, nil, Actions, QueryOutput, Depth);
+modify_kpnode(_Bt, NodeTuple, LowerBound, [], ResultNode, QueryOutput, _Depth) ->
{ok,
lists:reverse(
ResultNode,
@@ -566,7 +657,8 @@ modify_kpnode(
LowerBound,
[{_, FirstActionKey, _} | _] = Actions,
ResultNode,
- QueryOutput
+ QueryOutput,
+ Depth
) ->
Sz = tuple_size(NodeTuple),
N = find_first_gteq(Bt, NodeTuple, LowerBound, Sz, FirstActionKey),
@@ -575,7 +667,7 @@ modify_kpnode(
% perform remaining actions on last node
{_, PointerInfo} = element(Sz, NodeTuple),
{ok, ChildKPs, QueryOutput2} =
- modify_node(Bt, PointerInfo, Actions, QueryOutput),
+ modify_node(Bt, PointerInfo, Actions, QueryOutput, Depth),
NodeList = lists:reverse(
ResultNode,
bounded_tuple_to_list(
@@ -593,7 +685,7 @@ modify_kpnode(
end,
{LessEqQueries, GreaterQueries} = lists:splitwith(SplitFun, Actions),
{ok, ChildKPs, QueryOutput2} =
- modify_node(Bt, PointerInfo, LessEqQueries, QueryOutput),
+ modify_node(Bt, PointerInfo, LessEqQueries, QueryOutput, Depth),
ResultNode2 = lists:reverse(
ChildKPs,
bounded_tuple_to_revlist(
@@ -603,7 +695,7 @@ modify_kpnode(
ResultNode
)
),
- modify_kpnode(Bt, NodeTuple, N + 1, GreaterQueries, ResultNode2, QueryOutput2)
+ modify_kpnode(Bt, NodeTuple, N + 1, GreaterQueries, ResultNode2, QueryOutput2, Depth)
end.
bounded_tuple_to_revlist(_Tuple, Start, End, Tail) when Start > End ->
@@ -631,7 +723,7 @@ find_first_gteq(Bt, Tuple, Start, End, Key) ->
find_first_gteq(Bt, Tuple, Start, Mid, Key)
end.
-modify_kvnode(_Bt, NodeTuple, LowerBound, [], ResultNode, QueryOutput) ->
+modify_kvnode(_Bt, NodeTuple, LowerBound, [], ResultNode, QueryOutput, _Depth) ->
{ok,
lists:reverse(
ResultNode, bounded_tuple_to_list(NodeTuple, LowerBound, tuple_size(NodeTuple), [])
@@ -643,7 +735,8 @@ modify_kvnode(
LowerBound,
[{ActionType, ActionKey, ActionValue} | RestActions],
ResultNode,
- QueryOutput
+ QueryOutput,
+ Depth
) when LowerBound > tuple_size(NodeTuple) ->
case ActionType of
insert ->
@@ -653,16 +746,25 @@ modify_kvnode(
LowerBound,
RestActions,
[{ActionKey, ActionValue} | ResultNode],
- QueryOutput
+ QueryOutput,
+ Depth
);
remove ->
% just drop the action
- modify_kvnode(Bt, NodeTuple, LowerBound, RestActions, ResultNode, QueryOutput);
+ modify_kvnode(Bt, NodeTuple, LowerBound, RestActions, ResultNode, QueryOutput, Depth);
fetch ->
% the key/value must not exist in the tree
- modify_kvnode(Bt, NodeTuple, LowerBound, RestActions, ResultNode, [
- {not_found, {ActionKey, nil}} | QueryOutput
- ])
+ modify_kvnode(
+ Bt,
+ NodeTuple,
+ LowerBound,
+ RestActions,
+ ResultNode,
+ [
+ {not_found, {ActionKey, nil}} | QueryOutput
+ ],
+ Depth
+ )
end;
modify_kvnode(
Bt,
@@ -670,7 +772,8 @@ modify_kvnode(
LowerBound,
[{ActionType, ActionKey, ActionValue} | RestActions],
AccNode,
- QueryOutput
+ QueryOutput,
+ Depth
) ->
N = find_first_gteq(Bt, NodeTuple, LowerBound, tuple_size(NodeTuple), ActionKey),
{Key, Value} = element(N, NodeTuple),
@@ -686,16 +789,25 @@ modify_kvnode(
N,
RestActions,
[{ActionKey, ActionValue} | ResultNode],
- QueryOutput
+ QueryOutput,
+ Depth
);
remove ->
% ActionKey is less than the Key, just drop the action
- modify_kvnode(Bt, NodeTuple, N, RestActions, ResultNode, QueryOutput);
+ modify_kvnode(Bt, NodeTuple, N, RestActions, ResultNode, QueryOutput, Depth);
fetch ->
% ActionKey is less than the Key, the key/value must not exist in the tree
- modify_kvnode(Bt, NodeTuple, N, RestActions, ResultNode, [
- {not_found, {ActionKey, nil}} | QueryOutput
- ])
+ modify_kvnode(
+ Bt,
+ NodeTuple,
+ N,
+ RestActions,
+ ResultNode,
+ [
+ {not_found, {ActionKey, nil}} | QueryOutput
+ ],
+ Depth
+ )
end;
false ->
% ActionKey and Key are maybe equal.
@@ -709,18 +821,27 @@ modify_kvnode(
N + 1,
RestActions,
[{ActionKey, ActionValue} | ResultNode],
- QueryOutput
+ QueryOutput,
+ Depth
);
remove ->
modify_kvnode(
- Bt, NodeTuple, N + 1, RestActions, ResultNode, QueryOutput
+ Bt, NodeTuple, N + 1, RestActions, ResultNode, QueryOutput, Depth
);
fetch ->
% ActionKey is equal to the Key, insert into the QueryOuput, but re-process the node
% since an identical action key can follow it.
- modify_kvnode(Bt, NodeTuple, N, RestActions, ResultNode, [
- {ok, assemble(Bt, Key, Value)} | QueryOutput
- ])
+ modify_kvnode(
+ Bt,
+ NodeTuple,
+ N,
+ RestActions,
+ ResultNode,
+ [
+ {ok, assemble(Bt, Key, Value)} | QueryOutput
+ ],
+ Depth
+ )
end;
true ->
modify_kvnode(
@@ -729,7 +850,8 @@ modify_kvnode(
N + 1,
[{ActionType, ActionKey, ActionValue} | RestActions],
[{Key, Value} | ResultNode],
- QueryOutput
+ QueryOutput,
+ Depth
)
end
end.
@@ -745,7 +867,8 @@ reduce_stream_node(
GroupedRedsAcc,
_KeyGroupFun,
_Fun,
- Acc
+ Acc,
+ _Depth
) ->
{ok, Acc, GroupedRedsAcc, GroupedKVsAcc, GroupedKey};
reduce_stream_node(
@@ -759,10 +882,12 @@ reduce_stream_node(
GroupedRedsAcc,
KeyGroupFun,
Fun,
- Acc
+ Acc,
+ Depth0
) ->
+ Depth = Depth0 + 1,
P = element(1, Node),
- case get_node(Bt, P) of
+ case get_node(Bt, P, Depth) of
{kp_node, NodeList} ->
NodeList2 = adjust_dir(Dir, NodeList),
reduce_stream_kp_node(
@@ -776,7 +901,8 @@ reduce_stream_node(
GroupedRedsAcc,
KeyGroupFun,
Fun,
- Acc
+ Acc,
+ Depth
);
{kv_node, KVs} ->
KVs2 = adjust_dir(Dir, KVs),
@@ -791,7 +917,8 @@ reduce_stream_node(
GroupedRedsAcc,
KeyGroupFun,
Fun,
- Acc
+ Acc,
+ Depth
)
end.
@@ -806,7 +933,8 @@ reduce_stream_kv_node(
GroupedRedsAcc,
KeyGroupFun,
Fun,
- Acc
+ Acc,
+ Depth
) ->
GTEKeyStartKVs =
case KeyStart of
@@ -833,7 +961,8 @@ reduce_stream_kv_node(
GroupedRedsAcc,
KeyGroupFun,
Fun,
- Acc
+ Acc,
+ Depth
).
reduce_stream_kv_node2(
@@ -844,7 +973,8 @@ reduce_stream_kv_node2(
GroupedRedsAcc,
_KeyGroupFun,
_Fun,
- Acc
+ Acc,
+ _Depth
) ->
{ok, Acc, GroupedRedsAcc, GroupedKVsAcc, GroupedKey};
reduce_stream_kv_node2(
@@ -855,7 +985,8 @@ reduce_stream_kv_node2(
GroupedRedsAcc,
KeyGroupFun,
Fun,
- Acc
+ Acc,
+ Depth
) ->
case GroupedKey of
undefined ->
@@ -867,7 +998,8 @@ reduce_stream_kv_node2(
[],
KeyGroupFun,
Fun,
- Acc
+ Acc,
+ Depth
);
_ ->
case KeyGroupFun(GroupedKey, Key) of
@@ -880,7 +1012,8 @@ reduce_stream_kv_node2(
GroupedRedsAcc,
KeyGroupFun,
Fun,
- Acc
+ Acc,
+ Depth
);
false ->
case Fun(GroupedKey, {GroupedKVsAcc, GroupedRedsAcc}, Acc) of
@@ -893,7 +1026,8 @@ reduce_stream_kv_node2(
[],
KeyGroupFun,
Fun,
- Acc2
+ Acc2,
+ Depth
);
{stop, Acc2} ->
throw({stop, Acc2})
@@ -912,7 +1046,8 @@ reduce_stream_kp_node(
GroupedRedsAcc,
KeyGroupFun,
Fun,
- Acc
+ Acc,
+ Depth
) ->
Nodes =
case KeyStart of
@@ -955,7 +1090,8 @@ reduce_stream_kp_node(
GroupedRedsAcc,
KeyGroupFun,
Fun,
- Acc
+ Acc,
+ Depth
).
reduce_stream_kp_node2(
@@ -969,7 +1105,8 @@ reduce_stream_kp_node2(
[],
KeyGroupFun,
Fun,
- Acc
+ Acc,
+ Depth
) ->
{ok, Acc2, GroupedRedsAcc2, GroupedKVsAcc2, GroupedKey2} =
reduce_stream_node(
@@ -983,7 +1120,8 @@ reduce_stream_kp_node2(
[],
KeyGroupFun,
Fun,
- Acc
+ Acc,
+ Depth
),
reduce_stream_kp_node2(
Bt,
@@ -996,7 +1134,8 @@ reduce_stream_kp_node2(
GroupedRedsAcc2,
KeyGroupFun,
Fun,
- Acc2
+ Acc2,
+ Depth
);
reduce_stream_kp_node2(
Bt,
@@ -1009,7 +1148,8 @@ reduce_stream_kp_node2(
GroupedRedsAcc,
KeyGroupFun,
Fun,
- Acc
+ Acc,
+ Depth
) ->
{Grouped0, Ungrouped0} = lists:splitwith(
fun({Key, _}) ->
@@ -1040,7 +1180,8 @@ reduce_stream_kp_node2(
GroupedReds ++ GroupedRedsAcc,
KeyGroupFun,
Fun,
- Acc
+ Acc,
+ Depth
),
reduce_stream_kp_node2(
Bt,
@@ -1053,7 +1194,8 @@ reduce_stream_kp_node2(
GroupedRedsAcc2,
KeyGroupFun,
Fun,
- Acc2
+ Acc2,
+ Depth
);
[] ->
{ok, Acc, GroupedReds ++ GroupedRedsAcc, GroupedKVsAcc, GroupedKey}
@@ -1064,40 +1206,46 @@ adjust_dir(fwd, List) ->
adjust_dir(rev, List) ->
lists:reverse(List).
-stream_node(Bt, Reds, Node, StartKey, InRange, Dir, Fun, Acc) ->
+stream_node(Bt, Reds, Node, StartKey, InRange, Dir, Fun, Acc, Depth0) ->
+ Depth = Depth0 + 1,
Pointer = element(1, Node),
- {NodeType, NodeList} = get_node(Bt, Pointer),
+ {NodeType, NodeList} = get_node(Bt, Pointer, Depth),
case NodeType of
kp_node ->
- stream_kp_node(Bt, Reds, adjust_dir(Dir, NodeList), StartKey, InRange, Dir, Fun, Acc);
+ stream_kp_node(
+ Bt, Reds, adjust_dir(Dir, NodeList), StartKey, InRange, Dir, Fun, Acc, Depth
+ );
kv_node ->
- stream_kv_node(Bt, Reds, adjust_dir(Dir, NodeList), StartKey, InRange, Dir, Fun, Acc)
+ stream_kv_node(
+ Bt, Reds, adjust_dir(Dir, NodeList), StartKey, InRange, Dir, Fun, Acc, Depth
+ )
end.
-stream_node(Bt, Reds, Node, InRange, Dir, Fun, Acc) ->
+stream_node(Bt, Reds, Node, InRange, Dir, Fun, Acc, Depth0) ->
+ Depth = Depth0 + 1,
Pointer = element(1, Node),
- {NodeType, NodeList} = get_node(Bt, Pointer),
+ {NodeType, NodeList} = get_node(Bt, Pointer, Depth),
case NodeType of
kp_node ->
- stream_kp_node(Bt, Reds, adjust_dir(Dir, NodeList), InRange, Dir, Fun, Acc);
+ stream_kp_node(Bt, Reds, adjust_dir(Dir, NodeList), InRange, Dir, Fun, Acc, Depth);
kv_node ->
- stream_kv_node2(Bt, Reds, [], adjust_dir(Dir, NodeList), InRange, Dir, Fun, Acc)
+ stream_kv_node2(Bt, Reds, [], adjust_dir(Dir, NodeList), InRange, Dir, Fun, Acc, Depth)
end.
-stream_kp_node(_Bt, _Reds, [], _InRange, _Dir, _Fun, Acc) ->
+stream_kp_node(_Bt, _Reds, [], _InRange, _Dir, _Fun, Acc, _Depth) ->
{ok, Acc};
-stream_kp_node(Bt, Reds, [{Key, Node} | Rest], InRange, Dir, Fun, Acc) ->
+stream_kp_node(Bt, Reds, [{Key, Node} | Rest], InRange, Dir, Fun, Acc, Depth) ->
Red = element(2, Node),
case Fun(traverse, Key, Red, Acc) of
{ok, Acc2} ->
- case stream_node(Bt, Reds, Node, InRange, Dir, Fun, Acc2) of
+ case stream_node(Bt, Reds, Node, InRange, Dir, Fun, Acc2, Depth) of
{ok, Acc3} ->
- stream_kp_node(Bt, [Red | Reds], Rest, InRange, Dir, Fun, Acc3);
+ stream_kp_node(Bt, [Red | Reds], Rest, InRange, Dir, Fun, Acc3, Depth);
{stop, LastReds, Acc3} ->
{stop, LastReds, Acc3}
end;
{skip, Acc2} ->
- stream_kp_node(Bt, [Red | Reds], Rest, InRange, Dir, Fun, Acc2);
+ stream_kp_node(Bt, [Red | Reds], Rest, InRange, Dir, Fun, Acc2, Depth);
{stop, Acc2} ->
{stop, Reds, Acc2}
end.
@@ -1112,7 +1260,7 @@ drop_nodes(Bt, Reds, StartKey, [{NodeKey, Node} | RestKPs]) ->
{Reds, [{NodeKey, Node} | RestKPs]}
end.
-stream_kp_node(Bt, Reds, KPs, StartKey, InRange, Dir, Fun, Acc) ->
+stream_kp_node(Bt, Reds, KPs, StartKey, InRange, Dir, Fun, Acc, Depth) ->
{NewReds, NodesToStream} =
case Dir of
fwd ->
@@ -1135,16 +1283,16 @@ stream_kp_node(Bt, Reds, KPs, StartKey, InRange, Dir, Fun, Acc) ->
[] ->
{ok, Acc};
[{_Key, Node} | Rest] ->
- case stream_node(Bt, NewReds, Node, StartKey, InRange, Dir, Fun, Acc) of
+ case stream_node(Bt, NewReds, Node, StartKey, InRange, Dir, Fun, Acc, Depth) of
{ok, Acc2} ->
Red = element(2, Node),
- stream_kp_node(Bt, [Red | NewReds], Rest, InRange, Dir, Fun, Acc2);
+ stream_kp_node(Bt, [Red | NewReds], Rest, InRange, Dir, Fun, Acc2, Depth);
{stop, LastReds, Acc2} ->
{stop, LastReds, Acc2}
end
end.
-stream_kv_node(Bt, Reds, KVs, StartKey, InRange, Dir, Fun, Acc) ->
+stream_kv_node(Bt, Reds, KVs, StartKey, InRange, Dir, Fun, Acc, Depth) ->
DropFun =
case Dir of
fwd ->
@@ -1154,11 +1302,11 @@ stream_kv_node(Bt, Reds, KVs, StartKey, InRange, Dir, Fun, Acc) ->
end,
{LTKVs, GTEKVs} = lists:splitwith(DropFun, KVs),
AssembleLTKVs = [assemble(Bt, K, V) || {K, V} <- LTKVs],
- stream_kv_node2(Bt, Reds, AssembleLTKVs, GTEKVs, InRange, Dir, Fun, Acc).
+ stream_kv_node2(Bt, Reds, AssembleLTKVs, GTEKVs, InRange, Dir, Fun, Acc, Depth).
-stream_kv_node2(_Bt, _Reds, _PrevKVs, [], _InRange, _Dir, _Fun, Acc) ->
+stream_kv_node2(_Bt, _Reds, _PrevKVs, [], _InRange, _Dir, _Fun, Acc, _Depth) ->
{ok, Acc};
-stream_kv_node2(Bt, Reds, PrevKVs, [{K, V} | RestKVs], InRange, Dir, Fun, Acc) ->
+stream_kv_node2(Bt, Reds, PrevKVs, [{K, V} | RestKVs], InRange, Dir, Fun, Acc, Depth) ->
case InRange(K) of
false ->
{stop, {PrevKVs, Reds}, Acc};
@@ -1167,7 +1315,7 @@ stream_kv_node2(Bt, Reds, PrevKVs, [{K, V} | RestKVs], InRange, Dir, Fun, Acc) -
case Fun(visit, AssembledKV, {PrevKVs, Reds}, Acc) of
{ok, Acc2} ->
stream_kv_node2(
- Bt, Reds, [AssembledKV | PrevKVs], RestKVs, InRange, Dir, Fun, Acc2
+ Bt, Reds, [AssembledKV | PrevKVs], RestKVs, InRange, Dir, Fun, Acc2, Depth
);
{stop, Acc2} ->
{stop, {PrevKVs, Reds}, Acc2}
diff --git a/src/couch/src/couch_db.erl b/src/couch/src/couch_db.erl
index e33e695c0..fe540ec86 100644
--- a/src/couch/src/couch_db.erl
+++ b/src/couch/src/couch_db.erl
@@ -67,6 +67,9 @@
set_security/2,
set_user_ctx/2,
+ get_props/1,
+ update_props/3,
+
load_validation_funs/1,
reload_validation_funs/1,
@@ -152,6 +155,11 @@
% Purge client max lag window in seconds (defaulting to 24 hours)
-define(PURGE_LAG_SEC, 86400).
+% DB props which cannot be dynamically updated after db creation
+-define(PROP_PARTITIONED, partitioned).
+-define(PROP_HASH, hash).
+-define(STATIC_PROPS, [?PROP_PARTITIONED, ?PROP_HASH]).
+
start_link(Engine, DbName, Filepath, Options) ->
Arg = {Engine, DbName, Filepath, Options},
proc_lib:start_link(couch_db_updater, init, [Arg]).
@@ -227,9 +235,9 @@ is_clustered(#db{}) ->
is_clustered(?OLD_DB_REC = Db) ->
?OLD_DB_MAIN_PID(Db) == undefined.
-is_partitioned(#db{options = Options}) ->
- Props = couch_util:get_value(props, Options, []),
- couch_util:get_value(partitioned, Props, false).
+is_partitioned(#db{} = Db) ->
+ Props = get_props(Db),
+ couch_util:get_value(?PROP_PARTITIONED, Props, false).
close(#db{} = Db) ->
ok = couch_db_engine:decref(Db);
@@ -254,7 +262,7 @@ monitored_by(Db) ->
end.
monitor(#db{main_pid = MainPid}) ->
- erlang:monitor(process, MainPid).
+ monitor(process, MainPid).
start_compact(#db{} = Db) ->
gen_server:call(Db#db.main_pid, start_compact).
@@ -269,7 +277,7 @@ wait_for_compaction(#db{main_pid = Pid} = Db, Timeout) ->
Start = os:timestamp(),
case gen_server:call(Pid, compactor_pid) of
CPid when is_pid(CPid) ->
- Ref = erlang:monitor(process, CPid),
+ Ref = monitor(process, CPid),
receive
{'DOWN', Ref, _, _, normal} when Timeout == infinity ->
wait_for_compaction(Db, Timeout);
@@ -279,7 +287,7 @@ wait_for_compaction(#db{main_pid = Pid} = Db, Timeout) ->
{'DOWN', Ref, _, _, Reason} ->
{error, Reason}
after Timeout ->
- erlang:demonitor(Ref, [flush]),
+ demonitor(Ref, [flush]),
{error, Timeout}
end;
_ ->
@@ -420,7 +428,7 @@ purge_docs(#db{main_pid = Pid} = Db, UUIDsIdsRevs, Options) ->
% Gather any existing purges with the same UUIDs
UUIDs = element(1, lists:unzip3(UUIDsIdsRevs1)),
Old1 = get_purge_infos(Db, UUIDs),
- Old2 = maps:from_list([{UUID, {Id, Revs}} || {_, UUID, Id, Revs} <- Old1]),
+ Old2 = #{UUID => {Id, Revs} || {_, UUID, Id, Revs} <- Old1},
% Filter out all the purges which have already been processed
FilterCheckFun = fun({UUID, Id, Revs}) ->
case maps:is_key(UUID, Old2) of
@@ -478,7 +486,7 @@ get_minimum_purge_seq(#db{} = Db) ->
CS when is_integer(CS) ->
case purge_client_exists(DbName, DocId, Props) of
true ->
- {ok, erlang:min(CS, SeqAcc)};
+ {ok, min(CS, SeqAcc)};
false ->
Fmt1 =
"Missing or stale purge doc '~s' on ~p "
@@ -489,7 +497,7 @@ get_minimum_purge_seq(#db{} = Db) ->
_ ->
Fmt2 = "Invalid purge doc '~s' on ~p with purge_seq '~w'",
couch_log:error(Fmt2, [DocId, DbName, ClientSeq]),
- {ok, erlang:min(OldestPurgeSeq, SeqAcc)}
+ {ok, min(OldestPurgeSeq, SeqAcc)}
end;
_ ->
{stop, SeqAcc}
@@ -503,7 +511,7 @@ get_minimum_purge_seq(#db{} = Db) ->
FinalSeq =
case MinIdxSeq < PurgeSeq - PurgeInfosLimit of
true -> MinIdxSeq;
- false -> erlang:max(0, PurgeSeq - PurgeInfosLimit)
+ false -> max(0, PurgeSeq - PurgeInfosLimit)
end,
% Log a warning if we've got a purge sequence exceeding the
% configured threshold.
@@ -626,11 +634,7 @@ get_db_info(Db) ->
undefined -> null;
Else1 -> Else1
end,
- Props =
- case couch_db_engine:get_props(Db) of
- undefined -> null;
- Else2 -> {Else2}
- end,
+ Props = get_props(Db),
InfoList = [
{db_name, Name},
{engine, couch_db_engine:get_engine(Db)},
@@ -644,7 +648,7 @@ get_db_info(Db) ->
{disk_format_version, DiskVersion},
{committed_update_seq, CommittedUpdateSeq},
{compacted_seq, CompactedSeq},
- {props, Props},
+ {props, {Props}},
{uuid, Uuid}
],
{ok, InfoList}.
@@ -837,6 +841,24 @@ set_revs_limit(#db{main_pid = Pid} = Db, Limit) when Limit > 0 ->
set_revs_limit(_Db, _Limit) ->
throw(invalid_revs_limit).
+get_props(#db{options = Options}) ->
+ couch_util:get_value(props, Options, []).
+
+update_props(#db{main_pid = Pid} = Db, K, V) ->
+ check_is_admin(Db),
+ case lists:member(K, ?STATIC_PROPS) of
+ true ->
+ throw({bad_request, <<"cannot update static property">>});
+ false ->
+ Props = get_props(Db),
+ Props1 =
+ case V of
+ undefined -> lists:keydelete(K, 1, Props);
+ _ -> lists:keystore(K, 1, Props, {K, V})
+ end,
+ gen_server:call(Pid, {set_props, Props1}, infinity)
+ end.
+
name(#db{name = Name}) ->
Name;
name(?OLD_DB_REC = Db) ->
@@ -977,7 +999,7 @@ load_validation_funs(#db{main_pid = Pid, name = <<"shards/", _/binary>>} = Db) -
Funs;
{'DOWN', Ref, _, _, {database_does_not_exist, _StackTrace}} ->
ok = couch_server:close_db_if_idle(Db#db.name),
- erlang:error(database_does_not_exist);
+ error(database_does_not_exist);
{'DOWN', Ref, _, _, Reason} ->
couch_log:error("could not load validation funs ~p", [Reason]),
throw(internal_server_error)
@@ -1255,7 +1277,7 @@ new_revid(#doc{body = Body, revs = {OldStart, OldRevs}, atts = Atts, deleted = D
case DigestedAtts of
Atts2 when length(Atts) =/= length(Atts2) ->
% We must have old style non-md5 attachments
- ?l2b(integer_to_list(couch_util:rand32()));
+ integer_to_binary(couch_util:rand32());
Atts2 ->
OldRev =
case OldRevs of
@@ -1340,8 +1362,13 @@ update_docs(Db, Docs0, Options, ?REPLICATED_CHANGES) ->
{ok, DocErrors};
update_docs(Db, Docs0, Options, ?INTERACTIVE_EDIT) ->
BlockInteractiveDatabaseWrites = couch_disk_monitor:block_interactive_database_writes(),
+ InternalReplication =
+ case get(io_priority) of
+ {internal_repl, _} -> true;
+ _Else -> false
+ end,
if
- BlockInteractiveDatabaseWrites ->
+ not InternalReplication andalso BlockInteractiveDatabaseWrites ->
{ok, [{insufficient_storage, <<"database_dir is too full">>} || _ <- Docs0]};
true ->
update_docs_interactive(Db, Docs0, Options)
@@ -1466,7 +1493,7 @@ write_and_commit(
) ->
DocBuckets = prepare_doc_summaries(Db, DocBuckets1),
ReplicatedChanges = lists:member(?REPLICATED_CHANGES, Options),
- MRef = erlang:monitor(process, Pid),
+ MRef = monitor(process, Pid),
try
Pid ! {update_docs, self(), DocBuckets, LocalDocs, ReplicatedChanges},
case collect_results_with_metrics(Pid, MRef, []) of
@@ -1490,7 +1517,7 @@ write_and_commit(
end
end
after
- erlang:demonitor(MRef, [flush])
+ demonitor(MRef, [flush])
end.
prepare_doc_summaries(Db, BucketList) ->
@@ -1751,12 +1778,12 @@ validate_epochs(Epochs) ->
%% Assert uniqueness.
case length(Epochs) == length(lists:ukeysort(2, Epochs)) of
true -> ok;
- false -> erlang:error(duplicate_epoch)
+ false -> error(duplicate_epoch)
end,
%% Assert order.
case Epochs == lists:sort(fun({_, A}, {_, B}) -> B =< A end, Epochs) of
true -> ok;
- false -> erlang:error(epoch_order)
+ false -> error({epoch_order, Epochs})
end.
is_prefix(Pattern, Subject) ->
@@ -2352,7 +2379,10 @@ is_owner_test() ->
?assertNot(is_owner(bar, 99, [{baz, 200}, {bar, 100}, {foo, 1}])),
?assertNot(is_owner(baz, 199, [{baz, 200}, {bar, 100}, {foo, 1}])),
?assertError(duplicate_epoch, validate_epochs([{foo, 1}, {bar, 1}])),
- ?assertError(epoch_order, validate_epochs([{foo, 100}, {bar, 200}])).
+ ?assertError(
+ {epoch_order, [{foo, 100}, {bar, 200}]},
+ validate_epochs([{foo, 100}, {bar, 200}])
+ ).
to_binary(DbName) when is_list(DbName) ->
?l2b(DbName);
diff --git a/src/couch/src/couch_db_updater.erl b/src/couch/src/couch_db_updater.erl
index 3f6c8886d..b6dfc818d 100644
--- a/src/couch/src/couch_db_updater.erl
+++ b/src/couch/src/couch_db_updater.erl
@@ -92,6 +92,12 @@ handle_call({set_purge_infos_limit, Limit}, _From, Db) ->
{ok, Db2} = couch_db_engine:set_purge_infos_limit(Db, Limit),
ok = couch_server:db_updated(Db2),
{reply, ok, Db2};
+handle_call({set_props, Props}, _From, Db) ->
+ {ok, Db1} = couch_db_engine:set_props(Db, Props),
+ Db2 = options_set_props(Db1, Props),
+ {ok, Db3} = couch_db_engine:commit_data(Db2),
+ ok = couch_server:db_updated(Db3),
+ {reply, ok, Db3};
handle_call({purge_docs, [], _}, _From, Db) ->
{reply, {ok, []}, Db};
handle_call({purge_docs, PurgeReqs0, Options}, _From, Db) ->
@@ -308,13 +314,17 @@ init_db(DbName, FilePath, EngineState, Options) ->
after_doc_read = ADR
},
- DbProps = couch_db_engine:get_props(InitDb),
-
- InitDb#db{
+ Db = InitDb#db{
committed_update_seq = couch_db_engine:get_update_seq(InitDb),
security = couch_db_engine:get_security(InitDb),
- options = lists:keystore(props, 1, NonCreateOpts, {props, DbProps})
- }.
+ options = NonCreateOpts
+ },
+ DbProps = couch_db_engine:get_props(Db),
+ options_set_props(Db, DbProps).
+
+options_set_props(#db{options = Options} = Db, Props) ->
+ Options1 = lists:keystore(props, 1, Options, {props, Props}),
+ Db#db{options = Options1}.
refresh_validate_doc_funs(#db{name = <<"shards/", _/binary>> = Name} = Db) ->
spawn(fabric, reset_validation_funs, [mem3:dbname(Name)]),
@@ -795,22 +805,22 @@ purge_docs(Db, PurgeReqs) ->
FDIs = couch_db_engine:open_docs(Db, Ids),
USeq = couch_db_engine:get_update_seq(Db),
- IdFDIs = lists:zip(Ids, FDIs),
+ IdFDIs = maps:from_list(lists:zip(Ids, FDIs)),
{NewIdFDIs, Replies} = apply_purge_reqs(PurgeReqs, IdFDIs, USeq, []),
- Pairs = lists:flatmap(
- fun({DocId, OldFDI}) ->
- {DocId, NewFDI} = lists:keyfind(DocId, 1, NewIdFDIs),
- case {OldFDI, NewFDI} of
- {not_found, not_found} ->
- [];
- {#full_doc_info{} = A, #full_doc_info{} = A} ->
- [];
- {#full_doc_info{}, _} ->
- [{OldFDI, NewFDI}]
- end
- end,
- IdFDIs
+ Pairs = lists:sort(
+ maps:fold(
+ fun(DocId, OldFDI, Acc) ->
+ #{DocId := NewFDI} = NewIdFDIs,
+ case {OldFDI, NewFDI} of
+ {not_found, not_found} -> Acc;
+ {#full_doc_info{} = A, #full_doc_info{} = A} -> Acc;
+ {#full_doc_info{}, _} -> [{OldFDI, NewFDI} | Acc]
+ end
+ end,
+ [],
+ IdFDIs
+ )
),
PSeq = couch_db_engine:get_purge_seq(Db),
@@ -834,7 +844,7 @@ apply_purge_reqs([], IdFDIs, _USeq, Replies) ->
{IdFDIs, lists:reverse(Replies)};
apply_purge_reqs([Req | RestReqs], IdFDIs, USeq, Replies) ->
{_UUID, DocId, Revs} = Req,
- {value, {_, FDI0}, RestIdFDIs} = lists:keytake(DocId, 1, IdFDIs),
+ #{DocId := FDI0} = IdFDIs,
{NewFDI, RemovedRevs, NewUSeq} =
case FDI0 of
#full_doc_info{rev_tree = Tree} ->
@@ -872,9 +882,8 @@ apply_purge_reqs([Req | RestReqs], IdFDIs, USeq, Replies) ->
% Not found means nothing to change
{not_found, [], USeq}
end,
- NewIdFDIs = [{DocId, NewFDI} | RestIdFDIs],
NewReplies = [{ok, RemovedRevs} | Replies],
- apply_purge_reqs(RestReqs, NewIdFDIs, NewUSeq, NewReplies).
+ apply_purge_reqs(RestReqs, IdFDIs#{DocId := NewFDI}, NewUSeq, NewReplies).
commit_data(Db) ->
{ok, Db1} = couch_db_engine:commit_data(Db),
diff --git a/src/couch/src/couch_debug.erl b/src/couch/src/couch_debug.erl
index ff864210f..2cc0a94b4 100644
--- a/src/couch/src/couch_debug.erl
+++ b/src/couch/src/couch_debug.erl
@@ -48,7 +48,8 @@
dead_nodes/1,
ping/1,
ping/2,
- ping_nodes/0,
+ ping_live_cluster_nodes/0,
+ ping_live_cluster_nodes/1,
ping_nodes/1,
ping_nodes/2,
node_events/0
@@ -57,9 +58,12 @@
-export([
print_table/2,
print_report/1,
- print_report_with_info_width/2
+ print_report_with_info_width/2,
+ print_tree/2
]).
+-define(PING_TIMEOUT_IN_MS, 60000).
+
-type throw(_Reason) :: no_return().
-type process_name() :: atom().
@@ -83,18 +87,23 @@ help() ->
process_name,
get_pid,
link_tree,
- mapfold,
- map,
- fold,
+ mapfold_tree,
+ fold_tree,
+ map_tree,
linked_processes_info,
print_linked_processes,
memory_info,
+ resource_hoggers,
+ resource_hoggers_snapshot,
+ analyze_resource_hoggers,
print_table,
print_report,
print_report_with_info_width,
+ print_tree,
restart,
restart_busy,
dead_nodes,
+ ping,
ping_nodes,
node_events
].
@@ -230,7 +239,7 @@ help(link_tree) ->
The function doesn't recurse to pids older than initial one.
The Pids which are lesser than initial Pid are still shown in the output.
The info argument is a list of process_info_item() as documented in
- erlang:process_info/2. We don't do any attempts to prevent dangerous items.
+ process_info/2. We don't do any attempts to prevent dangerous items.
Be warn that passing some of them such as `messages` for example
can be dangerous in a very busy system.
---
@@ -288,7 +297,7 @@ help(linked_processes_info) ->
use of link_tree.
- Pid: initial Pid to start from
- Info: a list of process_info_item() as documented
- in erlang:process_info/2.
+ in process_info/2.
---
", []);
@@ -467,18 +476,27 @@ help(ping) ->
Ping a node and return either a time in microseconds or an error term.
+ ---
+ ", []);
+help(ping_live_cluster_nodes) ->
+ io:format("
+ ping_live_cluster_nodes()
+ ping_live_cluster_nodes(Timeout)
+ --------------------------------
+
+ Ping the currently connected cluster nodes. Returns a list of
+ {Node, Result} tuples or an empty list.
+
---
", []);
help(ping_nodes) ->
io:format("
- ping_nodes()
- ping_nodes(Timeout)
+ ping_nodes(Nodes)
ping_nodes(Nodes, Timeout)
--------------------------------
- Ping the list of currently connected nodes. Return a list of {Node,
- Result} tuples where Result is either a time in microseconds or an
- error term.
+ Ping the list of nodes. Return a list of {Node, Result} tuples where
+ Result is either a time in microseconds or an error term.
---
", []);
@@ -768,6 +786,7 @@ info_size(InfoKV) ->
{binary, BinInfos} -> lists:sum([S || {_, S, _} <- BinInfos]);
{_, V} -> V
end.
+
resource_hoggers(MemoryInfo, InfoKey) ->
KeyFun = fun
({_Pid, _Id, undefined}) -> undefined;
@@ -976,12 +995,15 @@ ping(Node) ->
ping(Node, Timeout) ->
mem3:ping(Node, Timeout).
-ping_nodes() ->
+ping_live_cluster_nodes() ->
mem3:ping_nodes().
-ping_nodes(Timeout) ->
+ping_live_cluster_nodes(Timeout) ->
mem3:ping_nodes(Timeout).
+ping_nodes(Nodes) ->
+ mem3:ping_nodes(Nodes, ?PING_TIMEOUT_IN_MS).
+
ping_nodes(Nodes, Timeout) ->
mem3:ping_nodes(Nodes, Timeout).
@@ -1007,6 +1029,7 @@ print_table(Rows, TableSpec) ->
end,
Rows
),
+ io:format("~n", []),
ok.
print_report(Report) ->
@@ -1124,8 +1147,8 @@ random_processes(Acc, Depth) ->
end);
open_port ->
spawn_link(fun() ->
- Port = erlang:open_port({spawn, "sleep 10"}, [hide]),
- true = erlang:link(Port),
+ Port = open_port({spawn, "sleep 10"}, [hide]),
+ true = link(Port),
Caller ! {Ref, random_processes(Depth - 1)},
receive
looper -> ok
diff --git a/src/couch/src/couch_doc.erl b/src/couch/src/couch_doc.erl
index 7b867f08d..7ad0f76b6 100644
--- a/src/couch/src/couch_doc.erl
+++ b/src/couch/src/couch_doc.erl
@@ -43,7 +43,7 @@ to_branch(Doc, [RevId | Rest]) ->
to_json_rev(0, []) ->
[];
to_json_rev(Start, [FirstRevId | _]) ->
- [{<<"_rev">>, ?l2b([integer_to_list(Start), "-", revid_to_str(FirstRevId)])}].
+ [{<<"_rev">>, rev_to_str({Start, FirstRevId})}].
to_json_body(true, {Body}) ->
Body ++ [{<<"_deleted">>, true}];
@@ -75,11 +75,13 @@ to_json_revisions(Options, Start, RevIds0) ->
revid_to_str(RevId) when size(RevId) =:= 16 ->
couch_util:to_hex_bin(RevId);
-revid_to_str(RevId) ->
- RevId.
+revid_to_str(RevId) when is_binary(RevId) ->
+ RevId;
+revid_to_str(RevId) when is_list(RevId) ->
+ list_to_binary(RevId).
rev_to_str({Pos, RevId}) ->
- ?l2b([integer_to_list(Pos), "-", revid_to_str(RevId)]).
+ <<(integer_to_binary(Pos))/binary, $-, (revid_to_str(RevId))/binary>>.
revs_to_strs([]) ->
[];
@@ -95,7 +97,7 @@ to_json_meta(Meta) ->
JsonObj =
{[
{<<"rev">>, rev_to_str({PosAcc, RevId})},
- {<<"status">>, ?l2b(atom_to_list(Status))}
+ {<<"status">>, atom_to_binary(Status)}
]},
{JsonObj, PosAcc - 1}
end,
@@ -186,12 +188,10 @@ from_json_obj({Props}, DbName) ->
from_json_obj(_Other, _) ->
throw({bad_request, "Document must be a JSON object"}).
-parse_revid(RevId) when size(RevId) =:= 32 ->
- RevInt = erlang:list_to_integer(?b2l(RevId), 16),
- <<RevInt:128>>;
-parse_revid(RevId) when length(RevId) =:= 32 ->
- RevInt = erlang:list_to_integer(RevId, 16),
- <<RevInt:128>>;
+parse_revid(RevId) when is_binary(RevId), size(RevId) =:= 32 ->
+ binary:decode_hex(RevId);
+parse_revid(RevId) when is_list(RevId), length(RevId) =:= 32 ->
+ binary:decode_hex(list_to_binary(RevId));
parse_revid(RevId) when is_binary(RevId) ->
RevId;
parse_revid(RevId) when is_list(RevId) ->
@@ -388,13 +388,13 @@ max_seq(Tree, UpdateSeq) ->
case Value of
{_Deleted, _DiskPos, OldTreeSeq} ->
% Older versions didn't track data sizes.
- erlang:max(MaxOldSeq, OldTreeSeq);
+ max(MaxOldSeq, OldTreeSeq);
% necessary clause?
{_Deleted, _DiskPos, OldTreeSeq, _Size} ->
% Older versions didn't store #leaf records.
- erlang:max(MaxOldSeq, OldTreeSeq);
+ max(MaxOldSeq, OldTreeSeq);
#leaf{seq = OldTreeSeq} ->
- erlang:max(MaxOldSeq, OldTreeSeq);
+ max(MaxOldSeq, OldTreeSeq);
_ ->
MaxOldSeq
end
@@ -566,7 +566,7 @@ restart_open_doc_revs(Parser, Ref, NewRef) ->
unlink(Parser),
exit(Parser, kill),
flush_parser_messages(Ref),
- erlang:error({restart_open_doc_revs, NewRef}).
+ error({restart_open_doc_revs, NewRef}).
flush_parser_messages(Ref) ->
receive
diff --git a/src/couch/src/couch_file.erl b/src/couch/src/couch_file.erl
index c1a069edd..2d0920f7e 100644
--- a/src/couch/src/couch_file.erl
+++ b/src/couch/src/couch_file.erl
@@ -47,11 +47,11 @@
-export([append_term/2, append_term/3]).
-export([pread_terms/2]).
-export([append_terms/2, append_terms/3]).
--export([write_header/2, read_header/1]).
+-export([write_header/2, write_header/3, read_header/1]).
-export([delete/2, delete/3, nuke_dir/2, init_delete_dir/1]).
% gen_server callbacks
--export([init/1, terminate/2, format_status/2]).
+-export([init/1, terminate/2]).
-export([handle_call/3, handle_cast/2, handle_info/2]).
%% helper functions
@@ -290,20 +290,20 @@ sync(Filepath) when is_list(Filepath) ->
ok ->
ok;
{error, Reason} ->
- erlang:error({fsync_error, Reason})
+ error({fsync_error, Reason})
end
after
ok = file:close(Fd)
end;
{error, Error} ->
- erlang:error(Error)
+ error(Error)
end;
sync(Fd) ->
case gen_server:call(Fd, sync, infinity) of
ok ->
ok;
{error, Reason} ->
- erlang:error({fsync_error, Reason})
+ error({fsync_error, Reason})
end.
%%----------------------------------------------------------------------
@@ -410,9 +410,7 @@ delete_dir(RootDelDir, Dir) ->
init_delete_dir(RootDir) ->
Dir = filename:join(RootDir, ".delete"),
- % note: ensure_dir requires an actual filename companent, which is the
- % reason for "foo".
- filelib:ensure_dir(filename:join(Dir, "foo")),
+ filelib:ensure_path(Dir),
spawn(fun() ->
filelib:fold_files(
Dir,
@@ -435,11 +433,16 @@ read_header(Fd) ->
end.
write_header(Fd, Data) ->
+ write_header(Fd, Data, []).
+
+% Only the sync option is currently supported
+%
+write_header(Fd, Data, Opts) when is_list(Opts) ->
Bin = ?term_to_bin(Data),
Checksum = generate_checksum(Bin),
% now we assemble the final header binary and write to disk
FinalBin = <<Checksum/binary, Bin/binary>>,
- ioq:call(Fd, {write_header, FinalBin}, erlang:get(io_priority)).
+ ioq:call(Fd, {write_header, FinalBin, Opts}, erlang:get(io_priority)).
init_status_error(ReturnPid, Ref, Error) ->
ReturnPid ! {Ref, self(), Error},
@@ -582,20 +585,21 @@ handle_call({append_bins, Bins}, _From, #file{} = File) ->
{{ok, Resps}, File1} -> {reply, {ok, Resps}, File1};
{Error, File1} -> {reply, Error, File1}
end;
-handle_call({write_header, Bin}, _From, #file{fd = Fd, eof = Pos} = File) ->
- BinSize = byte_size(Bin),
- case Pos rem ?SIZE_BLOCK of
- 0 ->
- Padding = <<>>;
- BlockOffset ->
- Padding = <<0:(8 * (?SIZE_BLOCK - BlockOffset))>>
- end,
- FinalBin = [Padding, <<1, BinSize:32/integer>> | make_blocks(5, [Bin])],
- case file:write(Fd, FinalBin) of
- ok ->
- {reply, ok, File#file{eof = Pos + iolist_size(FinalBin)}};
- Error ->
- {reply, Error, reset_eof(File)}
+handle_call({write_header, Bin, Opts}, _From, #file{} = File) ->
+ try
+ ok = header_fsync(File, Opts),
+ case handle_write_header(Bin, File) of
+ {ok, NewFile} ->
+ ok = header_fsync(NewFile, Opts),
+ {reply, ok, NewFile};
+ {{error, Err}, NewFile} ->
+ {reply, {error, Err}, NewFile}
+ end
+ catch
+ error:{fsync_error, Error} ->
+ % If fsync error happens we stop. See comment in
+ % handle_call(sync, ...) why we're dropping the fd
+ {stop, {error, Error}, {error, Error}, #file{fd = nil}}
end;
handle_call(find_header, _From, #file{fd = Fd, eof = Pos} = File) ->
{reply, find_header(Fd, Pos div ?SIZE_BLOCK), File}.
@@ -617,10 +621,6 @@ handle_info({'DOWN', Ref, process, _Pid, _Info}, #file{db_monitor = Ref} = File)
false -> {noreply, File}
end.
-format_status(_Opt, [PDict, #file{} = File]) ->
- {_Fd, FilePath} = couch_util:get_value(couch_file_fd, PDict),
- [{data, [{"State", File}, {"InitialFilePath", FilePath}]}].
-
eof(#file{fd = Fd}) ->
file:position(Fd, eof).
@@ -661,6 +661,17 @@ pread(#file{} = File, PosL) ->
Extracted = lists:zipwith(ZipFun, DataSizes, Resps),
{ok, Extracted}.
+header_fsync(#file{fd = Fd}, Opts) when is_list(Opts) ->
+ case proplists:get_value(sync, Opts) of
+ true ->
+ case fsync(Fd) of
+ ok -> ok;
+ {error, Err} -> error({fsync_error, Err})
+ end;
+ _ ->
+ ok
+ end.
+
fsync(Fd) ->
T0 = erlang:monotonic_time(),
% We do not rely on mtime/atime for our safety/consitency so we can use
@@ -759,6 +770,18 @@ find_newest_header(Fd, [{Location, Size} | LocationSizes]) ->
find_newest_header(Fd, LocationSizes)
end.
+handle_write_header(Bin, #file{fd = Fd, eof = Pos} = File) ->
+ BinSize = byte_size(Bin),
+ case Pos rem ?SIZE_BLOCK of
+ 0 -> Padding = <<>>;
+ BlockOffset -> Padding = <<0:(8 * (?SIZE_BLOCK - BlockOffset))>>
+ end,
+ FinalBin = [Padding, <<1, BinSize:32/integer>> | make_blocks(5, [Bin])],
+ case file:write(Fd, FinalBin) of
+ ok -> {ok, File#file{eof = Pos + iolist_size(FinalBin)}};
+ {error, Error} -> {{error, Error}, reset_eof(File)}
+ end.
+
read_multi_raw_iolists_int(#file{fd = Fd, eof = Eof} = File, PosLens) ->
MapFun = fun({Pos, Len}) -> get_pread_locnum(File, Pos, Len) end,
LocNums = lists:map(MapFun, PosLens),
diff --git a/src/couch/src/couch_flags_config.erl b/src/couch/src/couch_flags_config.erl
index a50f4411f..4281f2266 100644
--- a/src/couch/src/couch_flags_config.erl
+++ b/src/couch/src/couch_flags_config.erl
@@ -134,7 +134,7 @@ parse_flags(_Tokens, _) ->
parse_flags_term(FlagsBin) ->
{Flags, Errors} = lists:splitwith(
- fun erlang:is_atom/1,
+ fun is_atom/1,
[parse_flag(F) || F <- split_by_comma(FlagsBin)]
),
case Errors of
diff --git a/src/couch/src/couch_httpd_auth.erl b/src/couch/src/couch_httpd_auth.erl
index 4566157da..7c6a60d2b 100644
--- a/src/couch/src/couch_httpd_auth.erl
+++ b/src/couch/src/couch_httpd_auth.erl
@@ -381,7 +381,7 @@ cookie_authentication_handler(#httpd{mochi_req = MochiReq} = Req, AuthModule) ->
"timeout", 600
),
couch_log:debug("timeout ~p", [Timeout]),
- case (catch erlang:list_to_integer(TimeStr, 16)) of
+ case (catch list_to_integer(TimeStr, 16)) of
TimeStamp when CurrentTime < TimeStamp + Timeout ->
case lists:any(VerifyHash, HashAlgorithms) of
true ->
@@ -438,7 +438,7 @@ cookie_auth_header(_Req, _Headers) ->
[].
cookie_auth_cookie(Req, User, Secret, TimeStamp) ->
- SessionItems = [User, erlang:integer_to_list(TimeStamp, 16)],
+ SessionItems = [User, integer_to_list(TimeStamp, 16)],
cookie_auth_cookie(Req, Secret, SessionItems).
cookie_auth_cookie(Req, Secret, SessionItems) when is_list(SessionItems) ->
diff --git a/src/couch/src/couch_httpd_db.erl b/src/couch/src/couch_httpd_db.erl
index 5c566ed78..733991d84 100644
--- a/src/couch/src/couch_httpd_db.erl
+++ b/src/couch/src/couch_httpd_db.erl
@@ -817,7 +817,7 @@ receive_request_data(Req) ->
receive_request_data(Req, couch_httpd:body_length(Req)).
receive_request_data(Req, LenLeft) when LenLeft > 0 ->
- Len = erlang:min(4096, LenLeft),
+ Len = min(4096, LenLeft),
Data = couch_httpd:recv(Req, Len),
{Data, fun() -> receive_request_data(Req, LenLeft - iolist_size(Data)) end};
receive_request_data(_Req, _) ->
diff --git a/src/couch/src/couch_httpd_multipart.erl b/src/couch/src/couch_httpd_multipart.erl
index 80fc48a75..87c588fc8 100644
--- a/src/couch/src/couch_httpd_multipart.erl
+++ b/src/couch/src/couch_httpd_multipart.erl
@@ -27,7 +27,7 @@ decode_multipart_stream(ContentType, DataFun, Ref) ->
Parent = self(),
NumMpWriters = num_mp_writers(),
{Parser, ParserRef} = spawn_monitor(fun() ->
- ParentRef = erlang:monitor(process, Parent),
+ ParentRef = monitor(process, Parent),
put(mp_parent_ref, ParentRef),
num_mp_writers(NumMpWriters),
{<<"--", _/binary>>, _, _} = couch_httpd:parse_multipart_request(
@@ -214,7 +214,7 @@ maybe_send_data({Ref, Chunks, Offset, Counters, Waiting}) ->
end.
handle_hello(WriterPid, Counters) ->
- WriterRef = erlang:monitor(process, WriterPid),
+ WriterRef = monitor(process, WriterPid),
orddict:store(WriterPid, {WriterRef, 0}, Counters).
update_writer(WriterPid, Counters) ->
@@ -222,7 +222,7 @@ update_writer(WriterPid, Counters) ->
{ok, {WriterRef, Count}} ->
orddict:store(WriterPid, {WriterRef, Count + 1}, Counters);
error ->
- WriterRef = erlang:monitor(process, WriterPid),
+ WriterRef = monitor(process, WriterPid),
orddict:store(WriterPid, {WriterRef, 1}, Counters)
end.
@@ -274,7 +274,7 @@ atts_to_mp(
WriteFun,
AttFun
) ->
- LengthBin = list_to_binary(integer_to_list(Len)),
+ LengthBin = integer_to_binary(Len),
% write headers
WriteFun(<<"\r\nContent-Disposition: attachment; filename=\"", Name/binary, "\"">>),
WriteFun(<<"\r\nContent-Type: ", Type/binary>>),
@@ -344,7 +344,7 @@ length_multipart_stream(Boundary, JsonBytes, Atts) ->
end.
abort_multipart_stream(Parser) ->
- MonRef = erlang:monitor(process, Parser),
+ MonRef = monitor(process, Parser),
Parser ! abort_parsing,
receive
{'DOWN', MonRef, _, _, _} -> ok
diff --git a/src/couch/src/couch_httpd_vhost.erl b/src/couch/src/couch_httpd_vhost.erl
index 170e1a2f7..91da711af 100644
--- a/src/couch/src/couch_httpd_vhost.erl
+++ b/src/couch/src/couch_httpd_vhost.erl
@@ -329,7 +329,7 @@ split_host_port(HostAsString) ->
N ->
HostPart = string:substr(HostAsString, 1, N - 1),
case
- (catch erlang:list_to_integer(
+ (catch list_to_integer(
string:substr(
HostAsString,
N + 1,
diff --git a/src/couch/src/couch_key_tree.erl b/src/couch/src/couch_key_tree.erl
index 87504c78c..6a3dffc04 100644
--- a/src/couch/src/couch_key_tree.erl
+++ b/src/couch/src/couch_key_tree.erl
@@ -113,7 +113,7 @@ merge_tree([{Depth, Nodes} | Rest], {IDepth, INodes} = Tree, MergeAcc) ->
% value that's used throughout this module.
case merge_at([Nodes], Depth - IDepth, [INodes]) of
{[Merged], Result} ->
- NewDepth = erlang:min(Depth, IDepth),
+ NewDepth = min(Depth, IDepth),
{Rest ++ [{NewDepth, Merged} | MergeAcc], Result};
fail ->
merge_tree(Rest, Tree, [{Depth, Nodes} | MergeAcc])
@@ -507,12 +507,12 @@ stem_tree(Depth, {Key, Val, Children}, Limit, Seen0) ->
{SeenAcc, LimitPosAcc, ChildAcc, BranchAcc} = Acc,
case stem_tree(Depth + 1, Child, Limit, SeenAcc) of
{NewSeenAcc, LimitPos, NewChild, NewBranches} ->
- NewLimitPosAcc = erlang:max(LimitPos, LimitPosAcc),
+ NewLimitPosAcc = max(LimitPos, LimitPosAcc),
NewChildAcc = [NewChild | ChildAcc],
NewBranchAcc = NewBranches ++ BranchAcc,
{NewSeenAcc, NewLimitPosAcc, NewChildAcc, NewBranchAcc};
{NewSeenAcc, LimitPos, NewBranches} ->
- NewLimitPosAcc = erlang:max(LimitPos, LimitPosAcc),
+ NewLimitPosAcc = max(LimitPos, LimitPosAcc),
NewBranchAcc = NewBranches ++ BranchAcc,
{NewSeenAcc, NewLimitPosAcc, ChildAcc, NewBranchAcc}
end
diff --git a/src/couch/src/couch_multidb_changes.erl b/src/couch/src/couch_multidb_changes.erl
index 2ed200314..bb8a3fe47 100644
--- a/src/couch/src/couch_multidb_changes.erl
+++ b/src/couch/src/couch_multidb_changes.erl
@@ -241,7 +241,7 @@ should_wait_for_shard_map(<<_/binary>>) ->
-spec register_with_event_server(pid()) -> reference().
register_with_event_server(Server) ->
- Ref = erlang:monitor(process, couch_event_server),
+ Ref = monitor(process, couch_event_server),
couch_event:register_all(Server),
Ref.
@@ -475,7 +475,7 @@ setup_all() ->
meck:expect(couch_db, close, 1, ok),
mock_changes_reader(),
% create process to stand in for couch_event_server
- % mocking erlang:monitor doesn't work, so give it real process to monitor
+ % mocking monitor doesn't work, so give it real process to monitor
EvtPid = spawn_link(fun() ->
receive
looper -> ok
@@ -709,7 +709,7 @@ t_handle_info_change_feed_exited_and_need_rescan(_) ->
t_spawn_changes_reader(_) ->
Pid = start_changes_reader(?DBNAME, 3),
- ?assert(erlang:is_process_alive(Pid)),
+ ?assert(is_process_alive(Pid)),
ChArgs = kill_mock_changes_reader_and_get_its_args(Pid),
?assertEqual({self(), ?DBNAME}, ChArgs),
?assert(meck:validate(couch_db)),
@@ -1135,7 +1135,7 @@ kill_mock_changes_reader_and_get_its_args(Pid) ->
{'DOWN', Ref, _, Pid, {Server, DbName}} ->
{Server, DbName}
after 1000 ->
- erlang:error(spawn_change_reader_timeout)
+ error(spawn_change_reader_timeout)
end.
mock_changes_reader() ->
diff --git a/src/couch/src/couch_native_process.erl b/src/couch/src/couch_native_process.erl
index c9280f1d7..9d555c8a4 100644
--- a/src/couch/src/couch_native_process.erl
+++ b/src/couch/src/couch_native_process.erl
@@ -111,7 +111,7 @@ handle_call({prompt, Data}, _From, State) ->
end.
handle_cast(garbage_collect, State) ->
- erlang:garbage_collect(),
+ garbage_collect(),
{noreply, State, State#evstate.idle};
handle_cast(stop, State) ->
{stop, normal, State};
@@ -120,7 +120,7 @@ handle_cast(_Msg, State) ->
handle_info(timeout, State) ->
couch_proc_manager:os_proc_idle(self()),
- erlang:garbage_collect(),
+ garbage_collect(),
{noreply, State, State#evstate.idle};
handle_info({'EXIT', _, normal}, State) ->
{noreply, State, State#evstate.idle};
@@ -478,6 +478,6 @@ to_binary(true) ->
to_binary(false) ->
false;
to_binary(Data) when is_atom(Data) ->
- list_to_binary(atom_to_list(Data));
+ atom_to_binary(Data);
to_binary(Data) ->
Data.
diff --git a/src/couch/src/couch_os_process.erl b/src/couch/src/couch_os_process.erl
index 59ceeca13..339c93f72 100644
--- a/src/couch/src/couch_os_process.erl
+++ b/src/couch/src/couch_os_process.erl
@@ -152,7 +152,7 @@ init([Command]) ->
couch_stats:increment_counter([couchdb, query_server, process_starts]),
spawn(fun() ->
% this ensure the real os process is killed when this process dies.
- erlang:monitor(process, Pid),
+ monitor(process, Pid),
killer(OsPid)
end),
{ok, OsProc, IdleLimit}.
@@ -191,7 +191,7 @@ handle_call({prompt, Data}, _From, #os_proc{idle = Idle} = OsProc) ->
end.
handle_cast(garbage_collect, #os_proc{idle = Idle} = OsProc) ->
- erlang:garbage_collect(),
+ garbage_collect(),
{noreply, OsProc, Idle};
handle_cast(stop, OsProc) ->
{stop, normal, OsProc};
@@ -201,7 +201,7 @@ handle_cast(Msg, #os_proc{idle = Idle} = OsProc) ->
handle_info(timeout, #os_proc{idle = Idle} = OsProc) ->
couch_proc_manager:os_proc_idle(self()),
- erlang:garbage_collect(),
+ garbage_collect(),
{noreply, OsProc, Idle};
handle_info({Port, {exit_status, 0}}, #os_proc{port = Port} = OsProc) ->
couch_log:info("OS Process terminated normally", []),
diff --git a/src/couch/src/couch_primary_sup.erl b/src/couch/src/couch_primary_sup.erl
index 32ee282d6..93a1d2112 100644
--- a/src/couch/src/couch_primary_sup.erl
+++ b/src/couch/src/couch_primary_sup.erl
@@ -18,6 +18,7 @@ start_link() ->
supervisor:start_link({local, couch_primary_services}, ?MODULE, []).
init([]) ->
+ ok = couch_bt_engine_cache:create_tables(),
Children =
[
{couch_task_status, {couch_task_status, start_link, []}, permanent, brutal_kill, worker,
@@ -45,7 +46,7 @@ init([]) ->
]
]},
permanent, 5000, worker, [ets_lru]}
- ] ++ couch_servers(),
+ ] ++ couch_bt_engine_cache:sup_children() ++ couch_servers(),
{ok, {{one_for_one, 10, 3600}, Children}}.
couch_servers() ->
diff --git a/src/couch/src/couch_proc_manager.erl b/src/couch/src/couch_proc_manager.erl
index d90463bf3..aa538e23e 100644
--- a/src/couch/src/couch_proc_manager.erl
+++ b/src/couch/src/couch_proc_manager.erl
@@ -162,7 +162,7 @@ handle_call({get_proc, #client{} = Client}, From, State) ->
{noreply, State};
handle_call({ret_proc, #proc{} = Proc}, From, State) ->
#proc{client = Ref, pid = Pid} = Proc,
- erlang:demonitor(Ref, [flush]),
+ demonitor(Ref, [flush]),
gen_server:reply(From, true),
case ets:lookup(?PROCS, Pid) of
[#proc{} = ProcInt] ->
@@ -615,7 +615,7 @@ make_proc(Pid, Lang, Mod) when is_binary(Lang) ->
{ok, Proc}.
assign_proc(Pid, #proc{client = undefined} = Proc0) when is_pid(Pid) ->
- Proc = Proc0#proc{client = erlang:monitor(process, Pid)},
+ Proc = Proc0#proc{client = monitor(process, Pid)},
% It's important to insert the proc here instead of doing an update_element
% as we might have updated the db_key or ddoc_keys in teach_ddoc/4
ets:insert(?PROCS, Proc),
@@ -730,13 +730,25 @@ remove_waiting_client(#client{wait_key = Key}) ->
ets:delete(?WAITERS, Key).
get_proc_config() ->
- Limit = config:get_boolean("query_server_config", "reduce_limit", true),
- Timeout = get_os_process_timeout(),
{[
- {<<"reduce_limit">>, Limit},
- {<<"timeout">>, Timeout}
+ {<<"reduce_limit">>, get_reduce_limit()},
+ {<<"reduce_limit_threshold">>, couch_query_servers:reduce_limit_threshold()},
+ {<<"reduce_limit_ratio">>, couch_query_servers:reduce_limit_ratio()},
+ {<<"timeout">>, get_os_process_timeout()}
]}.
+% Reduce limit is a tri-state value of true, false or log. The default value if
+% is true. That's also the value if anything other than those 3 values are
+% specified.
+%
+get_reduce_limit() ->
+ case config:get("query_server_config", "reduce_limit", "true") of
+ "false" -> false;
+ "log" -> log;
+ "true" -> true;
+ Other when is_list(Other) -> true
+ end.
+
get_hard_limit() ->
config:get_integer("query_server_config", "os_process_limit", 100).
diff --git a/src/couch/src/couch_query_servers.erl b/src/couch/src/couch_query_servers.erl
index 3b222e081..a204a767f 100644
--- a/src/couch/src/couch_query_servers.erl
+++ b/src/couch/src/couch_query_servers.erl
@@ -19,6 +19,7 @@
-export([filter_view/4]).
-export([finalize/2]).
-export([rewrite/3]).
+-export([reduce_limit_threshold/0, reduce_limit_ratio/0]).
-export([with_ddoc_proc/3, proc_prompt/2, ddoc_prompt/4, ddoc_proc_prompt/3, json_doc/1]).
@@ -278,7 +279,7 @@ sum_arrays(Else, _) ->
throw_sum_error(Else).
check_sum_overflow(InSize, OutSize, Sum) ->
- Overflowed = OutSize > 4906 andalso OutSize * 2 > InSize,
+ Overflowed = OutSize > reduce_limit_threshold() andalso OutSize * reduce_limit_ratio() > InSize,
case config:get("query_server_config", "reduce_limit", "true") of
"true" when Overflowed ->
Msg = log_sum_overflow(InSize, OutSize),
@@ -302,6 +303,12 @@ log_sum_overflow(InSize, OutSize) ->
couch_log:error(Msg, []),
Msg.
+reduce_limit_threshold() ->
+ config:get_integer("query_server_config", "reduce_limit_threshold", 5000).
+
+reduce_limit_ratio() ->
+ config:get_float("query_server_config", "reduce_limit_ratio", 2.0).
+
builtin_stats(_, []) ->
{0, 0, 0, 0, 0};
builtin_stats(_, [[_, First] | Rest]) ->
@@ -327,8 +334,8 @@ stat_values(Value, Acc) when is_tuple(Value), is_tuple(Acc) ->
{
Sum0 + Sum1,
Cnt0 + Cnt1,
- erlang:min(Min0, Min1),
- erlang:max(Max0, Max1),
+ min(Min0, Min1),
+ max(Max0, Max1),
Sqr0 + Sqr1
};
stat_values(Else, _Acc) ->
diff --git a/src/couch/src/couch_server.erl b/src/couch/src/couch_server.erl
index ca12a56fa..246cdd1cb 100644
--- a/src/couch/src/couch_server.erl
+++ b/src/couch/src/couch_server.erl
@@ -303,7 +303,12 @@ init([N]) ->
"couchdb", "update_lru_on_read", false
),
ok = config:listen_for_changes(?MODULE, N),
- ok = couch_file:init_delete_dir(RootDir),
+ % Spawn async .deleted files recursive cleaner, but only
+ % for the first sharded couch_server instance
+ case N of
+ 1 -> ok = couch_file:init_delete_dir(RootDir);
+ _ -> ok
+ end,
ets:new(couch_dbs(N), [
set,
protected,
@@ -400,7 +405,7 @@ handle_config_terminate(_Server, _Reason, N) ->
erlang:send_after(?RELISTEN_DELAY, whereis(?MODULE), {restart_config_listener, N}).
per_couch_server(X) ->
- erlang:max(1, X div num_servers()).
+ max(1, X div num_servers()).
all_databases() ->
{ok, DbList} = all_databases(
@@ -858,7 +863,7 @@ get_engine(Server, DbName) ->
[Engine] ->
{ok, Engine};
_ ->
- erlang:error(engine_conflict)
+ error(engine_conflict)
end.
get_possible_engines(DbName, RootDir, Engines) ->
diff --git a/src/couch/src/couch_stream.erl b/src/couch/src/couch_stream.erl
index ea375101f..2998cd3ff 100644
--- a/src/couch/src/couch_stream.erl
+++ b/src/couch/src/couch_stream.erl
@@ -185,7 +185,7 @@ init({Engine, OpenerPid, OpenerPriority, Options}) ->
end,
{ok, #stream{
engine = Engine,
- opener_monitor = erlang:monitor(process, OpenerPid),
+ opener_monitor = monitor(process, OpenerPid),
md5 = couch_hash:md5_hash_init(),
identity_md5 = couch_hash:md5_hash_init(),
encoding_fun = EncodingFun,
@@ -269,7 +269,7 @@ handle_call(close, _From, Stream) ->
StreamLen = WrittenLen + iolist_size(WriteBin2),
{do_finalize(NewEngine), StreamLen, IdenLen, Md5Final, IdenMd5Final}
end,
- erlang:demonitor(MonRef),
+ demonitor(MonRef),
{stop, normal, Result, Stream}.
handle_cast(_Msg, State) ->
diff --git a/src/couch/src/couch_task_status.erl b/src/couch/src/couch_task_status.erl
index 29ab73692..8577c304d 100644
--- a/src/couch/src/couch_task_status.erl
+++ b/src/couch/src/couch_task_status.erl
@@ -107,7 +107,7 @@ handle_call({add_task, TaskProps}, {From, _}, Server) ->
case ets:lookup(?MODULE, From) of
[] ->
true = ets:insert(?MODULE, {From, TaskProps}),
- erlang:monitor(process, From),
+ monitor(process, From),
{reply, ok, Server};
[_] ->
{reply, {add_task_error, already_registered}, Server}
@@ -130,7 +130,7 @@ handle_cast({update_status, Pid, NewProps}, Server) ->
{noreply, Server}.
handle_info({'DOWN', _MonitorRef, _Type, Pid, _Info}, Server) ->
- %% should we also erlang:demonitor(_MonitorRef), ?
+ %% should we also demonitor(_MonitorRef), ?
ets:delete(?MODULE, Pid),
{noreply, Server}.
diff --git a/src/couch/src/couch_util.erl b/src/couch/src/couch_util.erl
index bdd5c14f3..e92caab93 100644
--- a/src/couch/src/couch_util.erl
+++ b/src/couch/src/couch_util.erl
@@ -137,7 +137,7 @@ to_existing_atom(V) when is_list(V) ->
end;
to_existing_atom(V) when is_binary(V) ->
try
- list_to_existing_atom(?b2l(V))
+ binary_to_existing_atom(V)
catch
_:_ -> V
end;
@@ -147,7 +147,7 @@ to_existing_atom(V) when is_atom(V) ->
shutdown_sync(Pid) when not is_pid(Pid) ->
ok;
shutdown_sync(Pid) ->
- MRef = erlang:monitor(process, Pid),
+ MRef = monitor(process, Pid),
try
catch unlink(Pid),
catch exit(Pid, shutdown),
@@ -156,7 +156,7 @@ shutdown_sync(Pid) ->
ok
end
after
- erlang:demonitor(MRef, [flush])
+ demonitor(MRef, [flush])
end.
validate_utf8(Data) when is_list(Data) ->
@@ -208,31 +208,8 @@ to_hex(Binary) when is_binary(Binary) ->
to_hex(List) when is_list(List) ->
binary_to_list(to_hex_bin(list_to_binary(List))).
-% Optimized encode_hex/1 function from Erlang/OTP binary module starting with OTP 24+ [1].
-% One exception is we are emitting lower case hex characters instead of upper case ones.
-%
-% [1] https://github.com/erlang/otp/blob/master/lib/stdlib/src/binary.erl#L365.
-%
-
--define(HEX(X), (hex(X)):16).
-
-%% erlfmt-ignore
-to_hex_bin(Data) when byte_size(Data) rem 8 =:= 0 ->
- << <<?HEX(A), ?HEX(B), ?HEX(C), ?HEX(D), ?HEX(E), ?HEX(F), ?HEX(G), ?HEX(H)>> || <<A, B, C, D, E, F ,G, H>> <= Data >>;
-to_hex_bin(Data) when byte_size(Data) rem 7 =:= 0 ->
- << <<?HEX(A), ?HEX(B), ?HEX(C), ?HEX(D), ?HEX(E), ?HEX(F), ?HEX(G)>> || <<A, B, C, D, E, F, G>> <= Data >>;
-to_hex_bin(Data) when byte_size(Data) rem 6 =:= 0 ->
- << <<?HEX(A), ?HEX(B), ?HEX(C), ?HEX(D), ?HEX(E), ?HEX(F)>> || <<A, B, C, D, E, F>> <= Data >>;
-to_hex_bin(Data) when byte_size(Data) rem 5 =:= 0 ->
- << <<?HEX(A), ?HEX(B), ?HEX(C), ?HEX(D), ?HEX(E)>> || <<A, B, C, D, E>> <= Data >>;
-to_hex_bin(Data) when byte_size(Data) rem 4 =:= 0 ->
- << <<?HEX(A), ?HEX(B), ?HEX(C), ?HEX(D)>> || <<A, B, C, D>> <= Data >>;
-to_hex_bin(Data) when byte_size(Data) rem 3 =:= 0 ->
- << <<?HEX(A), ?HEX(B), ?HEX(C)>> || <<A, B, C>> <= Data >>;
-to_hex_bin(Data) when byte_size(Data) rem 2 =:= 0 ->
- << <<?HEX(A), ?HEX(B)>> || <<A,B>> <= Data >>;
to_hex_bin(Data) when is_binary(Data) ->
- << <<?HEX(N)>> || <<N>> <= Data >>.
+ binary:encode_hex(Data, lowercase).
parse_term(Bin) when is_binary(Bin) ->
parse_term(binary_to_list(Bin));
@@ -251,8 +228,14 @@ get_value(Key, List, Default) ->
Default
end.
-set_value(Key, List, Value) ->
- lists:keyreplace(Key, 1, List, {Key, Value}).
+% insert or update a {Key, Value} tuple in a list of tuples
+-spec set_value(Key, TupleList1, Value) -> TupleList2 when
+ Key :: term(),
+ TupleList1 :: [tuple()],
+ Value :: term(),
+ TupleList2 :: [tuple()].
+set_value(Key, TupleList1, Value) ->
+ lists:keystore(Key, 1, TupleList1, {Key, Value}).
get_nested_json_value({Props}, [Key | Keys]) ->
case couch_util:get_value(Key, Props, nil) of
@@ -446,16 +429,16 @@ to_binary(V) when is_list(V) ->
list_to_binary(io_lib:format("~p", [V]))
end;
to_binary(V) when is_atom(V) ->
- list_to_binary(atom_to_list(V));
+ atom_to_binary(V);
to_binary(V) ->
list_to_binary(io_lib:format("~p", [V])).
to_integer(V) when is_integer(V) ->
V;
to_integer(V) when is_list(V) ->
- erlang:list_to_integer(V);
+ list_to_integer(V);
to_integer(V) when is_binary(V) ->
- erlang:list_to_integer(binary_to_list(V)).
+ binary_to_integer(V).
to_list(V) when is_list(V) ->
V;
@@ -528,13 +511,15 @@ reorder_results(Keys, SortedResults, Default) ->
Map = maps:from_list(SortedResults),
[maps:get(Key, Map, Default) || Key <- Keys].
-url_strip_password(Url) ->
+url_strip_password(Url) when is_list(Url) ->
re:replace(
Url,
"(http|https|socks5)://([^:]+):[^@]+@(.*)$",
"\\1://\\2:*****@\\3",
[{return, list}]
- ).
+ );
+url_strip_password(Other) ->
+ Other.
encode_doc_id(#doc{id = Id}) ->
encode_doc_id(Id);
@@ -568,7 +553,7 @@ with_db(Db, Fun) ->
true ->
Fun(Db);
false ->
- erlang:error({invalid_db, Db})
+ error({invalid_db, Db})
end.
rfc1123_date() ->
@@ -645,7 +630,7 @@ find_in_binary(_B, <<>>) ->
find_in_binary(B, Data) ->
case binary:match(Data, [B], []) of
nomatch ->
- MatchLength = erlang:min(byte_size(B), byte_size(Data)),
+ MatchLength = min(byte_size(B), byte_size(Data)),
match_prefix_at_end(
binary:part(B, {0, MatchLength}),
binary:part(Data, {byte_size(Data), -MatchLength}),
@@ -739,7 +724,7 @@ ensure_loaded(_Module) ->
%% a function that does a receive as it would hijack incoming messages.
with_proc(M, F, A, Timeout) ->
{Pid, Ref} = spawn_monitor(fun() ->
- exit({reply, erlang:apply(M, F, A)})
+ exit({reply, apply(M, F, A)})
end),
receive
{'DOWN', Ref, process, Pid, {reply, Resp}} ->
@@ -747,7 +732,7 @@ with_proc(M, F, A, Timeout) ->
{'DOWN', Ref, process, Pid, Error} ->
{error, Error}
after Timeout ->
- erlang:demonitor(Ref, [flush]),
+ demonitor(Ref, [flush]),
{error, timeout}
end.
@@ -787,39 +772,9 @@ version_to_binary(Ver) when is_tuple(Ver) ->
version_to_binary(Ver) when is_list(Ver) ->
IsZero = fun(N) -> N == 0 end,
Ver1 = lists:reverse(lists:dropwhile(IsZero, lists:reverse(Ver))),
- Ver2 = [erlang:integer_to_list(N) || N <- Ver1],
+ Ver2 = [integer_to_list(N) || N <- Ver1],
?l2b(lists:join(".", Ver2)).
--compile({inline, [hex/1]}).
-
-%% erlfmt-ignore
-hex(X) ->
- % We are encoding hex directly as lower case ASCII here and it's just a lookup table
- % for all the 00..ff combinations. 0x00 -> "00", 0xf1-> "f1", etc.
- %
- % 00, ..., 0f,
- % .. ..
- % f0, ..., ff
- %
- element(X + 1, {
- 16#3030, 16#3031, 16#3032, 16#3033, 16#3034, 16#3035, 16#3036, 16#3037, 16#3038, 16#3039, 16#3061, 16#3062, 16#3063, 16#3064, 16#3065, 16#3066,
- 16#3130, 16#3131, 16#3132, 16#3133, 16#3134, 16#3135, 16#3136, 16#3137, 16#3138, 16#3139, 16#3161, 16#3162, 16#3163, 16#3164, 16#3165, 16#3166,
- 16#3230, 16#3231, 16#3232, 16#3233, 16#3234, 16#3235, 16#3236, 16#3237, 16#3238, 16#3239, 16#3261, 16#3262, 16#3263, 16#3264, 16#3265, 16#3266,
- 16#3330, 16#3331, 16#3332, 16#3333, 16#3334, 16#3335, 16#3336, 16#3337, 16#3338, 16#3339, 16#3361, 16#3362, 16#3363, 16#3364, 16#3365, 16#3366,
- 16#3430, 16#3431, 16#3432, 16#3433, 16#3434, 16#3435, 16#3436, 16#3437, 16#3438, 16#3439, 16#3461, 16#3462, 16#3463, 16#3464, 16#3465, 16#3466,
- 16#3530, 16#3531, 16#3532, 16#3533, 16#3534, 16#3535, 16#3536, 16#3537, 16#3538, 16#3539, 16#3561, 16#3562, 16#3563, 16#3564, 16#3565, 16#3566,
- 16#3630, 16#3631, 16#3632, 16#3633, 16#3634, 16#3635, 16#3636, 16#3637, 16#3638, 16#3639, 16#3661, 16#3662, 16#3663, 16#3664, 16#3665, 16#3666,
- 16#3730, 16#3731, 16#3732, 16#3733, 16#3734, 16#3735, 16#3736, 16#3737, 16#3738, 16#3739, 16#3761, 16#3762, 16#3763, 16#3764, 16#3765, 16#3766,
- 16#3830, 16#3831, 16#3832, 16#3833, 16#3834, 16#3835, 16#3836, 16#3837, 16#3838, 16#3839, 16#3861, 16#3862, 16#3863, 16#3864, 16#3865, 16#3866,
- 16#3930, 16#3931, 16#3932, 16#3933, 16#3934, 16#3935, 16#3936, 16#3937, 16#3938, 16#3939, 16#3961, 16#3962, 16#3963, 16#3964, 16#3965, 16#3966,
- 16#6130, 16#6131, 16#6132, 16#6133, 16#6134, 16#6135, 16#6136, 16#6137, 16#6138, 16#6139, 16#6161, 16#6162, 16#6163, 16#6164, 16#6165, 16#6166,
- 16#6230, 16#6231, 16#6232, 16#6233, 16#6234, 16#6235, 16#6236, 16#6237, 16#6238, 16#6239, 16#6261, 16#6262, 16#6263, 16#6264, 16#6265, 16#6266,
- 16#6330, 16#6331, 16#6332, 16#6333, 16#6334, 16#6335, 16#6336, 16#6337, 16#6338, 16#6339, 16#6361, 16#6362, 16#6363, 16#6364, 16#6365, 16#6366,
- 16#6430, 16#6431, 16#6432, 16#6433, 16#6434, 16#6435, 16#6436, 16#6437, 16#6438, 16#6439, 16#6461, 16#6462, 16#6463, 16#6464, 16#6465, 16#6466,
- 16#6530, 16#6531, 16#6532, 16#6533, 16#6534, 16#6535, 16#6536, 16#6537, 16#6538, 16#6539, 16#6561, 16#6562, 16#6563, 16#6564, 16#6565, 16#6566,
- 16#6630, 16#6631, 16#6632, 16#6633, 16#6634, 16#6635, 16#6636, 16#6637, 16#6638, 16#6639, 16#6661, 16#6662, 16#6663, 16#6664, 16#6665, 16#6666
- }).
-
verify_hash_names(HashAlgorithms, SupportedHashes) ->
verify_hash_names(HashAlgorithms, SupportedHashes, []).
verify_hash_names([], _, HashNames) ->
@@ -856,11 +811,11 @@ remove_sensitive_data(KVList) ->
lists:keyreplace(password, 1, KVList1, {password, <<"****">>}).
ejson_to_map(#{} = Val) ->
- maps:map(fun(_, V) -> ejson_to_map(V) end, Val);
+ #{K => ejson_to_map(V) || K := V <- Val};
ejson_to_map(Val) when is_list(Val) ->
- lists:map(fun(V) -> ejson_to_map(V) end, Val);
+ [ejson_to_map(V) || V <- Val];
ejson_to_map({Val}) when is_list(Val) ->
- maps:from_list(lists:map(fun({K, V}) -> {K, ejson_to_map(V)} end, Val));
+ #{K => ejson_to_map(V) || {K, V} <- Val};
ejson_to_map(Val) ->
Val.
diff --git a/src/couch/src/couch_uuids.erl b/src/couch/src/couch_uuids.erl
index 588136159..f007eab91 100644
--- a/src/couch/src/couch_uuids.erl
+++ b/src/couch/src/couch_uuids.erl
@@ -17,7 +17,7 @@
-export([start/0, stop/0]).
-export([new/0, random/0]).
-
+-export([v7_hex/0, v7_bin/0]).
-export([init/1]).
-export([handle_call/3, handle_cast/2, handle_info/2]).
@@ -44,6 +44,8 @@ init([]) ->
handle_call(create, _From, random) ->
{reply, random(), random};
+handle_call(create, _From, uuid_v7) ->
+ {reply, v7_hex(), uuid_v7};
handle_call(create, _From, {utc_random, ClockSeq}) ->
{UtcRandom, NewClockSeq} = utc_random(ClockSeq),
{reply, UtcRandom, {utc_random, NewClockSeq}};
@@ -84,6 +86,32 @@ handle_config_terminate(_Server, _Reason, _State) ->
gen_server:cast(?MODULE, change),
erlang:send_after(?RELISTEN_DELAY, whereis(?MODULE), restart_config_listener).
+%% UUID Version 7
+%% https://datatracker.ietf.org/doc/html/rfc9562#name-uuid-version-7
+%%
+%% 0 1 2 3
+%% 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+%% +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+%% | unix_ts_ms |
+%% +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+%% | unix_ts_ms | ver | rand_a |
+%% +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+%% |var| rand_b |
+%% +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+%% | rand_b |
+%% +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+%%
+%% ver = 0111 = 7
+%% var = 10 = 2
+%%
+v7_bin() ->
+ MSec = os:system_time(millisecond),
+ <<RandA:12, RandB:62, _:6>> = crypto:strong_rand_bytes(10),
+ <<MSec:48, 7:4, RandA:12, 2:2, RandB:62>>.
+
+v7_hex() ->
+ couch_util:to_hex_bin(v7_bin()).
+
new_prefix() ->
couch_util:to_hex((crypto:strong_rand_bytes(13))).
@@ -104,6 +132,8 @@ state() ->
{utc_id, UtcIdSuffix, ClockSeq};
sequential ->
{sequential, new_prefix(), inc()};
+ uuid_v7 ->
+ uuid_v7;
Unknown ->
throw({unknown_uuid_algorithm, Unknown})
end.
diff --git a/src/couch/src/test_util.erl b/src/couch/src/test_util.erl
index 430c54788..b8001840f 100644
--- a/src/couch/src/test_util.erl
+++ b/src/couch/src/test_util.erl
@@ -155,7 +155,7 @@ stop_sync(Name, Reason, Timeout) when is_atom(Name) ->
stop_sync(Pid, Reason, Timeout) when is_atom(Reason) and is_pid(Pid) ->
stop_sync(Pid, fun() -> exit(Pid, Reason) end, Timeout);
stop_sync(Pid, Fun, Timeout) when is_function(Fun) and is_pid(Pid) ->
- MRef = erlang:monitor(process, Pid),
+ MRef = monitor(process, Pid),
try
begin
catch unlink(Pid),
@@ -168,7 +168,7 @@ stop_sync(Pid, Fun, Timeout) when is_function(Fun) and is_pid(Pid) ->
end
end
after
- erlang:demonitor(MRef, [flush])
+ demonitor(MRef, [flush])
end;
stop_sync(_, _, _) ->
error(badarg).
@@ -380,7 +380,7 @@ load_applications_with_stats() ->
stats_file_to_app(File) ->
[_Desc, _Priv, App | _] = lists:reverse(filename:split(File)),
- erlang:list_to_atom(App).
+ list_to_atom(App).
calculate_start_order(Apps) ->
AllApps = calculate_start_order(sort_apps(Apps), []),
diff --git a/src/couch/test/eunit/couch_bt_engine_cache_test.erl b/src/couch/test/eunit/couch_bt_engine_cache_test.erl
new file mode 100644
index 000000000..0eade12a4
--- /dev/null
+++ b/src/couch/test/eunit/couch_bt_engine_cache_test.erl
@@ -0,0 +1,102 @@
+% Licensed under the Apache License, Version 2.0 (the "License"); you may not
+% use this file except in compliance with the License. You may obtain a copy of
+% the License at
+%
+% http://www.apache.org/licenses/LICENSE-2.0
+%
+% Unless required by applicable law or agreed to in writing, software
+% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+% License for the specific language governing permissions and limitations under
+% the License.
+
+-module(couch_bt_engine_cache_test).
+
+-include_lib("couch/include/couch_eunit.hrl").
+
+couch_bt_engine_cache_test_() ->
+ {
+ foreach,
+ fun setup/0,
+ fun teardown/1,
+ [
+ ?TDEF_FE(t_created),
+ ?TDEF_FE(t_insert_and_lookup),
+ ?TDEF_FE(t_decay_and_removal_works, 10),
+ ?TDEF_FE(t_pid_cleanup_works, 10)
+ ]
+ }.
+
+setup() ->
+ Ctx = test_util:start_applications([config]),
+ couch_bt_engine_cache:create_tables(),
+ #{shard_count := N} = couch_bt_engine_cache:info(),
+ Pids = lists:map(
+ fun(I) ->
+ {ok, Pid} = couch_bt_engine_cache:start_link(I),
+ Pid
+ end,
+ lists:seq(1, N)
+ ),
+ {Ctx, Pids}.
+
+teardown({Ctx, [_ | _] = Pids}) ->
+ lists:foreach(
+ fun(Pid) ->
+ catch unlink(Pid),
+ exit(Pid, kill)
+ end,
+ Pids
+ ),
+ clear_tables(),
+ config:delete("bt_engine_cache", "max_size", false),
+ config:delete("bt_engine_cache", "leave_percent", false),
+ test_util:stop_applications(Ctx).
+
+clear_tables() ->
+ lists:foreach(fun ets:delete/1, couch_bt_engine_cache:tables()).
+
+t_created(_) ->
+ Info = couch_bt_engine_cache:info(),
+ #{size := Size, memory := Mem, shard_count := N} = Info,
+ ?assert(N >= 16, "shard count is greater or equal to 16"),
+ ?assertEqual(0, Size),
+ ?assert(is_integer(Mem)),
+ ?assert(Mem >= 0).
+
+t_insert_and_lookup(_) ->
+ ?assertError(function_clause, couch_bt_engine_cache:insert(not_a_pid, 1, foo)),
+ ?assertError(function_clause, couch_bt_engine_cache:insert(self(), xyz, foo)),
+ ?assertMatch(#{size := 0}, couch_bt_engine_cache:info()),
+ ?assert(couch_bt_engine_cache:insert({pid, 42}, term)),
+ ?assertMatch(#{size := 1}, couch_bt_engine_cache:info()),
+ ?assertNot(couch_bt_engine_cache:insert({pid, 42}, term)),
+ ?assertEqual(term, couch_bt_engine_cache:lookup({pid, 42})),
+ ?assertEqual(undefined, couch_bt_engine_cache:lookup({pid, 43})).
+
+t_decay_and_removal_works(_) ->
+ config:set("bt_engine_cache", "leave_percent", "0", false),
+ Term = [foo, bar, baz, lists:seq(1, 100)],
+ [couch_bt_engine_cache:insert({pid, I}, Term) || I <- lists:seq(1, 10000)],
+ WaitFun = fun() ->
+ #{size := Size} = couch_bt_engine_cache:info(),
+ case Size > 0 of
+ true -> wait;
+ false -> ok
+ end
+ end,
+ test_util:wait(WaitFun, 7500),
+ ?assertMatch(#{size := 0}, couch_bt_engine_cache:info()).
+
+t_pid_cleanup_works(_) ->
+ Pid = spawn(fun() -> timer:sleep(2000) end),
+ [couch_bt_engine_cache:insert({Pid, I}, baz) || I <- lists:seq(1, 1000)],
+ WaitFun = fun() ->
+ #{size := Size} = couch_bt_engine_cache:info(),
+ case Size > 0 of
+ true -> wait;
+ false -> ok
+ end
+ end,
+ test_util:wait(WaitFun, 7500),
+ ?assertMatch(#{size := 0}, couch_bt_engine_cache:info()).
diff --git a/src/couch/test/eunit/couch_bt_engine_compactor_ev_tests.erl b/src/couch/test/eunit/couch_bt_engine_compactor_ev_tests.erl
index 007c74d06..803d6295f 100644
--- a/src/couch/test/eunit/couch_bt_engine_compactor_ev_tests.erl
+++ b/src/couch/test/eunit/couch_bt_engine_compactor_ev_tests.erl
@@ -264,7 +264,7 @@ run_successful_compaction(DbName) ->
{ok, ContinueFun} = ?EV_MOD:set_wait(init),
{ok, Db} = couch_db:open_int(DbName, []),
{ok, CPid} = couch_db:start_compact(Db),
- Ref = erlang:monitor(process, CPid),
+ Ref = monitor(process, CPid),
ContinueFun(CPid),
receive
{'DOWN', Ref, _, _, normal} -> ok
@@ -278,7 +278,7 @@ wait_db_cleared(Db) ->
wait_db_cleared(Db, 5).
wait_db_cleared(Db, N) when N < 0 ->
- erlang:error({db_clear_timeout, couch_db:name(Db)});
+ error({db_clear_timeout, couch_db:name(Db)});
wait_db_cleared(Db, N) ->
Tab = couch_server:couch_dbs(couch_db:name(Db)),
case ets:lookup(Tab, couch_db:name(Db)) of
@@ -299,7 +299,7 @@ wait_db_cleared(Db, N) ->
populate_db(_Db, NumDocs) when NumDocs =< 0 ->
ok;
populate_db(Db, NumDocs) ->
- String = [$a || _ <- lists:seq(1, erlang:min(NumDocs, 500))],
+ String = [$a || _ <- lists:seq(1, min(NumDocs, 500))],
Docs = lists:map(
fun(_) ->
couch_doc:from_json_obj(
diff --git a/src/couch/test/eunit/couch_bt_engine_compactor_tests.erl b/src/couch/test/eunit/couch_bt_engine_compactor_tests.erl
index 4ed57668e..a7fec17db 100644
--- a/src/couch/test/eunit/couch_bt_engine_compactor_tests.erl
+++ b/src/couch/test/eunit/couch_bt_engine_compactor_tests.erl
@@ -89,7 +89,7 @@ check_db_validity(DbName) ->
with_mecked_emsort(Fun) ->
meck:new(couch_emsort, [passthrough]),
- meck:expect(couch_emsort, iter, fun(_) -> erlang:error(kaboom) end),
+ meck:expect(couch_emsort, iter, fun(_) -> error(kaboom) end),
try
Fun()
after
@@ -131,7 +131,7 @@ wait_db_compact_done(_DbName, 0) ->
{line, ?LINE},
{reason, "DB compaction failed to finish"}
],
- erlang:error({assertion_failed, Failure});
+ error({assertion_failed, Failure});
wait_db_compact_done(DbName, N) ->
IsDone = couch_util:with_db(DbName, fun(Db) ->
not is_pid(couch_db:get_compactor_pid(Db))
diff --git a/src/couch/test/eunit/couch_btree_prop_tests.erl b/src/couch/test/eunit/couch_btree_prop_tests.erl
new file mode 100644
index 000000000..1a9bd4f75
--- /dev/null
+++ b/src/couch/test/eunit/couch_btree_prop_tests.erl
@@ -0,0 +1,225 @@
+% Licensed under the Apache License, Version 2.0 (the "License"); you may not
+% use this file except in compliance with the License. You may obtain a copy of
+% the License at
+%
+% http://www.apache.org/licenses/LICENSE-2.0
+%
+% Unless required by applicable law or agreed to in writing, software
+% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+% License for the specific language governing permissions and limitations under
+% the License.
+
+-module(couch_btree_prop_tests).
+
+-ifdef(WITH_PROPER).
+
+-export([
+ command/1,
+ initial_state/0,
+ next_state/3,
+ precondition/2,
+ postcondition/3,
+ query_modify/3,
+ lookup/1
+]).
+
+% Process dict keys
+-define(BTREE, btree).
+-define(BTREE_FILENAME, btree_filename).
+
+-include_lib("couch/include/couch_eunit_proper.hrl").
+-include_lib("couch/include/couch_eunit.hrl").
+
+btree_property_test_() ->
+ ?EUNIT_QUICKCHECK(90, 3000).
+
+%
+% Properties
+%
+
+prop_btree_() ->
+ ?FORALL(
+ Cmds,
+ commands(?MODULE),
+ begin
+ setup_btree(),
+ {Hist, St, Res} = run_commands(?MODULE, Cmds),
+ cleanup_btree(),
+ ?WHENFAIL(
+ on_failure(Hist, St, Res),
+ aggregate(command_names(Cmds), Res =:= ok)
+ )
+ end
+ ).
+
+%
+% Setup, teardown and proxy calls to couch_btree.
+%
+
+% PropEr is a bit awkward when it comes to test setup and teardown, so to make
+% everything easier use plain function calls in the test and keep the btree
+% state in the process dictionary.
+
+setup_btree() ->
+ Filename = ?tempfile(),
+ {ok, Fd} = couch_file:open(Filename, [create, overwrite]),
+ {ok, Bt} = couch_btree:open(nil, Fd, [{compression, none}]),
+ put(?BTREE, Bt),
+ put(?BTREE_FILENAME, Filename).
+
+cleanup_btree() ->
+ Bt = get(?BTREE),
+ Fd = couch_btree:get_fd(Bt),
+ ok = couch_file:close(Fd),
+ ok = file:delete(get(?BTREE_FILENAME)),
+ erase(?BTREE),
+ erase(?BTREE_FILENAME).
+
+get_btree() ->
+ Bt = get(?BTREE),
+ % Sanity check. The btree didn't somehow disappear.
+ true = couch_btree:is_btree(Bt),
+ Bt.
+
+update_btree(NewBt) ->
+ OldBt = get(?BTREE),
+ % Sanity check. Expect an old btree instance to exist.
+ true = couch_btree:is_btree(OldBt),
+ true = couch_btree:is_btree(NewBt),
+ put(?BTREE, NewBt),
+ ok.
+
+% add/2 and add_remove/3 call query_modify/4, so just test that
+%
+query_modify(Lookups, Inserts, Removes) ->
+ Bt = get_btree(),
+ {ok, QueryResults, Bt1} = couch_btree:query_modify(Bt, Lookups, Inserts, Removes),
+ ok = update_btree(Bt1),
+ {ok, QueryResults, Bt1}.
+
+lookup(Keys) ->
+ Bt = get_btree(),
+ couch_btree:lookup(Bt, Keys).
+
+foldl() ->
+ Fun = fun({K, V}, Acc) -> {ok, [{K, V} | Acc]} end,
+ {ok, _, Acc1} = couch_btree:foldl(get_btree(), Fun, []),
+ lists:reverse(Acc1).
+
+%
+% PropEr state callbacks
+%
+
+% Model the btree as a simple orddict.
+%
+initial_state() ->
+ orddict:new().
+
+command(Model) when is_list(Model) ->
+ frequency([
+ {1, {call, ?MODULE, query_modify, [keys(), kvs(), remove_keys()]}},
+ {1, {call, ?MODULE, lookup, [keys()]}}
+ ]).
+
+% These are called during command generation, the test with an actual model and
+% during shrinking to guide the shrinking behavior.
+%
+precondition(_Model, {call, ?MODULE, query_modify, [_, _, _]}) ->
+ true;
+precondition(Model, {call, ?MODULE, lookup, [Keys]}) ->
+ % Avoid exploring too many useless cases and only look up keys if we know
+ % we have some keys to look at
+ orddict:size(Model) > 0 andalso length(Keys) > 0.
+
+% Assuming the postcondition passed, advance to the next state
+%
+next_state(Model, _, {call, ?MODULE, query_modify, [_Lookups, Inserts, Removes]}) ->
+ model_add_remove(Model, Inserts, Removes);
+next_state(Model, _, {call, ?MODULE, lookup, [_]}) ->
+ Model.
+
+% The Model is *before* the call is applied. The Result is *after* the command
+% was applied to the actual btree we're testing. This is where the "model" vs
+% "real" btree check happens.
+%
+postcondition(Model, {call, ?MODULE, query_modify, [Lookups, Inserts, Removes]}, Result) ->
+ {ok, QueryResults, _Bt} = Result,
+ ModelUpdate = model_add_remove(Model, Inserts, Removes),
+ ModelLookup = model_query(Model, Lookups),
+ ModelLookup == lists:sort(QueryResults) andalso ModelUpdate == foldl();
+postcondition(Model, {call, ?MODULE, lookup, [Lookups]}, Result) ->
+ model_lookup(Model, Lookups) == Result.
+
+%
+% Generators
+%
+
+key() ->
+ integer(1, 1000).
+
+val() ->
+ elements([a, b, c]).
+
+kvs() ->
+ list({key(), val()}).
+
+keys() ->
+ list(key()).
+
+remove_keys() ->
+ % Bias a bit towards not removing keys
+ frequency([{4, []}, {1, keys()}]).
+
+%
+% Helper functions
+%
+
+% Model (orddict) helpers
+
+model_add_remove(Model, Inserts, Removes) ->
+ % Keep this in sync with the op_order/1 from the
+ % couch_btree model:
+ % op_order(fetch) -> 1;
+ % op_order(remove) -> 2;
+ % op_order(insert) -> 3.
+ Model1 = model_remove(Model, Removes),
+ Model2 = model_insert(Model1, Inserts),
+ Model2.
+
+model_insert(Model, KVs) ->
+ UsortFun = fun({K1, _}, {K2, _}) -> K1 =< K2 end,
+ FoldFun = fun({K, V}, M) -> orddict:store(K, V, M) end,
+ lists:foldl(FoldFun, Model, lists:usort(UsortFun, KVs)).
+
+model_remove(Model, Keys) ->
+ FoldFun = fun(K, M) -> orddict:erase(K, M) end,
+ lists:foldl(FoldFun, Model, lists:usort(Keys)).
+
+model_lookup(Model, Keys) ->
+ Fun =
+ fun(K) ->
+ case orddict:find(K, Model) of
+ {ok, V} -> {ok, {K, V}};
+ error -> not_found
+ end
+ end,
+ lists:map(Fun, Keys).
+
+model_query(Model, Keys) ->
+ Fun =
+ fun(K) ->
+ case orddict:find(K, Model) of
+ {ok, V} -> {ok, {K, V}};
+ error -> {not_found, {K, nil}}
+ end
+ end,
+ lists:sort(lists:map(Fun, Keys)).
+
+% Other helpers
+
+on_failure(History, St, Res) ->
+ Msg = "~nWHENFAIL: History: ~p\nState: ~p\nResult: ~p\n",
+ io:format(standard_error, Msg, [History, St, Res]).
+
+-endif.
diff --git a/src/couch/test/eunit/couch_btree_tests.erl b/src/couch/test/eunit/couch_btree_tests.erl
index 1ec92818b..f365a37cf 100644
--- a/src/couch/test/eunit/couch_btree_tests.erl
+++ b/src/couch/test/eunit/couch_btree_tests.erl
@@ -13,7 +13,6 @@
-module(couch_btree_tests).
-include_lib("couch/include/couch_eunit.hrl").
--include_lib("couch/include/couch_db.hrl").
-define(ROWS, 1000).
% seconds
@@ -30,6 +29,35 @@ setup() ->
setup_kvs(_) ->
setup().
+setup_kvs_with_cache(_) ->
+ {ok, Fd} = couch_file:open(?tempfile(), [create, overwrite]),
+ {ok, Btree} = couch_btree:open(nil, Fd, [
+ {compression, none},
+ {reduce, fun reduce_fun/2},
+ {cache_depth, 2}
+ ]),
+ {Fd, Btree}.
+
+setup_kvs_with_small_chunk_size(_) ->
+ % Less than a 1/4 than current default 1279
+ config:set("couchdb", "btree_chunk_size", "300", false),
+ {ok, Fd} = couch_file:open(?tempfile(), [create, overwrite]),
+ {ok, Btree} = couch_btree:open(nil, Fd, [
+ {compression, none},
+ {reduce, fun reduce_fun/2}
+ ]),
+ {Fd, Btree}.
+
+setup_kvs_with_large_chunk_size(_) ->
+ % About 4x than current default 1279
+ config:set("couchdb", "btree_chunk_size", "5000", false),
+ {ok, Fd} = couch_file:open(?tempfile(), [create, overwrite]),
+ {ok, Btree} = couch_btree:open(nil, Fd, [
+ {compression, none},
+ {reduce, fun reduce_fun/2}
+ ]),
+ {Fd, Btree}.
+
setup_red() ->
{_, EvenOddKVs} = lists:foldl(
fun(Idx, {Key, Acc}) ->
@@ -48,6 +76,7 @@ setup_red(_) ->
setup_red().
teardown(Fd) when is_pid(Fd) ->
+ config:delete("couchdb", "btree_chunk_size", false),
ok = couch_file:close(Fd);
teardown({Fd, _}) ->
teardown(Fd).
@@ -81,7 +110,7 @@ btree_open_test_() ->
{ok, Btree} = couch_btree:open(nil, Fd, [{compression, none}]),
{
"Ensure that created btree is really a btree record",
- ?_assert(is_record(Btree, btree))
+ ?_assert(couch_btree:is_btree(Btree))
}.
sorted_kvs_test_() ->
@@ -105,7 +134,7 @@ sorted_kvs_test_() ->
rsorted_kvs_test_() ->
Sorted = [{Seq, rand:uniform()} || Seq <- lists:seq(1, ?ROWS)],
Funs = kvs_test_funs(),
- Reversed = Sorted,
+ Reversed = lists:reverse(Sorted),
{
"BTree with backward sorted keys",
{
@@ -140,6 +169,60 @@ shuffled_kvs_test_() ->
}
}.
+sorted_kvs_with_cache_test_() ->
+ Funs = kvs_test_funs(),
+ Sorted = [{Seq, rand:uniform()} || Seq <- lists:seq(1, ?ROWS)],
+ {
+ "BTree with a cache and sorted keys",
+ {
+ setup,
+ fun() -> test_util:start_couch() end,
+ fun test_util:stop/1,
+ {
+ foreachx,
+ fun setup_kvs_with_cache/1,
+ fun teardown/2,
+ [{Sorted, Fun} || Fun <- Funs]
+ }
+ }
+ }.
+
+sorted_kvs_small_chunk_size_test_() ->
+ Funs = kvs_test_funs(),
+ Sorted = [{Seq, rand:uniform()} || Seq <- lists:seq(1, ?ROWS)],
+ {
+ "BTree with a small chunk size and sorted keys",
+ {
+ setup,
+ fun() -> test_util:start_couch() end,
+ fun test_util:stop/1,
+ {
+ foreachx,
+ fun setup_kvs_with_small_chunk_size/1,
+ fun teardown/2,
+ [{Sorted, Fun} || Fun <- Funs]
+ }
+ }
+ }.
+
+sorted_kvs_large_chunk_size_test_() ->
+ Funs = kvs_test_funs(),
+ Sorted = [{Seq, rand:uniform()} || Seq <- lists:seq(1, ?ROWS)],
+ {
+ "BTree with a large chunk size and sorted keys",
+ {
+ setup,
+ fun() -> test_util:start_couch() end,
+ fun test_util:stop/1,
+ {
+ foreachx,
+ fun setup_kvs_with_large_chunk_size/1,
+ fun teardown/2,
+ [{Sorted, Fun} || Fun <- Funs]
+ }
+ }
+ }.
+
reductions_test_() ->
{
"BTree reductions",
@@ -189,10 +272,10 @@ reductions_test_() ->
}.
should_set_fd_correctly(_, {Fd, Btree}) ->
- ?_assertMatch(Fd, Btree#btree.fd).
+ ?_assertMatch(Fd, couch_btree:get_fd(Btree)).
should_set_root_correctly(_, {_, Btree}) ->
- ?_assertMatch(nil, Btree#btree.root).
+ ?_assertMatch(nil, couch_btree:get_state(Btree)).
should_create_zero_sized_btree(_, {_, Btree}) ->
?_assertMatch(0, couch_btree:size(Btree)).
@@ -200,7 +283,7 @@ should_create_zero_sized_btree(_, {_, Btree}) ->
should_set_reduce_option(_, {_, Btree}) ->
ReduceFun = fun reduce_fun/2,
Btree1 = couch_btree:set_options(Btree, [{reduce, ReduceFun}]),
- ?_assertMatch(ReduceFun, Btree1#btree.reduce).
+ ?_assertMatch(ReduceFun, couch_btree:get_reduce_fun(Btree1)).
should_fold_over_empty_btree(_, {_, Btree}) ->
{ok, _, EmptyRes} = couch_btree:foldl(Btree, fun(_, X) -> {ok, X + 1} end, 0),
@@ -228,7 +311,7 @@ should_have_lesser_size_than_file(Fd, Btree) ->
should_keep_root_pointer_to_kp_node(Fd, Btree) ->
?_assertMatch(
{ok, {kp_node, _}},
- couch_file:pread_term(Fd, element(1, Btree#btree.root))
+ couch_file:pread_term(Fd, element(1, couch_btree:get_state(Btree)))
).
should_remove_all_keys(KeyValues, Btree) ->
@@ -615,18 +698,15 @@ test_key_access(Btree, List) ->
FoldFun = fun(Element, {[HAcc | TAcc], Count}) ->
case Element == HAcc of
true -> {ok, {TAcc, Count + 1}};
- _ -> {ok, {TAcc, Count + 1}}
+ _ -> {ok, {TAcc, Count}}
end
end,
Length = length(List),
Sorted = lists:sort(List),
{ok, _, {[], Length}} = couch_btree:foldl(Btree, FoldFun, {Sorted, 0}),
- {ok, _, {[], Length}} = couch_btree:fold(
- Btree,
- FoldFun,
- {Sorted, 0},
- [{dir, rev}]
- ),
+ Reversed = lists:reverse(Sorted),
+ RevOpts = [{dir, rev}],
+ {ok, _, {[], Length}} = couch_btree:fold(Btree, FoldFun, {Reversed, 0}, RevOpts),
ok.
test_lookup_access(Btree, KeyValues) ->
diff --git a/src/couch/test/eunit/couch_changes_tests.erl b/src/couch/test/eunit/couch_changes_tests.erl
index bbeeac26a..917689e86 100644
--- a/src/couch/test/eunit/couch_changes_tests.erl
+++ b/src/couch/test/eunit/couch_changes_tests.erl
@@ -1654,7 +1654,7 @@ wait_finished({_, ConsumerRef}) ->
{'DOWN', ConsumerRef, _, _, Msg} when Msg == normal; Msg == ok ->
ok;
{'DOWN', ConsumerRef, _, _, Msg} ->
- erlang:error(
+ error(
{consumer_died, [
{module, ?MODULE},
{line, ?LINE},
@@ -1662,7 +1662,7 @@ wait_finished({_, ConsumerRef}) ->
]}
)
after ?TIMEOUT ->
- erlang:error(
+ error(
{consumer_died, [
{module, ?MODULE},
{line, ?LINE},
@@ -1752,7 +1752,7 @@ maybe_pause(Parent, Acc) ->
Parent ! {ok, Ref},
throw({stop, Acc});
V when V /= updated ->
- erlang:error(
+ error(
{assertion_failed, [
{module, ?MODULE},
{line, ?LINE},
diff --git a/src/couch/test/eunit/couch_file_tests.erl b/src/couch/test/eunit/couch_file_tests.erl
index 5b7481636..c138a9c0a 100644
--- a/src/couch/test/eunit/couch_file_tests.erl
+++ b/src/couch/test/eunit/couch_file_tests.erl
@@ -946,3 +946,86 @@ legacy_stats() ->
reset_legacy_checksum_stats() ->
Counter = couch_stats:sample([couchdb, legacy_checksums]),
couch_stats:decrement_counter([couchdb, legacy_checksums], Counter).
+
+write_header_sync_test_() ->
+ {
+ "Test sync options for write_header",
+ {
+ setup,
+ fun test_util:start_couch/0,
+ fun test_util:stop_couch/1,
+ {
+ foreach,
+ fun unlinked_setup/0,
+ fun teardown/1,
+ [
+ ?TDEF_FE(should_handle_sync_option),
+ ?TDEF_FE(should_not_sync_by_default),
+ ?TDEF_FE(should_handle_error_of_the_first_sync),
+ ?TDEF_FE(should_handle_error_of_the_second_sync),
+ ?TDEF_FE(should_handle_error_of_the_file_write)
+ ]
+ }
+ }
+ }.
+
+unlinked_setup() ->
+ Self = self(),
+ ReqId = make_ref(),
+ meck:new(file, [passthrough, unstick]),
+ spawn(fun() ->
+ {ok, Fd} = couch_file:open(?tempfile(), [create, overwrite]),
+ Self ! {ReqId, Fd}
+ end),
+ receive
+ {ReqId, Result} -> Result
+ end.
+
+should_handle_sync_option(Fd) ->
+ ok = couch_file:write_header(Fd, {<<"some_data">>, 32}, [sync]),
+ ?assertMatch({ok, {<<"some_data">>, 32}}, couch_file:read_header(Fd)),
+ ?assertEqual(2, meck:num_calls(file, datasync, ['_'])),
+ ok.
+
+should_not_sync_by_default(Fd) ->
+ ok = couch_file:write_header(Fd, {<<"some_data">>, 32}),
+ ?assertMatch({ok, {<<"some_data">>, 32}}, couch_file:read_header(Fd)),
+ ?assertEqual(0, meck:num_calls(file, datasync, ['_'])),
+ ok.
+
+should_handle_error_of_the_first_sync(Fd) ->
+ meck:expect(
+ file,
+ datasync,
+ ['_'],
+ meck:val({error, terminated})
+ ),
+ ?assertEqual({error, terminated}, couch_file:write_header(Fd, {<<"some_data">>, 32}, [sync])),
+ ?assertEqual(1, meck:num_calls(file, datasync, ['_'])),
+ ok.
+
+should_handle_error_of_the_second_sync(Fd) ->
+ meck:expect(
+ file,
+ datasync,
+ ['_'],
+ meck:seq([
+ meck:val(ok),
+ meck:val({error, terminated})
+ ])
+ ),
+ ?assertEqual({error, terminated}, couch_file:write_header(Fd, {<<"some_data">>, 32}, [sync])),
+ ?assertEqual(2, meck:num_calls(file, datasync, ['_'])),
+ ok.
+
+should_handle_error_of_the_file_write(Fd) ->
+ meck:expect(
+ file,
+ write,
+ ['_', '_'],
+ meck:val({error, terminated})
+ ),
+ ?assertEqual({error, terminated}, couch_file:write_header(Fd, {<<"some_data">>, 32}, [sync])),
+ ?assertEqual(1, meck:num_calls(file, datasync, ['_'])),
+ ?assertEqual(1, meck:num_calls(file, write, ['_', '_'])),
+ ok.
diff --git a/src/couch/test/eunit/couch_index_tests.erl b/src/couch/test/eunit/couch_index_tests.erl
index 368f7a059..3c078ca15 100644
--- a/src/couch/test/eunit/couch_index_tests.erl
+++ b/src/couch/test/eunit/couch_index_tests.erl
@@ -245,7 +245,7 @@ tracer_new() ->
ok.
tracer_delete() ->
- dbg:stop_clear(),
+ dbg:stop(),
(catch ets:delete(?MODULE)),
ok.
diff --git a/src/couch/test/eunit/couch_query_servers_tests.erl b/src/couch/test/eunit/couch_query_servers_tests.erl
index 1ade40b67..a2fffb446 100644
--- a/src/couch/test/eunit/couch_query_servers_tests.erl
+++ b/src/couch/test/eunit/couch_query_servers_tests.erl
@@ -16,96 +16,110 @@
-include_lib("couch/include/couch_eunit.hrl").
setup() ->
- meck:new([config, couch_log]).
+ meck:new(couch_log, [passthrough]),
+ Ctx = test_util:start_couch([ioq]),
+ config:set("query_server_config", "reduce_limit", "true", false),
+ config:set("log", "level", "info", false),
+ Ctx.
-teardown(_) ->
+teardown(Ctx) ->
+ config:delete("query_server_config", "reduce_limit", true),
+ config:delete("query_server_config", "reduce_limit_threshold", true),
+ config:delete("query_server_config", "reduce_limit_ratio", true),
+ config:delete("log", "level", false),
+ test_util:stop_couch(Ctx),
meck:unload().
-setup_oom() ->
- test_util:start_couch([ioq]).
-
-teardown_oom(Ctx) ->
- meck:unload(),
- test_util:stop_couch(Ctx).
-
-sum_overflow_test_() ->
+query_server_limits_test_() ->
{
- "Test overflow detection in the _sum reduce function",
+ "Test overflow detection and batch splitting in query server",
{
- setup,
+ foreach,
fun setup/0,
fun teardown/1,
[
- fun should_return_error_on_overflow/0,
- fun should_return_object_on_log/0,
- fun should_return_object_on_false/0
- ]
- }
- }.
-
-filter_oom_test_() ->
- {
- "Test recovery from oom in filters",
- {
- setup,
- fun setup_oom/0,
- fun teardown_oom/1,
- [
- fun should_split_large_batches/0
+ ?TDEF_FE(builtin_should_return_error_on_overflow),
+ ?TDEF_FE(builtin_should_not_return_error_with_generous_overflow_threshold),
+ ?TDEF_FE(builtin_should_not_return_error_with_generous_overflow_ratio),
+ ?TDEF_FE(builtin_should_return_object_on_log),
+ ?TDEF_FE(builtin_should_return_object_on_false),
+ ?TDEF_FE(js_reduce_should_return_error_on_overflow),
+ ?TDEF_FE(js_reduce_should_return_object_on_log),
+ ?TDEF_FE(js_reduce_should_return_object_on_false),
+ ?TDEF_FE(should_split_large_batches)
]
}
}.
-should_return_error_on_overflow() ->
- meck:reset([config, couch_log]),
- meck:expect(
- config,
- get,
- ["query_server_config", "reduce_limit", "true"],
- "true"
- ),
- meck:expect(couch_log, error, ['_', '_'], ok),
+builtin_should_return_error_on_overflow(_) ->
+ config:set("query_server_config", "reduce_limit", "true", false),
+ meck:reset(couch_log),
KVs = gen_sum_kvs(),
{ok, [Result]} = couch_query_servers:reduce(<<"foo">>, [<<"_sum">>], KVs),
?assertMatch({[{<<"error">>, <<"builtin_reduce_error">>} | _]}, Result),
- ?assert(meck:called(config, get, '_')),
?assert(meck:called(couch_log, error, '_')).
-should_return_object_on_log() ->
- meck:reset([config, couch_log]),
- meck:expect(
- config,
- get,
- ["query_server_config", "reduce_limit", "true"],
- "log"
- ),
- meck:expect(couch_log, error, ['_', '_'], ok),
+builtin_should_not_return_error_with_generous_overflow_threshold(_) ->
+ config:set("query_server_config", "reduce_limit", "true", false),
+ config:set_integer("query_server_config", "reduce_limit_threshold", 1000000, false),
+ meck:reset(couch_log),
+ KVs = gen_sum_kvs(),
+ {ok, [Result]} = couch_query_servers:reduce(<<"foo">>, [<<"_sum">>], KVs),
+ ?assertNotMatch({[{<<"error">>, <<"builtin_reduce_error">>} | _]}, Result).
+
+builtin_should_not_return_error_with_generous_overflow_ratio(_) ->
+ config:set("query_server_config", "reduce_limit", "true", false),
+ config:set_float("query_server_config", "reduce_limit_ratio", 0.1, false),
+ meck:reset(couch_log),
+ KVs = gen_sum_kvs(),
+ {ok, [Result]} = couch_query_servers:reduce(<<"foo">>, [<<"_sum">>], KVs),
+ ?assertNotMatch({[{<<"error">>, <<"builtin_reduce_error">>} | _]}, Result).
+
+builtin_should_return_object_on_log(_) ->
+ config:set("query_server_config", "reduce_limit", "log", false),
+ meck:reset(couch_log),
KVs = gen_sum_kvs(),
{ok, [Result]} = couch_query_servers:reduce(<<"foo">>, [<<"_sum">>], KVs),
?assertMatch({[_ | _]}, Result),
Keys = [K || {K, _} <- element(1, Result)],
?assert(not lists:member(<<"error">>, Keys)),
- ?assert(meck:called(config, get, '_')),
?assert(meck:called(couch_log, error, '_')).
-should_return_object_on_false() ->
- meck:reset([config, couch_log]),
- meck:expect(
- config,
- get,
- ["query_server_config", "reduce_limit", "true"],
- "false"
- ),
- meck:expect(couch_log, error, ['_', '_'], ok),
+builtin_should_return_object_on_false(_) ->
+ config:set("query_server_config", "reduce_limit", "false", false),
+ meck:reset(couch_log),
KVs = gen_sum_kvs(),
{ok, [Result]} = couch_query_servers:reduce(<<"foo">>, [<<"_sum">>], KVs),
?assertMatch({[_ | _]}, Result),
Keys = [K || {K, _} <- element(1, Result)],
?assert(not lists:member(<<"error">>, Keys)),
- ?assert(meck:called(config, get, '_')),
?assertNot(meck:called(couch_log, error, '_')).
-should_split_large_batches() ->
+js_reduce_should_return_error_on_overflow(_) ->
+ config:set("query_server_config", "reduce_limit", "true", false),
+ meck:reset(couch_log),
+ KVs = gen_sum_kvs(),
+ {ok, [Result]} = couch_query_servers:reduce(<<"javascript">>, [sum_js()], KVs),
+ ?assertMatch({[{reduce_overflow_error, <<"Reduce output must shrink", _/binary>>}]}, Result),
+ ?assert(meck:called(couch_log, error, '_')).
+
+js_reduce_should_return_object_on_log(_) ->
+ config:set("query_server_config", "reduce_limit", "log", false),
+ meck:reset(couch_log),
+ KVs = gen_sum_kvs(),
+ {ok, [Result]} = couch_query_servers:reduce(<<"javascript">>, [sum_js()], KVs),
+ ?assertMatch([<<"result">>, [_ | _]], Result),
+ ?assert(meck:called(couch_log, info, '_')).
+
+js_reduce_should_return_object_on_false(_) ->
+ config:set("query_server_config", "reduce_limit", "false", false),
+ meck:reset(couch_log),
+ KVs = gen_sum_kvs(),
+ {ok, [Result]} = couch_query_servers:reduce(<<"javascript">>, [sum_js()], KVs),
+ ?assertMatch([<<"result">>, [_ | _]], Result),
+ ?assertNot(meck:called(couch_log, info, '_')).
+
+should_split_large_batches(_) ->
Req = {json_req, {[]}},
Db = <<"somedb">>,
DDoc = #doc{
@@ -152,3 +166,13 @@ gen_sum_kvs() ->
end,
lists:seq(1, 10)
).
+
+sum_js() ->
+ % Don't do this in real views
+ <<
+ "\n"
+ " function(keys, vals, rereduce) {\n"
+ " return ['result', vals.concat(vals)]\n"
+ " }\n"
+ " "
+ >>.
diff --git a/src/couch/test/eunit/couch_server_tests.erl b/src/couch/test/eunit/couch_server_tests.erl
index a43106d89..77ddfde21 100644
--- a/src/couch/test/eunit/couch_server_tests.erl
+++ b/src/couch/test/eunit/couch_server_tests.erl
@@ -224,7 +224,7 @@ t_interleaved_create_delete_open(DbName) ->
% Now monitor and resume the couch_server and assert that
% couch_server does not crash while processing OpenResultMsg
- CSRef = erlang:monitor(process, CouchServer),
+ CSRef = monitor(process, CouchServer),
erlang:resume_process(CouchServer),
check_monitor_not_triggered(CSRef),
@@ -253,7 +253,7 @@ get_opener_pid(DbName) ->
wait_for_open_async_result(CouchServer, Opener) ->
WaitFun = fun() ->
- {_, Messages} = erlang:process_info(CouchServer, messages),
+ {_, Messages} = process_info(CouchServer, messages),
Found = lists:foldl(
fun(Msg, Acc) ->
case Msg of
@@ -276,7 +276,7 @@ wait_for_open_async_result(CouchServer, Opener) ->
check_monitor_not_triggered(Ref) ->
receive
{'DOWN', Ref, _, _, Reason0} ->
- erlang:error({monitor_triggered, Reason0})
+ error({monitor_triggered, Reason0})
after 100 ->
ok
end.
@@ -286,5 +286,5 @@ get_next_message() ->
Msg ->
Msg
after 5000 ->
- erlang:error(timeout)
+ error(timeout)
end.
diff --git a/src/couch/test/eunit/couch_stream_tests.erl b/src/couch/test/eunit/couch_stream_tests.erl
index f29c04c82..6bc2c7952 100644
--- a/src/couch/test/eunit/couch_stream_tests.erl
+++ b/src/couch/test/eunit/couch_stream_tests.erl
@@ -124,7 +124,7 @@ should_stop_on_normal_exit_of_stream_opener({Fd, _}) ->
end,
?assertNot(is_process_alive(OpenerPid)),
% Verify the stream itself has also died
- StreamRef = erlang:monitor(process, StreamPid),
+ StreamRef = monitor(process, StreamPid),
receive
{'DOWN', StreamRef, _, _, _} -> ok
end,
diff --git a/src/couch/test/eunit/couch_task_status_tests.erl b/src/couch/test/eunit/couch_task_status_tests.erl
index e5d8ead98..90e25362a 100644
--- a/src/couch/test/eunit/couch_task_status_tests.erl
+++ b/src/couch/test/eunit/couch_task_status_tests.erl
@@ -181,7 +181,7 @@ loop() ->
end.
call(Pid, done) ->
- Ref = erlang:monitor(process, Pid),
+ Ref = monitor(process, Pid),
Pid ! {done, self()},
Res = wait(Pid),
receive
@@ -222,7 +222,7 @@ get_task_prop(Pid, Prop) ->
),
case couch_util:get_value(Prop, hd(Element), nil) of
nil ->
- erlang:error(
+ error(
{assertion_failed, [
{module, ?MODULE},
{line, ?LINE},
diff --git a/src/couch/test/eunit/couch_work_queue_tests.erl b/src/couch/test/eunit/couch_work_queue_tests.erl
index c41cf598e..85c3f1a3c 100644
--- a/src/couch/test/eunit/couch_work_queue_tests.erl
+++ b/src/couch/test/eunit/couch_work_queue_tests.erl
@@ -375,7 +375,7 @@ produce_term(Q, Producer, Term, Wait) ->
{item, Ref, Item} ->
Item
after ?TIMEOUT ->
- erlang:error(
+ error(
{assertion_failed, [
{module, ?MODULE},
{line, ?LINE},
@@ -395,7 +395,7 @@ produce(Q, Producer, Size, Wait) ->
{item, Ref, Item} ->
Item
after ?TIMEOUT ->
- erlang:error(
+ error(
{assertion_failed, [
{module, ?MODULE},
{line, ?LINE},
diff --git a/src/couch/test/eunit/couchdb_attachments_tests.erl b/src/couch/test/eunit/couchdb_attachments_tests.erl
index 5de1eae9e..103a02326 100644
--- a/src/couch/test/eunit/couchdb_attachments_tests.erl
+++ b/src/couch/test/eunit/couchdb_attachments_tests.erl
@@ -646,7 +646,7 @@ wait_compaction(DbName, Kind, Line) ->
end,
case test_util:wait(WaitFun, ?TIMEOUT) of
timeout ->
- erlang:error(
+ error(
{assertion_failed, [
{module, ?MODULE},
{line, Line},
diff --git a/src/couch/test/eunit/couchdb_file_compression_tests.erl b/src/couch/test/eunit/couchdb_file_compression_tests.erl
index 122900d4b..1016cd2de 100644
--- a/src/couch/test/eunit/couchdb_file_compression_tests.erl
+++ b/src/couch/test/eunit/couchdb_file_compression_tests.erl
@@ -222,7 +222,7 @@ wait_compaction(DbName, Kind, Line) ->
end,
case test_util:wait(WaitFun, ?TIMEOUT * 1000) of
timeout ->
- erlang:error(
+ error(
{assertion_failed, [
{module, ?MODULE},
{line, Line},
diff --git a/src/couch/test/eunit/couchdb_os_proc_pool.erl b/src/couch/test/eunit/couchdb_os_proc_pool.erl
index 1a8479497..e230e761a 100644
--- a/src/couch/test/eunit/couchdb_os_proc_pool.erl
+++ b/src/couch/test/eunit/couchdb_os_proc_pool.erl
@@ -562,7 +562,7 @@ get_client_proc({Pid, Ref}, ClientName) ->
receive
{proc, Ref, Proc} -> Proc
after ?TIMEOUT ->
- erlang:error(
+ error(
{assertion_failed, [
{module, ?MODULE},
{line, ?LINE},
@@ -574,7 +574,7 @@ get_client_proc({Pid, Ref}, ClientName) ->
end.
stop_client({Pid, Ref}) ->
- MRef = erlang:monitor(process, Pid),
+ MRef = monitor(process, Pid),
Pid ! stop,
receive
{stop, Ref} ->
@@ -583,12 +583,12 @@ stop_client({Pid, Ref}) ->
end,
ok
after ?TIMEOUT ->
- erlang:demonitor(MRef, [flush]),
+ demonitor(MRef, [flush]),
timeout
end.
kill_client({Pid, Ref}) ->
- MRef = erlang:monitor(process, Pid),
+ MRef = monitor(process, Pid),
Pid ! die,
receive
{die, Ref} ->
@@ -597,7 +597,7 @@ kill_client({Pid, Ref}) ->
end,
ok
after ?TIMEOUT ->
- erlang:demonitor(MRef, [flush]),
+ demonitor(MRef, [flush]),
timeout
end.
diff --git a/src/couch/test/eunit/couchdb_update_conflicts_tests.erl b/src/couch/test/eunit/couchdb_update_conflicts_tests.erl
index 0722103a4..fc7884ed9 100644
--- a/src/couch/test/eunit/couchdb_update_conflicts_tests.erl
+++ b/src/couch/test/eunit/couchdb_update_conflicts_tests.erl
@@ -120,7 +120,7 @@ concurrent_doc_update(NumClients, DbName, InitRev) ->
]}
),
Pid = spawn_client(DbName, ClientDoc),
- {Value, Pid, erlang:monitor(process, Pid)}
+ {Value, Pid, monitor(process, Pid)}
end,
lists:seq(1, NumClients)
),
@@ -135,7 +135,7 @@ concurrent_doc_update(NumClients, DbName, InitRev) ->
{'DOWN', MonRef, process, Pid, conflict} ->
{AccConflicts + 1, AccValue};
{'DOWN', MonRef, process, Pid, Error} ->
- erlang:error(
+ error(
{assertion_failed, [
{module, ?MODULE},
{line, ?LINE},
@@ -146,7 +146,7 @@ concurrent_doc_update(NumClients, DbName, InitRev) ->
]}
)
after ?TIMEOUT div 2 ->
- erlang:error(
+ error(
{assertion_failed, [
{module, ?MODULE},
{line, ?LINE},
diff --git a/src/couch/test/eunit/couchdb_vhosts_tests.erl b/src/couch/test/eunit/couchdb_vhosts_tests.erl
index d1b758914..e005537cb 100644
--- a/src/couch/test/eunit/couchdb_vhosts_tests.erl
+++ b/src/couch/test/eunit/couchdb_vhosts_tests.erl
@@ -96,7 +96,7 @@ should_return_database_info({Url, DbName}) ->
{JsonBody} = jiffy:decode(Body),
?assert(proplists:is_defined(<<"db_name">>, JsonBody));
Else ->
- erlang:error(
+ error(
{assertion_failed, [
{module, ?MODULE},
{line, ?LINE},
@@ -120,7 +120,7 @@ should_return_revs_info({Url, DbName}) ->
{JsonBody} = jiffy:decode(Body),
?assert(proplists:is_defined(<<"_revs_info">>, JsonBody));
Else ->
- erlang:error(
+ error(
{assertion_failed, [
{module, ?MODULE},
{line, ?LINE},
@@ -146,7 +146,7 @@ should_return_virtual_request_path_field_in_request({Url, DbName}) ->
proplists:get_value(<<"requested_path">>, Json)
);
Else ->
- erlang:error(
+ error(
{assertion_failed, [
{module, ?MODULE},
{line, ?LINE},
@@ -170,7 +170,7 @@ should_return_real_request_path_field_in_request({Url, DbName}) ->
Path = ?l2b("/" ++ DbName ++ "/_design/doc1/_show/test"),
?assertEqual(Path, proplists:get_value(<<"path">>, Json));
Else ->
- erlang:error(
+ error(
{assertion_failed, [
{module, ?MODULE},
{line, ?LINE},
@@ -194,7 +194,7 @@ should_match_wildcard_vhost({Url, DbName}) ->
Path = ?l2b("/" ++ DbName ++ "/_design/doc1/_show/test"),
?assertEqual(Path, proplists:get_value(<<"path">>, Json));
Else ->
- erlang:error(
+ error(
{assertion_failed, [
{module, ?MODULE},
{line, ?LINE},
@@ -218,7 +218,7 @@ should_return_db_info_for_wildcard_vhost_for_custom_db({Url, DbName}) ->
{JsonBody} = jiffy:decode(Body),
?assert(proplists:is_defined(<<"db_name">>, JsonBody));
Else ->
- erlang:error(
+ error(
{assertion_failed, [
{module, ?MODULE},
{line, ?LINE},
@@ -243,7 +243,7 @@ should_replace_rewrite_variables_for_db_and_doc({Url, DbName}) ->
Path = ?l2b("/" ++ DbName ++ "/_design/doc1/_show/test"),
?assertEqual(Path, proplists:get_value(<<"path">>, Json));
Else ->
- erlang:error(
+ error(
{assertion_failed, [
{module, ?MODULE},
{line, ?LINE},
@@ -267,7 +267,7 @@ should_return_db_info_for_vhost_with_resource({Url, DbName}) ->
{JsonBody} = jiffy:decode(Body),
?assert(proplists:is_defined(<<"db_name">>, JsonBody));
Else ->
- erlang:error(
+ error(
{assertion_failed, [
{module, ?MODULE},
{line, ?LINE},
@@ -291,7 +291,7 @@ should_return_revs_info_for_vhost_with_resource({Url, DbName}) ->
{JsonBody} = jiffy:decode(Body),
?assert(proplists:is_defined(<<"_revs_info">>, JsonBody));
Else ->
- erlang:error(
+ error(
{assertion_failed, [
{module, ?MODULE},
{line, ?LINE},
@@ -311,7 +311,7 @@ should_return_db_info_for_vhost_with_wildcard_resource({Url, DbName}) ->
{JsonBody} = jiffy:decode(Body),
?assert(proplists:is_defined(<<"db_name">>, JsonBody));
Else ->
- erlang:error(
+ error(
{assertion_failed, [
{module, ?MODULE},
{line, ?LINE},
@@ -335,7 +335,7 @@ should_return_path_for_vhost_with_wildcard_host({Url, DbName}) ->
Path = ?l2b("/" ++ DbName ++ "/_design/doc1/_show/test"),
?assertEqual(Path, proplists:get_value(<<"path">>, Json));
Else ->
- erlang:error(
+ error(
{assertion_failed, [
{module, ?MODULE},
{line, ?LINE},
diff --git a/src/couch/test/eunit/couchdb_views_tests.erl b/src/couch/test/eunit/couchdb_views_tests.erl
index 0d32d7fcf..8b1950948 100644
--- a/src/couch/test/eunit/couchdb_views_tests.erl
+++ b/src/couch/test/eunit/couchdb_views_tests.erl
@@ -728,7 +728,7 @@ couchdb_1283() ->
),
% Start and pause compacton
- WaitRef = erlang:make_ref(),
+ WaitRef = make_ref(),
meck:expect(couch_mrview_index, compact, fun(Db, State, Opts) ->
receive
{WaitRef, From, init} -> ok
@@ -741,7 +741,7 @@ couchdb_1283() ->
end),
{ok, CPid} = gen_server:call(Pid, compact),
- CRef = erlang:monitor(process, CPid),
+ CRef = monitor(process, CPid),
?assert(is_process_alive(CPid)),
% Make sure that our compactor is waiting for us
@@ -773,7 +773,7 @@ wait_for_process_shutdown(Pid, ExpectedReason, Error) ->
{'DOWN', Pid, process, _, Reason} ->
?assertEqual(ExpectedReason, Reason)
after ?TIMEOUT ->
- erlang:error(
+ error(
{assertion_failed, [{module, ?MODULE}, {line, ?LINE}, Error]}
)
end.
@@ -994,7 +994,7 @@ compact_db(DbName) ->
wait_db_compact_done(DbName, ?WAIT_DELAY_COUNT).
wait_db_compact_done(_DbName, 0) ->
- erlang:error(
+ error(
{assertion_failed, [
{module, ?MODULE},
{line, ?LINE},
@@ -1020,7 +1020,7 @@ compact_view_group(DbName, DDocId) when is_binary(DDocId) ->
wait_view_compact_done(DbName, DDocId, 10).
wait_view_compact_done(_DbName, _DDocId, 0) ->
- erlang:error(
+ error(
{assertion_failed, [
{module, ?MODULE},
{line, ?LINE},
@@ -1052,7 +1052,7 @@ read_header(File) ->
stop_indexer(StopFun, Pid, Line, Reason) ->
case test_util:stop_sync(Pid, StopFun) of
timeout ->
- erlang:error(
+ error(
{assertion_failed, [
{module, ?MODULE},
{line, Line},
diff --git a/src/couch_event/src/couch_event_listener.erl b/src/couch_event/src/couch_event_listener.erl
index 22bf23327..87d17b633 100644
--- a/src/couch_event/src/couch_event_listener.erl
+++ b/src/couch_event/src/couch_event_listener.erl
@@ -47,7 +47,7 @@
term().
start(Mod, Arg, Options) ->
- Pid = erlang:spawn(?MODULE, do_init, [Mod, Arg, Options]),
+ Pid = spawn(?MODULE, do_init, [Mod, Arg, Options]),
{ok, Pid}.
start(Name, Mod, Arg, Options) ->
@@ -59,7 +59,7 @@ start(Name, Mod, Arg, Options) ->
end.
start_link(Mod, Arg, Options) ->
- Pid = erlang:spawn_link(?MODULE, do_init, [Mod, Arg, Options]),
+ Pid = spawn_link(?MODULE, do_init, [Mod, Arg, Options]),
{ok, Pid}.
start_link(Name, Mod, Arg, Options) ->
@@ -87,7 +87,7 @@ do_init(Module, Arg, Options) ->
{ok, State, Timeout} when is_integer(Timeout), Timeout >= 0 ->
?MODULE:loop(#st{module = Module, state = State}, Timeout);
Else ->
- erlang:exit(Else)
+ exit(Else)
end.
loop(St, Timeout) ->
@@ -109,7 +109,7 @@ maybe_name_process(Options) ->
true ->
ok;
{false, Pid} ->
- erlang:error({already_started, Pid})
+ error({already_started, Pid})
end;
none ->
ok
@@ -133,7 +133,7 @@ do_event(#st{module = Module, state = State} = St, DbName, Event) ->
{stop, Reason, NewState} ->
do_terminate(Reason, St#st{state = NewState});
Else ->
- erlang:error(Else)
+ error(Else)
end.
do_cast(#st{module = Module, state = State} = St, Message) ->
@@ -145,7 +145,7 @@ do_cast(#st{module = Module, state = State} = St, Message) ->
{stop, Reason, NewState} ->
do_terminate(Reason, St#st{state = NewState});
Else ->
- erlang:error(Else)
+ error(Else)
end.
do_info(#st{module = Module, state = State} = St, Message) ->
@@ -157,7 +157,7 @@ do_info(#st{module = Module, state = State} = St, Message) ->
{stop, Reason, NewState} ->
do_terminate(Reason, St#st{state = NewState});
Else ->
- erlang:error(Else)
+ error(Else)
end.
do_terminate(Reason, #st{module = Module, state = State}) ->
@@ -173,7 +173,7 @@ do_terminate(Reason, #st{module = Module, state = State}) ->
ignore -> normal;
Else -> Else
end,
- erlang:exit(Status).
+ exit(Status).
where({local, Name}) -> whereis(Name).
@@ -192,7 +192,7 @@ get_all_dbnames(Options) ->
end.
get_all_dbnames([], []) ->
- erlang:error(no_dbnames_provided);
+ error(no_dbnames_provided);
get_all_dbnames([], Acc) ->
lists:usort(convert_dbname_list(Acc));
get_all_dbnames([{dbname, DbName} | Rest], Acc) ->
@@ -209,4 +209,4 @@ convert_dbname_list([DbName | Rest]) when is_binary(DbName) ->
convert_dbname_list([DbName | Rest]) when is_list(DbName) ->
[list_to_binary(DbName) | convert_dbname_list(Rest)];
convert_dbname_list([DbName | _]) ->
- erlang:error({invalid_dbname, DbName}).
+ error({invalid_dbname, DbName}).
diff --git a/src/couch_event/src/couch_event_listener_mfa.erl b/src/couch_event/src/couch_event_listener_mfa.erl
index 5ec465cf7..55099c2c4 100644
--- a/src/couch_event/src/couch_event_listener_mfa.erl
+++ b/src/couch_event/src/couch_event_listener_mfa.erl
@@ -47,7 +47,7 @@ enter_loop(Mod, Func, State, Options) ->
Parent =
case proplists:get_value(parent, Options) of
P when is_pid(P) ->
- erlang:monitor(process, P),
+ monitor(process, P),
P;
_ ->
undefined
@@ -64,7 +64,7 @@ stop(Pid) ->
couch_event_listener:cast(Pid, shutdown).
init({Parent, Mod, Func, State}) ->
- erlang:monitor(process, Parent),
+ monitor(process, Parent),
{ok, #st{
mod = Mod,
func = Func,
@@ -86,7 +86,7 @@ handle_event(DbName, Event, #st{mod = Mod, func = Func, state = State} = St) ->
couch_log:error("~p: else in handle_event for db ~p, event ~p, else ~p", [
?MODULE, DbName, Event, Else
]),
- erlang:error(Else)
+ error(Else)
end
catch
Class:Reason:Stack ->
diff --git a/src/couch_event/src/couch_event_server.erl b/src/couch_event/src/couch_event_server.erl
index dfdf0ac02..f14730688 100644
--- a/src/couch_event/src/couch_event_server.erl
+++ b/src/couch_event/src/couch_event_server.erl
@@ -42,7 +42,7 @@ init(_) ->
handle_call({register, Pid, NewDbNames}, _From, St) ->
case maps:get(Pid, St#st.by_pid, undefined) of
undefined ->
- NewRef = erlang:monitor(process, Pid),
+ NewRef = monitor(process, Pid),
{reply, ok, register(St, NewRef, Pid, NewDbNames)};
{ReuseRef, OldDbNames} ->
unregister(St, Pid, OldDbNames),
@@ -53,7 +53,7 @@ handle_call({unregister, Pid}, _From, #st{by_pid = ByPid} = St) ->
undefined ->
{reply, not_registered, St};
{Ref, OldDbNames} ->
- erlang:demonitor(Ref, [flush]),
+ demonitor(Ref, [flush]),
{reply, ok, unregister(St, Pid, OldDbNames)}
end;
handle_call(Msg, From, St) ->
@@ -229,7 +229,7 @@ t_invalid_gen_server_messages(_) ->
kill_sync(Pid) ->
unlink(Pid),
- Ref = erlang:monitor(process, Pid),
+ Ref = monitor(process, Pid),
exit(Pid, kill),
receive
{'DOWN', Ref, _, _, _} -> ok
diff --git a/src/couch_index/src/couch_index.erl b/src/couch_index/src/couch_index.erl
index b8bb35183..0d0e62fb5 100644
--- a/src/couch_index/src/couch_index.erl
+++ b/src/couch_index/src/couch_index.erl
@@ -61,7 +61,7 @@ compact(Pid) ->
compact(Pid, Options) ->
{ok, CPid} = gen_server:call(Pid, compact),
case lists:member(monitor, Options) of
- true -> {ok, erlang:monitor(process, CPid)};
+ true -> {ok, monitor(process, CPid)};
false -> ok
end.
@@ -381,7 +381,7 @@ send_replies(Waiters, UpdateSeq, IdxState) ->
assert_signature_match(Mod, OldIdxState, NewIdxState) ->
case {Mod:get(signature, OldIdxState), Mod:get(signature, NewIdxState)} of
{Sig, Sig} -> ok;
- _ -> erlang:error(signature_mismatch)
+ _ -> error(signature_mismatch)
end.
commit_compacted(NewIdxState, State) ->
diff --git a/src/couch_index/src/couch_index_server.erl b/src/couch_index/src/couch_index_server.erl
index 973b06337..d4593ee0d 100644
--- a/src/couch_index/src/couch_index_server.erl
+++ b/src/couch_index/src/couch_index_server.erl
@@ -78,7 +78,7 @@ get_index(Module, <<"shards/", _/binary>> = DbName, DDoc) ->
{'DOWN', Ref, process, Pid, Error} ->
Error
after 61000 ->
- erlang:demonitor(Ref, [flush]),
+ demonitor(Ref, [flush]),
{error, timeout}
end;
get_index(Module, DbName, DDoc) when is_binary(DbName) ->
diff --git a/src/couch_index/src/couch_index_util.erl b/src/couch_index/src/couch_index_util.erl
index db8aad470..9a16d06d6 100644
--- a/src/couch_index/src/couch_index_util.erl
+++ b/src/couch_index/src/couch_index_util.erl
@@ -14,6 +14,7 @@
-export([root_dir/0, index_dir/2, index_file/3]).
-export([load_doc/3, sort_lib/1, hexsig/1]).
+-export([get_purge_checkpoints/2, cleanup_purges/3]).
-include_lib("couch/include/couch_db.hrl").
@@ -72,3 +73,49 @@ sort_lib([{LName, LCode} | Rest], LAcc) ->
hexsig(Sig) ->
couch_util:to_hex(Sig).
+
+% Helper function for indexes to get their purge checkpoints as signatures.
+%
+get_purge_checkpoints(DbName, Type) when is_binary(DbName), is_binary(Type) ->
+ couch_util:with_db(DbName, fun(Db) -> get_purge_checkpoints(Db, Type) end);
+get_purge_checkpoints(Db, Type) when is_binary(Type) ->
+ Prefix = <<?LOCAL_DOC_PREFIX, "purge-", Type:(byte_size(Type))/binary, "-">>,
+ PrefixSize = byte_size(Prefix),
+ FoldFun = fun(#doc{id = Id}, Acc) ->
+ case Id of
+ <<Prefix:PrefixSize/binary, Sig/binary>> -> {ok, Acc#{Sig => Id}};
+ _ -> {stop, Acc}
+ end
+ end,
+ Opts = [{start_key, Prefix}],
+ {ok, Signatures = #{}} = couch_db:fold_local_docs(Db, FoldFun, #{}, Opts),
+ Signatures.
+
+% Helper functions for indexes to clean their purge checkpoints.
+%
+cleanup_purges(DbName, #{} = Sigs, #{} = Checkpoints) when is_binary(DbName) ->
+ couch_util:with_db(DbName, fun(Db) ->
+ cleanup_purges(Db, Sigs, Checkpoints)
+ end);
+cleanup_purges(Db, #{} = Sigs, #{} = CheckpointsMap) ->
+ InactiveMap = maps:without(maps:keys(Sigs), CheckpointsMap),
+ InactiveCheckpoints = maps:values(InactiveMap),
+ DeleteFun = fun(DocId) -> delete_checkpoint(Db, DocId) end,
+ lists:foreach(DeleteFun, InactiveCheckpoints).
+
+delete_checkpoint(Db, DocId) ->
+ DbName = couch_db:name(Db),
+ LogMsg = "~p : deleting inactive purge checkpoint ~s : ~s",
+ couch_log:debug(LogMsg, [?MODULE, DbName, DocId]),
+ try couch_db:open_doc(Db, DocId, []) of
+ {ok, Doc = #doc{}} ->
+ Deleted = Doc#doc{deleted = true, body = {[]}},
+ couch_db:update_doc(Db, Deleted, [?ADMIN_CTX]);
+ {not_found, _} ->
+ ok
+ catch
+ Tag:Error ->
+ ErrLog = "~p : error deleting checkpoint ~s : ~s error: ~p:~p",
+ couch_log:error(ErrLog, [?MODULE, DbName, DocId, Tag, Error]),
+ ok
+ end.
diff --git a/src/couch_index/test/eunit/couch_index_ddoc_updated_tests.erl b/src/couch_index/test/eunit/couch_index_ddoc_updated_tests.erl
index cbdb71954..6b7fe5a4a 100644
--- a/src/couch_index/test/eunit/couch_index_ddoc_updated_tests.erl
+++ b/src/couch_index/test/eunit/couch_index_ddoc_updated_tests.erl
@@ -88,7 +88,7 @@ check_all_indexers_exit_on_ddoc_change({_Ctx, DbName}) ->
IndexesBefore = get_indexes_by_ddoc(DDocID, N),
?assertEqual(N, length(IndexesBefore)),
- AliveBefore = lists:filter(fun erlang:is_process_alive/1, IndexesBefore),
+ AliveBefore = lists:filter(fun is_process_alive/1, IndexesBefore),
?assertEqual(N, length(AliveBefore)),
% update ddoc
@@ -121,7 +121,7 @@ check_all_indexers_exit_on_ddoc_change({_Ctx, DbName}) ->
?assertEqual(0, length(IndexesAfter)),
%% assert that previously running indexes are gone
- AliveAfter = lists:filter(fun erlang:is_process_alive/1, IndexesBefore),
+ AliveAfter = lists:filter(fun is_process_alive/1, IndexesBefore),
?assertEqual(0, length(AliveAfter)),
ok
end).
diff --git a/src/couch_log/src/couch_log_config.erl b/src/couch_log/src/couch_log_config.erl
index c3fd8fe85..265e4d15f 100644
--- a/src/couch_log/src/couch_log_config.erl
+++ b/src/couch_log/src/couch_log_config.erl
@@ -108,7 +108,7 @@ transform(filter_fields, FieldsStr) ->
Default = [pid, registered_name, error_info, messages],
case parse_term(FieldsStr) of
{ok, List} when is_list(List) ->
- case lists:all(fun erlang:is_atom/1, List) of
+ case lists:all(fun is_atom/1, List) of
true ->
List;
false ->
diff --git a/src/couch_log/src/couch_log_trunc_io.erl b/src/couch_log/src/couch_log_trunc_io.erl
index c330edb33..72ce5390e 100644
--- a/src/couch_log/src/couch_log_trunc_io.erl
+++ b/src/couch_log/src/couch_log_trunc_io.erl
@@ -69,7 +69,7 @@ format(Fmt, Args, Max, Options) ->
couch_log_trunc_io_fmt:format(Fmt, Args, Max, Options)
catch
_What:_Why ->
- erlang:error(badarg, [Fmt, Args])
+ error(badarg, [Fmt, Args])
end.
%% @doc Returns an flattened list containing the ASCII representation of the given
@@ -114,7 +114,7 @@ print(Term, Max, Options) when is_list(Options) ->
print(Term, _Max, #print_options{force_strings = true}) when
not is_list(Term), not is_binary(Term), not is_atom(Term)
->
- erlang:error(badarg);
+ error(badarg);
print(_, Max, _Options) when Max < 0 -> {"...", 3};
print(_, _, #print_options{depth = 0}) ->
{"...", 3};
@@ -249,7 +249,7 @@ print(Fun, Max, _Options) when is_function(Fun) ->
L = erlang:fun_to_list(Fun),
case length(L) > Max of
true ->
- S = erlang:max(5, Max),
+ S = max(5, Max),
Res = string:substr(L, 1, S) ++ "..>",
{Res, length(Res)};
_ ->
@@ -347,7 +347,7 @@ list_bodyc(X, Max, Options, _Tuple) ->
{[$|, List], Len + 1}.
map_body(Map, Max, #print_options{depth = Depth}) when Max < 4; Depth =:= 0 ->
- case erlang:map_size(Map) of
+ case map_size(Map) of
0 -> {[], 0};
_ -> {"...", 3}
end;
@@ -474,7 +474,7 @@ alist([H | T], Max, Options = #print_options{force_strings = true}) when is_bina
{[List | Final], FLen + Len}
end;
alist(_, _, #print_options{force_strings = true}) ->
- erlang:error(badarg);
+ error(badarg);
alist([H | _L], _Max, _Options) ->
throw({unprintable, H});
alist(H, _Max, _Options) ->
diff --git a/src/couch_log/src/couch_log_trunc_io_fmt.erl b/src/couch_log/src/couch_log_trunc_io_fmt.erl
index 40f3248c2..3c772bd6d 100644
--- a/src/couch_log/src/couch_log_trunc_io_fmt.erl
+++ b/src/couch_log/src/couch_log_trunc_io_fmt.erl
@@ -56,10 +56,10 @@ format(FmtStr, Args, MaxLen, Opts) when is_list(FmtStr) ->
),
build2(Cs2, Count, MaxLen2 - StrLen);
false ->
- erlang:error(badarg)
+ error(badarg)
end;
format(_FmtStr, _Args, _MaxLen, _Opts) ->
- erlang:error(badarg).
+ error(badarg).
collect([$~ | Fmt0], Args0) ->
{C, Fmt1, Args1} = collect_cseq(Fmt0, Args0),
@@ -324,7 +324,7 @@ term(T, F, Adj, P0, Pad) ->
L = lists:flatlength(T),
P =
case P0 of
- none -> erlang:min(L, F);
+ none -> min(L, F);
_ -> P0
end,
if
@@ -501,10 +501,10 @@ unprefixed_integer(Int, F, Adj, Base, Pad, Lowercase) when
->
if
Int < 0 ->
- S = cond_lowercase(erlang:integer_to_list(-Int, Base), Lowercase),
+ S = cond_lowercase(integer_to_list(-Int, Base), Lowercase),
term([$- | S], F, Adj, none, Pad);
true ->
- S = cond_lowercase(erlang:integer_to_list(Int, Base), Lowercase),
+ S = cond_lowercase(integer_to_list(Int, Base), Lowercase),
term(S, F, Adj, none, Pad)
end.
@@ -516,10 +516,10 @@ prefixed_integer(Int, F, Adj, Base, Pad, Prefix, Lowercase) when
->
if
Int < 0 ->
- S = cond_lowercase(erlang:integer_to_list(-Int, Base), Lowercase),
+ S = cond_lowercase(integer_to_list(-Int, Base), Lowercase),
term([$-, Prefix | S], F, Adj, none, Pad);
true ->
- S = cond_lowercase(erlang:integer_to_list(Int, Base), Lowercase),
+ S = cond_lowercase(integer_to_list(Int, Base), Lowercase),
term([Prefix | S], F, Adj, none, Pad)
end.
diff --git a/src/couch_log/test/eunit/couch_log_config_listener_test.erl b/src/couch_log/test/eunit/couch_log_config_listener_test.erl
index c955972ff..2e4a45be3 100644
--- a/src/couch_log/test/eunit/couch_log_config_listener_test.erl
+++ b/src/couch_log/test/eunit/couch_log_config_listener_test.erl
@@ -29,14 +29,14 @@ check_restart_listener() ->
Handler1 = get_handler(),
?assertNotEqual(not_found, Handler1),
- Ref = erlang:monitor(process, Listener1),
+ Ref = monitor(process, Listener1),
ok = gen_event:delete_handler(config_event, get_handler(), testing),
receive
{'DOWN', Ref, process, _, _} ->
?assertNot(is_process_alive(Listener1))
after ?TIMEOUT ->
- erlang:error({timeout, config_listener_mon_death})
+ error({timeout, config_listener_mon_death})
end,
NewHandler = test_util:wait(
diff --git a/src/couch_log/test/eunit/couch_log_formatter_test.erl b/src/couch_log/test/eunit/couch_log_formatter_test.erl
index cdb7eae31..d09f3b38a 100644
--- a/src/couch_log/test/eunit/couch_log_formatter_test.erl
+++ b/src/couch_log/test/eunit/couch_log_formatter_test.erl
@@ -53,7 +53,7 @@ crashing_formatting_test() ->
Pid = self(),
Event = {
error,
- erlang:group_leader(),
+ group_leader(),
{
Pid,
"** Generic server and some stuff",
@@ -76,7 +76,7 @@ gen_server_error_test() ->
Pid = self(),
Event = {
error,
- erlang:group_leader(),
+ group_leader(),
{
Pid,
"** Generic server and some stuff",
@@ -102,7 +102,7 @@ gen_server_error_with_extra_args_test() ->
Pid = self(),
Event = {
error,
- erlang:group_leader(),
+ group_leader(),
{
Pid,
"** Generic server and some stuff",
@@ -128,7 +128,7 @@ gen_fsm_error_test() ->
Pid = self(),
Event = {
error,
- erlang:group_leader(),
+ group_leader(),
{
Pid,
"** State machine did a thing",
@@ -154,7 +154,7 @@ gen_fsm_error_with_extra_args_test() ->
Pid = self(),
Event = {
error,
- erlang:group_leader(),
+ group_leader(),
{
Pid,
"** State machine did a thing",
@@ -180,7 +180,7 @@ gen_event_error_test() ->
Pid = self(),
Event = {
error,
- erlang:group_leader(),
+ group_leader(),
{
Pid,
"** gen_event handler did a thing",
@@ -210,7 +210,7 @@ gen_event_error_test() ->
emulator_error_test() ->
Event = {
error,
- erlang:group_leader(),
+ group_leader(),
{
emulator,
"~s~n",
@@ -230,7 +230,7 @@ normal_error_test() ->
Pid = self(),
Event = {
error,
- erlang:group_leader(),
+ group_leader(),
{
Pid,
"format thing: ~w ~w",
@@ -253,7 +253,7 @@ error_report_std_error_test() ->
Pid = self(),
Event = {
error_report,
- erlang:group_leader(),
+ group_leader(),
{
Pid,
std_error,
@@ -274,7 +274,7 @@ supervisor_report_test() ->
% A standard supervisor report
Event1 = {
error_report,
- erlang:group_leader(),
+ group_leader(),
{
Pid,
supervisor_report,
@@ -307,7 +307,7 @@ supervisor_report_test() ->
% in the offender blob.
Event2 = {
error_report,
- erlang:group_leader(),
+ group_leader(),
{
Pid,
supervisor_report,
@@ -339,7 +339,7 @@ supervisor_report_test() ->
% A supervisor_bridge
Event3 = {
error_report,
- erlang:group_leader(),
+ group_leader(),
{
Pid,
supervisor_report,
@@ -370,7 +370,7 @@ supervisor_report_test() ->
% Any other supervisor report
Event4 = {
error_report,
- erlang:group_leader(),
+ group_leader(),
{
Pid,
supervisor_report,
@@ -391,7 +391,7 @@ crash_report_test() ->
% A standard crash report
Event1 = {
error_report,
- erlang:group_leader(),
+ group_leader(),
{
Pid,
crash_report,
@@ -425,7 +425,7 @@ crash_report_test() ->
% A registered process crash report
Event2 = {
error_report,
- erlang:group_leader(),
+ group_leader(),
{
Pid,
crash_report,
@@ -450,7 +450,7 @@ crash_report_test() ->
% A non-exit crash report
Event3 = {
error_report,
- erlang:group_leader(),
+ group_leader(),
{
Pid,
crash_report,
@@ -475,7 +475,7 @@ crash_report_test() ->
% A extra report info
Event4 = {
error_report,
- erlang:group_leader(),
+ group_leader(),
{
Pid,
crash_report,
@@ -504,7 +504,7 @@ warning_report_test() ->
% A warning message
Event1 = {
warning_msg,
- erlang:group_leader(),
+ group_leader(),
{
Pid,
"a ~s string ~w",
@@ -522,7 +522,7 @@ warning_report_test() ->
% A warning report
Event2 = {
warning_report,
- erlang:group_leader(),
+ group_leader(),
{
Pid,
std_warning,
@@ -543,7 +543,7 @@ info_report_test() ->
% An info message
Event1 = {
info_msg,
- erlang:group_leader(),
+ group_leader(),
{
Pid,
"an info ~s string ~w",
@@ -561,7 +561,7 @@ info_report_test() ->
% Application exit info
Event2 = {
info_report,
- erlang:group_leader(),
+ group_leader(),
{
Pid,
std_info,
@@ -583,7 +583,7 @@ info_report_test() ->
% Any other std_info message
Event3 = {
info_report,
- erlang:group_leader(),
+ group_leader(),
{
Pid,
std_info,
@@ -604,7 +604,7 @@ info_report_test() ->
% Non-list other report
Event4 = {
info_report,
- erlang:group_leader(),
+ group_leader(),
{
Pid,
std_info,
@@ -625,7 +625,7 @@ progress_report_test() ->
% Application started
Event1 = {
info_report,
- erlang:group_leader(),
+ group_leader(),
{
Pid,
progress,
@@ -643,7 +643,7 @@ progress_report_test() ->
% Supervisor started child
Event2 = {
info_report,
- erlang:group_leader(),
+ group_leader(),
{
Pid,
progress,
@@ -669,7 +669,7 @@ progress_report_test() ->
% Other progress report
Event3 = {
info_report,
- erlang:group_leader(),
+ group_leader(),
{
Pid,
progress,
@@ -787,7 +787,7 @@ format_reason_test_() ->
"bad argument in call to j:k(a, 2) at y:x/1"
},
{
- {{badarity, {fun erlang:spawn/1, [a, b]}}, [{y, x, 1}]},
+ {{badarity, {fun spawn/1, [a, b]}}, [{y, x, 1}]},
"function called with wrong arity of 2 instead of 1 at y:x/1"
},
{
@@ -837,7 +837,7 @@ coverage_test() ->
do_format(
{
error_report,
- erlang:group_leader(),
+ group_leader(),
{self(), std_error, "foobar"}
}
)
@@ -852,7 +852,7 @@ coverage_test() ->
do_format(
{
error_report,
- erlang:group_leader(),
+ group_leader(),
{self(), std_error, dang}
}
)
@@ -862,7 +862,7 @@ gen_server_error_with_last_msg_test() ->
Pid = self(),
Event = {
error,
- erlang:group_leader(),
+ group_leader(),
{
Pid,
"** Generic server and some stuff",
@@ -890,7 +890,7 @@ gen_event_error_with_last_msg_test() ->
Pid = self(),
Event = {
error,
- erlang:group_leader(),
+ group_leader(),
{
Pid,
"** gen_event handler did a thing",
@@ -923,7 +923,7 @@ gen_fsm_error_with_last_msg_test() ->
Pid = self(),
Event = {
error,
- erlang:group_leader(),
+ group_leader(),
{
Pid,
"** State machine did a thing",
diff --git a/src/couch_log/test/eunit/couch_log_server_test.erl b/src/couch_log/test/eunit/couch_log_server_test.erl
index df768f26e..ff9dbc3f0 100644
--- a/src/couch_log/test/eunit/couch_log_server_test.erl
+++ b/src/couch_log/test/eunit/couch_log_server_test.erl
@@ -39,7 +39,7 @@ check_can_reconfigure() ->
check_can_restart() ->
Pid1 = whereis(couch_log_server),
- Ref = erlang:monitor(process, Pid1),
+ Ref = monitor(process, Pid1),
?assert(is_process_alive(Pid1)),
supervisor:terminate_child(couch_log_sup, couch_log_server),
@@ -48,7 +48,7 @@ check_can_restart() ->
receive
{'DOWN', Ref, _, _, _} -> ok
after 1000 ->
- erlang:error(timeout_restarting_couch_log_server)
+ error(timeout_restarting_couch_log_server)
end,
?assert(not is_process_alive(Pid1)),
diff --git a/src/couch_log/test/eunit/couch_log_test_util.erl b/src/couch_log/test/eunit/couch_log_test_util.erl
index 9a170bdbd..743cdf6ef 100644
--- a/src/couch_log/test/eunit/couch_log_test_util.erl
+++ b/src/couch_log/test/eunit/couch_log_test_util.erl
@@ -64,7 +64,7 @@ wait_for_config() ->
receive
couch_log_config_change_finished -> ok
after 1000 ->
- erlang:error(config_change_timeout)
+ error(config_change_timeout)
end.
with_meck(Mods, Fun) ->
@@ -119,7 +119,7 @@ disable_logs_from(Name) when is_atom(Name) ->
P when is_pid(P) ->
disable_logs_from(P);
undefined ->
- erlang:error({unknown_pid_name, Name})
+ error({unknown_pid_name, Name})
end.
last_log_key() ->
diff --git a/src/couch_mrview/src/couch_mrview.erl b/src/couch_mrview/src/couch_mrview.erl
index 037c35cdd..bc7b1f8ab 100644
--- a/src/couch_mrview/src/couch_mrview.erl
+++ b/src/couch_mrview/src/couch_mrview.erl
@@ -183,7 +183,7 @@ map_function_type({Props}) ->
end.
format_type(Type) when is_atom(Type) ->
- ?l2b(atom_to_list(Type));
+ atom_to_binary(Type);
format_type(Types) when is_list(Types) ->
iolist_to_binary(join(lists:map(fun atom_to_list/1, Types), <<" or ">>)).
@@ -287,12 +287,22 @@ query_all_docs(Db, Args0, Callback, Acc) ->
couch_index_util:hexsig(couch_hash:md5_hash(?term_to_bin(Info)))
end),
Args1 = Args0#mrargs{view_type = map},
+
+ % TODO: Compatibility clause. Remove after upgrading to next minor release
+ % after 3.5.0.
+ %
+ % As of commit 7aa8a4, args are validated in fabric. However, during online
+ % cluster upgrades, old nodes will still expect args to be validated on
+ % workers, so keep the clause around until the next minor version then
+ % remove.
+ %
+ Args2 = couch_mrview_util:validate_all_docs_args(Db, Args1),
{ok, Acc1} =
- case Args1#mrargs.preflight_fun of
+ case Args2#mrargs.preflight_fun of
PFFun when is_function(PFFun, 2) -> PFFun(Sig, Acc);
_ -> {ok, Acc}
end,
- all_docs_fold(Db, Args1, Callback, Acc1).
+ all_docs_fold(Db, Args2, Callback, Acc1).
query_view(Db, DDoc, VName) ->
Args = #mrargs{extra = [{view_row_map, true}]},
@@ -328,7 +338,7 @@ query_view(Db, {Type, View, Ref}, Args, Callback, Acc) ->
red -> red_fold(Db, View, Args, Callback, Acc)
end
after
- erlang:demonitor(Ref, [flush])
+ demonitor(Ref, [flush])
end.
get_info(Db, DDoc) ->
diff --git a/src/couch_mrview/src/couch_mrview_cleanup.erl b/src/couch_mrview/src/couch_mrview_cleanup.erl
index 5b5afbdce..e8a2833a7 100644
--- a/src/couch_mrview/src/couch_mrview_cleanup.erl
+++ b/src/couch_mrview/src/couch_mrview_cleanup.erl
@@ -14,12 +14,9 @@
-export([
run/1,
- cleanup_purges/3,
- cleanup_indices/2
+ cleanup/2
]).
--include_lib("couch/include/couch_db.hrl").
-
run(Db) ->
Indices = couch_mrview_util:get_index_files(Db),
Checkpoints = couch_mrview_util:get_purge_checkpoints(Db),
@@ -28,15 +25,26 @@ run(Db) ->
ok = cleanup_purges(Db1, Sigs, Checkpoints),
ok = cleanup_indices(Sigs, Indices).
-cleanup_purges(DbName, Sigs, Checkpoints) when is_binary(DbName) ->
- couch_util:with_db(DbName, fun(Db) ->
- cleanup_purges(Db, Sigs, Checkpoints)
- end);
-cleanup_purges(Db, #{} = Sigs, #{} = CheckpointsMap) ->
- InactiveMap = maps:without(maps:keys(Sigs), CheckpointsMap),
- InactiveCheckpoints = maps:values(InactiveMap),
- DeleteFun = fun(DocId) -> delete_checkpoint(Db, DocId) end,
- lists:foreach(DeleteFun, InactiveCheckpoints).
+% erpc endpoint for fabric_index_cleanup:cleanup_indexes/2
+%
+cleanup(Dbs, #{} = Sigs) ->
+ try
+ lists:foreach(
+ fun(Db) ->
+ Indices = couch_mrview_util:get_index_files(Db),
+ Checkpoints = couch_mrview_util:get_purge_checkpoints(Db),
+ ok = cleanup_purges(Db, Sigs, Checkpoints),
+ ok = cleanup_indices(Sigs, Indices)
+ end,
+ Dbs
+ )
+ catch
+ error:database_does_not_exist ->
+ ok
+ end.
+
+cleanup_purges(Db, Sigs, Checkpoints) ->
+ couch_index_util:cleanup_purges(Db, Sigs, Checkpoints).
cleanup_indices(#{} = Sigs, #{} = IndexMap) ->
Fun = fun(_, Files) -> lists:foreach(fun delete_file/1, Files) end,
@@ -54,20 +62,3 @@ delete_file(File) ->
couch_log:error(ErrLog, [?MODULE, File, Tag, Error]),
ok
end.
-
-delete_checkpoint(Db, DocId) ->
- DbName = couch_db:name(Db),
- LogMsg = "~p : deleting inactive purge checkpoint ~s : ~s",
- couch_log:debug(LogMsg, [?MODULE, DbName, DocId]),
- try couch_db:open_doc(Db, DocId, []) of
- {ok, Doc = #doc{}} ->
- Deleted = Doc#doc{deleted = true, body = {[]}},
- couch_db:update_doc(Db, Deleted, [?ADMIN_CTX]);
- {not_found, _} ->
- ok
- catch
- Tag:Error ->
- ErrLog = "~p : error deleting checkpoint ~s : ~s error: ~p:~p",
- couch_log:error(ErrLog, [?MODULE, DbName, DocId, Tag, Error]),
- ok
- end.
diff --git a/src/couch_mrview/src/couch_mrview_compactor.erl b/src/couch_mrview/src/couch_mrview_compactor.erl
index 28e5a9b3d..a534dd0e8 100644
--- a/src/couch_mrview/src/couch_mrview_compactor.erl
+++ b/src/couch_mrview/src/couch_mrview_compactor.erl
@@ -136,11 +136,11 @@ recompact(State) ->
recompact(State, recompact_retry_count()).
recompact(#mrst{db_name = DbName, idx_name = IdxName}, 0) ->
- erlang:error({exceeded_recompact_retry_count, [{db_name, DbName}, {idx_name, IdxName}]});
+ error({exceeded_recompact_retry_count, [{db_name, DbName}, {idx_name, IdxName}]});
recompact(State, RetryCount) ->
Self = self(),
link(State#mrst.fd),
- {Pid, Ref} = erlang:spawn_monitor(fun() ->
+ {Pid, Ref} = spawn_monitor(fun() ->
couch_index_updater:update(Self, couch_mrview_index, State)
end),
recompact_loop(Pid, Ref, State, RetryCount).
@@ -240,7 +240,7 @@ swap_compacted(OldState, NewState) ->
} = NewState,
link(NewState#mrst.fd),
- Ref = erlang:monitor(process, NewState#mrst.fd),
+ Ref = monitor(process, NewState#mrst.fd),
RootDir = couch_index_util:root_dir(),
IndexFName = couch_mrview_util:index_file(DbName, Sig),
@@ -257,7 +257,7 @@ swap_compacted(OldState, NewState) ->
ok = file:rename(CompactFName, IndexFName),
unlink(OldState#mrst.fd),
- erlang:demonitor(OldState#mrst.fd_monitor, [flush]),
+ demonitor(OldState#mrst.fd_monitor, [flush]),
{ok, NewState#mrst{fd_monitor = Ref}}.
diff --git a/src/couch_mrview/src/couch_mrview_index.erl b/src/couch_mrview/src/couch_mrview_index.erl
index 51777480c..a5080ed76 100644
--- a/src/couch_mrview/src/couch_mrview_index.erl
+++ b/src/couch_mrview/src/couch_mrview_index.erl
@@ -167,7 +167,7 @@ open(Db, State0) ->
end.
close(State) ->
- erlang:demonitor(State#mrst.fd_monitor, [flush]),
+ demonitor(State#mrst.fd_monitor, [flush]),
couch_file:close(State#mrst.fd).
% This called after ddoc_updated event occurrs, and
@@ -178,7 +178,7 @@ close(State) ->
% couch_file will be closed automatically after all
% outstanding queries are done.
shutdown(State) ->
- erlang:demonitor(State#mrst.fd_monitor, [flush]),
+ demonitor(State#mrst.fd_monitor, [flush]),
unlink(State#mrst.fd).
delete(#mrst{db_name = DbName, sig = Sig} = State) ->
diff --git a/src/couch_mrview/src/couch_mrview_test_util.erl b/src/couch_mrview/src/couch_mrview_test_util.erl
index 349611191..f021ce58d 100644
--- a/src/couch_mrview/src/couch_mrview_test_util.erl
+++ b/src/couch_mrview/src/couch_mrview_test_util.erl
@@ -139,7 +139,7 @@ ddoc(Id) ->
doc(Id) ->
couch_doc:from_json_obj(
{[
- {<<"_id">>, list_to_binary(integer_to_list(Id))},
+ {<<"_id">>, integer_to_binary(Id)},
{<<"val">>, Id}
]}
).
diff --git a/src/couch_mrview/src/couch_mrview_updater.erl b/src/couch_mrview/src/couch_mrview_updater.erl
index 92e66d0fa..4238e6b7d 100644
--- a/src/couch_mrview/src/couch_mrview_updater.erl
+++ b/src/couch_mrview/src/couch_mrview_updater.erl
@@ -166,13 +166,13 @@ map_docs(Parent, #mrst{db_name = DbName, idx_name = IdxName} = State0) ->
QServer = State1#mrst.qserver,
DocFun = fun
({nil, Seq, _}, {SeqAcc, Results}) ->
- {erlang:max(Seq, SeqAcc), Results};
+ {max(Seq, SeqAcc), Results};
({Id, Seq, deleted}, {SeqAcc, Results}) ->
- {erlang:max(Seq, SeqAcc), [{Id, []} | Results]};
+ {max(Seq, SeqAcc), [{Id, []} | Results]};
({Id, Seq, Doc}, {SeqAcc, Results}) ->
couch_stats:increment_counter([couchdb, mrview, map_doc]),
{ok, Res} = couch_query_servers:map_doc_raw(QServer, Doc),
- {erlang:max(Seq, SeqAcc), [{Id, Res} | Results]}
+ {max(Seq, SeqAcc), [{Id, Res} | Results]}
end,
FoldFun = fun(Docs, Acc) ->
update_task(length(Docs)),
@@ -242,7 +242,7 @@ merge_results([{Seq, Results} | Rest], SeqAcc, ViewKVs, DocIdKeys) ->
merge_results(RawResults, VKV, DIK)
end,
{ViewKVs1, DocIdKeys1} = lists:foldl(Fun, {ViewKVs, DocIdKeys}, Results),
- merge_results(Rest, erlang:max(Seq, SeqAcc), ViewKVs1, DocIdKeys1).
+ merge_results(Rest, max(Seq, SeqAcc), ViewKVs1, DocIdKeys1).
merge_results({DocId, []}, ViewKVs, DocIdKeys) ->
{ViewKVs, [{DocId, []} | DocIdKeys]};
diff --git a/src/couch_mrview/src/couch_mrview_util.erl b/src/couch_mrview/src/couch_mrview_util.erl
index a5c81a073..5405e8db8 100644
--- a/src/couch_mrview/src/couch_mrview_util.erl
+++ b/src/couch_mrview/src/couch_mrview_util.erl
@@ -16,6 +16,7 @@
-export([get_local_purge_doc_id/1, get_value_from_options/2]).
-export([verify_view_filename/1, get_signature_from_filename/1]).
-export([get_signatures/1, get_purge_checkpoints/1, get_index_files/1]).
+-export([get_signatures_from_ddocs/2]).
-export([ddoc_to_mrst/2, init_state/4, reset_index/3]).
-export([make_header/1]).
-export([index_file/2, compaction_file/2, open_file/1]).
@@ -94,40 +95,35 @@ get_signatures(DbName) when is_binary(DbName) ->
couch_util:with_db(DbName, fun get_signatures/1);
get_signatures(Db) ->
DbName = couch_db:name(Db),
- % get_design_docs/1 returns ejson for clustered shards, and
- % #full_doc_info{}'s for other cases.
{ok, DDocs} = couch_db:get_design_docs(Db),
+ % get_design_docs/1 returns ejson for clustered shards, and
+ % #full_doc_info{}'s for other cases. Both are transformed to #doc{} records
FoldFun = fun
({[_ | _]} = EJsonDoc, Acc) ->
Doc = couch_doc:from_json_obj(EJsonDoc),
- {ok, Mrst} = ddoc_to_mrst(DbName, Doc),
- Sig = couch_util:to_hex_bin(Mrst#mrst.sig),
- Acc#{Sig => true};
+ [Doc | Acc];
(#full_doc_info{} = FDI, Acc) ->
{ok, Doc} = couch_db:open_doc_int(Db, FDI, [ejson_body]),
- {ok, Mrst} = ddoc_to_mrst(DbName, Doc),
- Sig = couch_util:to_hex_bin(Mrst#mrst.sig),
- Acc#{Sig => true}
+ [Doc | Acc]
+ end,
+ DDocs1 = lists:foldl(FoldFun, [], DDocs),
+ get_signatures_from_ddocs(DbName, DDocs1).
+
+% From a list of design #doc{} records returns signatures map: #{Sig => true}
+%
+get_signatures_from_ddocs(DbName, DDocs) when is_list(DDocs) ->
+ FoldFun = fun(#doc{} = Doc, Acc) ->
+ {ok, Mrst} = ddoc_to_mrst(DbName, Doc),
+ Sig = couch_util:to_hex_bin(Mrst#mrst.sig),
+ Acc#{Sig => true}
end,
lists:foldl(FoldFun, #{}, DDocs).
% Returns a map of `Sig => DocId` elements for all the purge view
% checkpoint docs. Sig is a hex-encoded binary.
%
-get_purge_checkpoints(DbName) when is_binary(DbName) ->
- couch_util:with_db(DbName, fun get_purge_checkpoints/1);
get_purge_checkpoints(Db) ->
- FoldFun = fun(#doc{id = Id}, Acc) ->
- case Id of
- <<?LOCAL_DOC_PREFIX, "purge-mrview-", Sig/binary>> ->
- {ok, Acc#{Sig => Id}};
- _ ->
- {stop, Acc}
- end
- end,
- Opts = [{start_key, <<?LOCAL_DOC_PREFIX, "purge-mrview-">>}],
- {ok, Signatures = #{}} = couch_db:fold_local_docs(Db, FoldFun, #{}, Opts),
- Signatures.
+ couch_index_util:get_purge_checkpoints(Db, <<"mrview">>).
% Returns a map of `Sig => [FilePath, ...]` elements. Sig is a hex-encoded
% binary and FilePaths are lists as they intended to be passed to couch_file
@@ -152,7 +148,7 @@ get_index_files(Db) ->
get_view(Db, DDoc, ViewName, Args0) ->
case get_view_index_state(Db, DDoc, ViewName, Args0) of
{ok, State, Args2} ->
- Ref = erlang:monitor(process, State#mrst.fd),
+ Ref = monitor(process, State#mrst.fd),
#mrst{language = Lang, views = Views} = State,
{Type, View, Args3} = extract_view(Lang, Args2, ViewName, Views),
check_range(Args3, view_cmp(View)),
@@ -382,7 +378,7 @@ init_state(Db, Fd, State, Header) ->
{ShouldCommit, State#mrst{
fd = Fd,
- fd_monitor = erlang:monitor(process, Fd),
+ fd_monitor = monitor(process, Fd),
update_seq = Seq,
purge_seq = PurgeSeq,
id_btree = IdBtree,
@@ -544,7 +540,13 @@ apply_limit(ViewPartitioned, Args) ->
mrverror(io_lib:format(Fmt, [MaxLimit]))
end.
-validate_all_docs_args(Db, Args0) ->
+validate_all_docs_args(Db, #mrargs{} = Args) ->
+ case get_extra(Args, validated, false) of
+ true -> Args;
+ false -> validate_all_docs_args_int(Db, Args)
+ end.
+
+validate_all_docs_args_int(Db, Args0) ->
Args = validate_args(Args0#mrargs{view_type = map}),
DbPartitioned = couch_db:is_partitioned(Db),
@@ -560,7 +562,13 @@ validate_all_docs_args(Db, Args0) ->
apply_limit(false, Args)
end.
-validate_args(Args) ->
+validate_args(#mrargs{} = Args) ->
+ case get_extra(Args, validated, false) of
+ true -> Args;
+ false -> validate_args_int(Args)
+ end.
+
+validate_args_int(#mrargs{} = Args) ->
GroupLevel = determine_group_level(Args),
Reduce = Args#mrargs.reduce,
case Reduce == undefined orelse is_boolean(Reduce) of
@@ -696,11 +704,12 @@ validate_args(Args) ->
_ -> mrverror(<<"Invalid value for `partition`.">>)
end,
- Args#mrargs{
+ Args1 = Args#mrargs{
start_key_docid = SKDocId,
end_key_docid = EKDocId,
group_level = GroupLevel
- }.
+ },
+ set_extra(Args1, validated, true).
determine_group_level(#mrargs{group = undefined, group_level = undefined}) ->
0;
@@ -1304,7 +1313,8 @@ make_user_reds_reduce_fun(Lang, ReduceFuns, NthRed) ->
get_btree_state(nil) ->
nil;
-get_btree_state(#btree{} = Btree) ->
+get_btree_state(Btree) ->
+ true = couch_btree:is_btree(Btree),
couch_btree:get_state(Btree).
extract_view_reduce({red, {N, _Lang, #mrview{reduce_funs = Reds}}, _Ref}) ->
diff --git a/src/couch_mrview/test/eunit/couch_mrview_collation_tests.erl b/src/couch_mrview/test/eunit/couch_mrview_collation_tests.erl
index c00b97b33..87d481426 100644
--- a/src/couch_mrview/test/eunit/couch_mrview_collation_tests.erl
+++ b/src/couch_mrview/test/eunit/couch_mrview_collation_tests.erl
@@ -137,7 +137,7 @@ find_matching_rows(Index, Value) ->
),
lists:map(
fun({Id, V}) ->
- {row, [{id, list_to_binary(integer_to_list(Id))}, {key, V}, {value, 0}]}
+ {row, [{id, integer_to_binary(Id)}, {key, V}, {value, 0}]}
end,
Matches
).
@@ -206,7 +206,7 @@ make_docs() ->
fun(V, {Docs0, Count}) ->
Doc = couch_doc:from_json_obj(
{[
- {<<"_id">>, list_to_binary(integer_to_list(Count))},
+ {<<"_id">>, integer_to_binary(Count)},
{<<"foo">>, V}
]}
),
@@ -220,7 +220,7 @@ make_docs() ->
rows() ->
{Rows, _} = lists:foldl(
fun(V, {Rows0, Count}) ->
- Id = list_to_binary(integer_to_list(Count)),
+ Id = integer_to_binary(Count),
Row = {row, [{id, Id}, {key, V}, {value, 0}]},
{[Row | Rows0], Count + 1}
end,
diff --git a/src/couch_mrview/test/eunit/couch_mrview_compact_tests.erl b/src/couch_mrview/test/eunit/couch_mrview_compact_tests.erl
index df035c649..048f6bc70 100644
--- a/src/couch_mrview/test/eunit/couch_mrview_compact_tests.erl
+++ b/src/couch_mrview/test/eunit/couch_mrview_compact_tests.erl
@@ -55,7 +55,7 @@ should_swap(Db) ->
receive
{'DOWN', MonRef, process, _, _} -> ok
after ?TIMEOUT ->
- erlang:error(
+ error(
{assertion_failed, [
{module, ?MODULE},
{line, ?LINE},
@@ -68,7 +68,7 @@ should_swap(Db) ->
{QPid, Count} ->
?assertEqual(1000, Count)
after ?TIMEOUT ->
- erlang:error(
+ error(
{assertion_failed, [
{module, ?MODULE},
{line, ?LINE},
@@ -86,7 +86,7 @@ should_remove(Db) ->
ok = couch_index:compact(IndexPid, []),
{ok, CompactorPid} = couch_index:get_compactor_pid(IndexPid),
{ok, CompactingPid} = couch_index_compactor:get_compacting_pid(CompactorPid),
- MonRef = erlang:monitor(process, CompactingPid),
+ MonRef = monitor(process, CompactingPid),
exit(CompactingPid, crash),
receive
{'DOWN', MonRef, process, _, crash} ->
@@ -100,7 +100,7 @@ should_remove(Db) ->
?assert(is_process_alive(IndexPid)),
?assert(is_process_alive(CompactorPid))
after ?TIMEOUT ->
- erlang:error(
+ error(
{assertion_failed, [
{module, ?MODULE},
{line, ?LINE},
diff --git a/src/couch_mrview/test/eunit/couch_mrview_ddoc_updated_tests.erl b/src/couch_mrview/test/eunit/couch_mrview_ddoc_updated_tests.erl
index 91b24e336..756434892 100644
--- a/src/couch_mrview/test/eunit/couch_mrview_ddoc_updated_tests.erl
+++ b/src/couch_mrview/test/eunit/couch_mrview_ddoc_updated_tests.erl
@@ -90,7 +90,7 @@ check_indexing_stops_on_ddoc_change(Db) ->
IndexesBefore = get_indexes_by_ddoc(couch_db:name(Db), DDocID, 1),
?assertEqual(1, length(IndexesBefore)),
- AliveBefore = lists:filter(fun erlang:is_process_alive/1, IndexesBefore),
+ AliveBefore = lists:filter(fun is_process_alive/1, IndexesBefore),
?assertEqual(1, length(AliveBefore)),
{ok, DDoc} = couch_db:open_doc(Db, DDocID, [ejson_body, ?ADMIN_CTX]),
@@ -117,7 +117,7 @@ check_indexing_stops_on_ddoc_change(Db) ->
{QPid, Msg} ->
?assertEqual(Msg, ddoc_updated)
after ?TIMEOUT ->
- erlang:error(
+ error(
{assertion_failed, [
{module, ?MODULE},
{line, ?LINE},
@@ -129,7 +129,7 @@ check_indexing_stops_on_ddoc_change(Db) ->
%% assert that previously running indexes are gone
IndexesAfter = get_indexes_by_ddoc(couch_db:name(Db), DDocID, 0),
?assertEqual(0, length(IndexesAfter)),
- AliveAfter = lists:filter(fun erlang:is_process_alive/1, IndexesBefore),
+ AliveAfter = lists:filter(fun is_process_alive/1, IndexesBefore),
?assertEqual(0, length(AliveAfter))
end).
diff --git a/src/couch_mrview/test/eunit/couch_mrview_purge_docs_fabric_tests.erl b/src/couch_mrview/test/eunit/couch_mrview_purge_docs_fabric_tests.erl
index 3207a3da3..f3452b55a 100644
--- a/src/couch_mrview/test/eunit/couch_mrview_purge_docs_fabric_tests.erl
+++ b/src/couch_mrview/test/eunit/couch_mrview_purge_docs_fabric_tests.erl
@@ -288,7 +288,7 @@ wait_compaction(DbName, Line) ->
end,
case test_util:wait(WaitFun, 10000) of
timeout ->
- erlang:error(
+ error(
{assertion_failed, [
{module, ?MODULE},
{line, Line},
diff --git a/src/couch_mrview/test/eunit/couch_mrview_purge_docs_tests.erl b/src/couch_mrview/test/eunit/couch_mrview_purge_docs_tests.erl
index 44500bdf1..c4ac9ed13 100644
--- a/src/couch_mrview/test/eunit/couch_mrview_purge_docs_tests.erl
+++ b/src/couch_mrview/test/eunit/couch_mrview_purge_docs_tests.erl
@@ -299,7 +299,7 @@ test_purge_index_reset(Db) ->
PurgeInfos = lists:map(
fun(I) ->
- DocId = list_to_binary(integer_to_list(I)),
+ DocId = integer_to_binary(I),
FDI = couch_db:get_full_doc_info(Db, DocId),
Rev = get_rev(FDI),
{couch_uuids:random(), DocId, [Rev]}
@@ -576,7 +576,7 @@ wait_compaction(DbName, Kind, Line) ->
end,
case test_util:wait(WaitFun, 10000) of
timeout ->
- erlang:error(
+ error(
{assertion_failed, [
{module, ?MODULE},
{line, Line},
@@ -600,7 +600,7 @@ fold_fun({_PSeq, _UUID, Id, Revs}, Acc) ->
{ok, [{Id, Revs} | Acc]}.
docid(I) ->
- list_to_binary(integer_to_list(I)).
+ integer_to_binary(I).
uuid(I) ->
Str = io_lib:format("UUID~4..0b", [I]),
diff --git a/src/couch_mrview/test/eunit/couch_mrview_util_tests.erl b/src/couch_mrview/test/eunit/couch_mrview_util_tests.erl
index 2562bb511..c304dcdad 100644
--- a/src/couch_mrview/test/eunit/couch_mrview_util_tests.erl
+++ b/src/couch_mrview/test/eunit/couch_mrview_util_tests.erl
@@ -174,3 +174,31 @@ t_get_index_files_clustered({DbName, _Db}) ->
?assertMatch({ok, _}, file:read_file_info(File)),
{ok, Info} = couch_mrview:get_info(ShardName1, ?DDOC_ID),
?assertEqual(proplists:get_value(signature, Info), Sig).
+
+do_not_validate_args_if_already_validated_test() ->
+ Args = #mrargs{
+ view_type = red,
+ group = true,
+ group_level = undefined,
+ extra = [{foo, bar}]
+ },
+
+ % Initially if we haven't validated, it's not flagged as such
+ ?assertNot(couch_mrview_util:get_extra(Args, validated, false)),
+
+ % Do the validation
+ Args1 = couch_mrview_util:validate_args(Args),
+
+ % Validation worked
+ ?assertEqual(exact, Args1#mrargs.group_level),
+
+ % Validation flag is set to true
+ ?assert(couch_mrview_util:get_extra(Args1, validated, false)),
+
+ Args2 = couch_mrview_util:validate_args(Args1),
+ % No change, as already validated
+ ?assertEqual(Args1, Args2),
+
+ Args3 = couch_mrview_util:validate_all_docs_args(some_db, Args2),
+ % No change for all docs validation as already validated
+ ?assertEqual(Args1, Args3).
diff --git a/src/couch_peruser/src/couch_peruser.erl b/src/couch_peruser/src/couch_peruser.erl
index 6f4a24cab..8a7cbe13a 100644
--- a/src/couch_peruser/src/couch_peruser.erl
+++ b/src/couch_peruser/src/couch_peruser.erl
@@ -269,7 +269,7 @@ should_handle_doc(ShardName, DocId) ->
) -> boolean().
should_handle_doc_int(ShardName, DocId) ->
DbName = mem3:dbname(ShardName),
- Live = [erlang:node() | erlang:nodes()],
+ Live = [erlang:node() | nodes()],
Shards = mem3:shards(DbName, DocId),
Nodes = [N || #shard{node = N} <- Shards, lists:member(N, Live)],
case mem3:owner(DbName, DocId, Nodes) of
diff --git a/src/couch_prometheus/src/couch_prometheus.erl b/src/couch_prometheus/src/couch_prometheus.erl
index 4d053d1af..7f3dc494d 100644
--- a/src/couch_prometheus/src/couch_prometheus.erl
+++ b/src/couch_prometheus/src/couch_prometheus.erl
@@ -68,7 +68,8 @@ get_system_stats() ->
get_internal_replication_jobs_stat(),
get_membership_stat(),
get_membership_nodes(),
- get_distribution_stats()
+ get_distribution_stats(),
+ get_bt_engine_cache_stats()
]).
get_uptime_stat() ->
@@ -119,9 +120,9 @@ get_vm_stats() ->
end,
erlang:memory()
),
- {NumGCs, WordsReclaimed, _} = erlang:statistics(garbage_collection),
- CtxSwitches = element(1, erlang:statistics(context_switches)),
- Reds = element(1, erlang:statistics(reductions)),
+ {NumGCs, WordsReclaimed, _} = statistics(garbage_collection),
+ CtxSwitches = element(1, statistics(context_switches)),
+ Reds = element(1, statistics(reductions)),
ProcCount = erlang:system_info(process_count),
ProcLimit = erlang:system_info(process_limit),
[
@@ -157,7 +158,7 @@ get_vm_stats() ->
].
get_io_stats() ->
- {{input, In}, {output, Out}} = erlang:statistics(io),
+ {{input, In}, {output, Out}} = statistics(io),
[
to_prom(
erlang_io_recv_bytes_total,
@@ -374,3 +375,12 @@ get_distribution_stats() ->
get_ets_stats() ->
NumTabs = length(ets:all()),
to_prom(erlang_ets_table, gauge, "number of ETS tables", NumTabs).
+
+get_bt_engine_cache_stats() ->
+ Stats = couch_bt_engine_cache:info(),
+ Size = maps:get(size, Stats, 0),
+ Mem = maps:get(memory, Stats, 0),
+ [
+ to_prom(couchdb_bt_engine_cache_memory, gauge, "memory used by the btree cache", Mem),
+ to_prom(couchdb_bt_engine_cache_size, gauge, "number of entries in the btree cache", Size)
+ ].
diff --git a/src/couch_prometheus/test/eunit/couch_prometheus_e2e_tests.erl b/src/couch_prometheus/test/eunit/couch_prometheus_e2e_tests.erl
index c33b379a8..383871721 100644
--- a/src/couch_prometheus/test/eunit/couch_prometheus_e2e_tests.erl
+++ b/src/couch_prometheus/test/eunit/couch_prometheus_e2e_tests.erl
@@ -114,9 +114,9 @@ t_no_duplicate_metrics(Port) ->
% definition, not the values. These lines always start with
% a # character.
MetricDefs = lists:filter(fun(S) -> string:find(S, "#") =:= S end, Lines),
- ?assertNotEqual(erlang:length(MetricDefs), 0),
+ ?assertNotEqual(length(MetricDefs), 0),
Diff = get_duplicates(MetricDefs),
- ?assertEqual(erlang:length(Diff), 0).
+ ?assertEqual(length(Diff), 0).
get_duplicates(List) ->
List -- sets:to_list(couch_util:set_from_list(List)).
@@ -158,7 +158,7 @@ t_starts_with_couchdb(Port) ->
{match, _} ->
ok;
nomatch ->
- erlang:error(
+ error(
{assertRegexp_failed, [
{module, ?MODULE},
{line, ?LINE},
diff --git a/src/couch_pse_tests/src/cpse_test_ref_counting.erl b/src/couch_pse_tests/src/cpse_test_ref_counting.erl
index e56321080..401353f37 100644
--- a/src/couch_pse_tests/src/cpse_test_ref_counting.erl
+++ b/src/couch_pse_tests/src/cpse_test_ref_counting.erl
@@ -82,7 +82,7 @@ start_client(Db0) ->
{waiting, Pid} ->
Pid ! go
after 1000 ->
- erlang:error(timeout)
+ error(timeout)
end,
receive
@@ -90,7 +90,7 @@ start_client(Db0) ->
couch_db:close(Db1),
ok
after 1000 ->
- erlang:error(timeout)
+ error(timeout)
end
end).
@@ -99,7 +99,7 @@ wait_client({Pid, _Ref}) ->
receive
go -> ok
after 1000 ->
- erlang:error(timeout)
+ error(timeout)
end.
close_client({Pid, Ref}) ->
@@ -108,5 +108,5 @@ close_client({Pid, Ref}) ->
{'DOWN', Ref, _, _, _} ->
ok
after 1000 ->
- erlang:error(timeout)
+ error(timeout)
end.
diff --git a/src/couch_pse_tests/src/cpse_util.erl b/src/couch_pse_tests/src/cpse_util.erl
index c5aac94c0..bd17de26b 100644
--- a/src/couch_pse_tests/src/cpse_util.erl
+++ b/src/couch_pse_tests/src/cpse_util.erl
@@ -95,13 +95,13 @@ open_db(DbName) ->
shutdown_db(Db) ->
Pid = couch_db:get_pid(Db),
- Ref = erlang:monitor(process, Pid),
+ Ref = monitor(process, Pid),
exit(Pid, kill),
receive
{'DOWN', Ref, _, _, _} ->
ok
after ?SHUTDOWN_TIMEOUT ->
- erlang:error(database_shutdown_timeout)
+ error(database_shutdown_timeout)
end,
test_util:wait(fun() ->
case
@@ -189,7 +189,7 @@ assert_db_props(Module, Line, DbName, Props) when is_binary(DbName) ->
catch
error:{assertEqual, Props} ->
{_, Rest} = proplists:split(Props, [module, line]),
- erlang:error({assertEqual, [{module, Module}, {line, Line} | Rest]})
+ error({assertEqual, [{module, Module}, {line, Line} | Rest]})
after
couch_db:close(Db)
end;
@@ -199,7 +199,7 @@ assert_db_props(Module, Line, Db, Props) ->
catch
error:{assertEqual, Props} ->
{_, Rest} = proplists:split(Props, [module, line]),
- erlang:error({assertEqual, [{module, Module}, {line, Line} | Rest]})
+ error({assertEqual, [{module, Module}, {line, Line} | Rest]})
end.
assert_each_prop(_Db, []) ->
@@ -309,7 +309,7 @@ gen_write(Db, {Action, {<<"_local/", _/binary>> = DocId, Body}}) ->
end,
{local, #doc{
id = DocId,
- revs = {0, [list_to_binary(integer_to_list(RevId))]},
+ revs = {0, [integer_to_binary(RevId)]},
body = Body,
deleted = Deleted
}};
@@ -387,7 +387,7 @@ prep_atts(Db, [{FileName, Data} | Rest]) ->
{'DOWN', Ref, _, _, Resp} ->
Resp
after ?ATTACHMENT_WRITE_TIMEOUT ->
- erlang:error(attachment_write_timeout)
+ error(attachment_write_timeout)
end,
[Att | prep_atts(Db, Rest)].
@@ -617,7 +617,7 @@ list_diff([T1 | R1], [T2 | R2]) ->
compact(Db) ->
{ok, Pid} = couch_db:start_compact(Db),
- Ref = erlang:monitor(process, Pid),
+ Ref = monitor(process, Pid),
% Ideally I'd assert that Pid is linked to us
% at this point but its technically possible
@@ -630,9 +630,9 @@ compact(Db) ->
{'DOWN', Ref, _, _, noproc} ->
ok;
{'DOWN', Ref, _, _, Reason} ->
- erlang:error({compactor_died, Reason})
+ error({compactor_died, Reason})
after ?COMPACTOR_TIMEOUT ->
- erlang:error(compactor_timed_out)
+ error(compactor_timed_out)
end,
test_util:wait(fun() ->
diff --git a/src/couch_quickjs/.gitignore b/src/couch_quickjs/.gitignore
index dd78afee1..f7d339351 100644
--- a/src/couch_quickjs/.gitignore
+++ b/src/couch_quickjs/.gitignore
@@ -16,6 +16,8 @@
/quickjs/qjscalc.c
/quickjs/repl.c
/quickjs/run-test262
+/quickjs/test262_report.txt
+/quickjs/test262/
/quickjs/test_fib.c
/quickjs/.github
compile_commands.json
diff --git a/src/couch_quickjs/c_src/couchjs.c b/src/couch_quickjs/c_src/couchjs.c
index 7958acda5..420f5f41d 100644
--- a/src/couch_quickjs/c_src/couchjs.c
+++ b/src/couch_quickjs/c_src/couchjs.c
@@ -86,14 +86,20 @@ static CmdType parse_command(char* str, size_t len) {
return CMD_VIEW;
}
-static void add_cx_methods(JSContext* cx) {
+// Return true if initializations succeed and false if any fails. Failure
+// will shortcut the sequence and will return early. The only thing to do
+// then is to free the context and return early
+//
+static bool add_cx_methods(JSContext* cx) {
//TODO: configure some features with env vars of command line switches
- JS_AddIntrinsicBaseObjects(cx);
- JS_AddIntrinsicEval(cx);
- JS_AddIntrinsicJSON(cx);
- JS_AddIntrinsicRegExp(cx);
- JS_AddIntrinsicMapSet(cx);
- JS_AddIntrinsicDate(cx);
+ return ! (
+ JS_AddIntrinsicBaseObjects(cx) ||
+ JS_AddIntrinsicEval(cx) ||
+ JS_AddIntrinsicJSON(cx) ||
+ JS_AddIntrinsicRegExp(cx) ||
+ JS_AddIntrinsicMapSet(cx) ||
+ JS_AddIntrinsicDate(cx)
+ );
}
// Creates a new JSContext with only the provided sandbox function
@@ -104,7 +110,12 @@ static JSContext* make_sandbox(JSContext* cx, JSValue sbox) {
if(!cx1) {
return NULL;
}
- add_cx_methods(cx1);
+
+ if(!add_cx_methods(cx1)) {
+ JS_FreeContext(cx1);
+ return NULL;
+ }
+
JSValue global = JS_GetGlobalObject(cx1);
int i;
diff --git a/src/couch_quickjs/patches/01-spidermonkey-185-mode.patch b/src/couch_quickjs/patches/01-spidermonkey-185-mode.patch
index 6b65fe4f6..f50c02bf9 100644
--- a/src/couch_quickjs/patches/01-spidermonkey-185-mode.patch
+++ b/src/couch_quickjs/patches/01-spidermonkey-185-mode.patch
@@ -1,6 +1,6 @@
---- quickjs-master/quickjs.c 2025-04-30 08:12:10
-+++ quickjs/quickjs.c 2025-04-30 13:50:44
-@@ -30110,10 +30110,24 @@
+--- quickjs-master/quickjs.c 2025-11-05 05:46:20
++++ quickjs/quickjs.c 2025-11-05 09:54:50
+@@ -31286,10 +31286,24 @@
if (s->token.val == TOK_FUNCTION ||
(token_is_pseudo_keyword(s, JS_ATOM_async) &&
peek_token(s, TRUE) == TOK_FUNCTION)) {
diff --git a/src/couch_quickjs/patches/02-test262-errors.patch b/src/couch_quickjs/patches/02-test262-errors.patch
new file mode 100644
index 000000000..267bcb6c8
--- /dev/null
+++ b/src/couch_quickjs/patches/02-test262-errors.patch
@@ -0,0 +1,11 @@
+--- quickjs-master/test262_errors.txt 2025-11-05 05:46:20
++++ quickjs/test262_errors.txt 2025-11-05 09:54:50
+@@ -19,6 +19,8 @@
+ test262/test/language/expressions/compound-assignment/S11.13.2_A6.10_T1.js:24: Test262Error: #1: innerX === 2. Actual: 5
+ test262/test/language/expressions/compound-assignment/S11.13.2_A6.11_T1.js:24: Test262Error: #1: innerX === 2. Actual: 5
+ test262/test/language/identifier-resolution/assign-to-global-undefined.js:20: strict mode: expected error
++test262/test/language/statements/expression/S12.4_A1.js:15: unexpected error type: Test262: This statement should not be evaluated.
++test262/test/language/statements/expression/S12.4_A1.js:15: strict mode: unexpected error type: Test262: This statement should not be evaluated.
+ test262/test/staging/sm/Function/arguments-parameter-shadowing.js:14: Test262Error: Expected SameValue(«true», «false») to be true
+ test262/test/staging/sm/Function/constructor-binding.js:11: Test262Error: Expected SameValue(«"function"», «"undefined"») to be true
+ test262/test/staging/sm/Function/constructor-binding.js:11: strict mode: Test262Error: Expected SameValue(«"function"», «"undefined"») to be true
diff --git a/src/couch_quickjs/quickjs/Changelog b/src/couch_quickjs/quickjs/Changelog
index 7cc33993d..7d6afd6da 100644
--- a/src/couch_quickjs/quickjs/Changelog
+++ b/src/couch_quickjs/quickjs/Changelog
@@ -1,3 +1,31 @@
+- micro optimizations (15% faster on bench-v8)
+- added resizable array buffers
+- added ArrayBuffer.prototype.transfer
+- added the Iterator object and methods
+- added set methods
+- added Atomics.pause
+- added added Map and WeakMap upsert methods
+- added Math.sumPrecise()
+- misc bug fixes
+
+2025-09-13:
+
+- added JSON modules and import attributes
+- added JS_PrintValue() API
+- qjs: pretty print objects in print() and console.log()
+- qjs: better promise rejection tracker heuristics
+- added RegExp v flag
+- added RegExp modifiers
+- added RegExp.escape
+- added Float16Array
+- added Promise.try
+- improved JSON parser spec conformance
+- qjs: improved compatibility of std.parseExtJSON() with JSON5 and
+ accept JSON5 modules
+- added JS_FreePropertyEnum() and JS_AtomToCStringLen() API
+- added Error.isError()
+- misc bug fixes
+
2025-04-26:
- removed the bignum extensions and qjscalc
diff --git a/src/couch_quickjs/quickjs/Makefile b/src/couch_quickjs/quickjs/Makefile
index 3b1c74594..ba64923d2 100644
--- a/src/couch_quickjs/quickjs/Makefile
+++ b/src/couch_quickjs/quickjs/Makefile
@@ -54,6 +54,10 @@ PREFIX?=/usr/local
# use UB sanitizer
#CONFIG_UBSAN=y
+# TEST262 bootstrap config: commit id and shallow "since" parameter
+TEST262_COMMIT?=42303c7c2bcf1c1edb9e5375c291c6fbc8a261ab
+TEST262_SINCE?=2025-09-01
+
OBJDIR=.obj
ifdef CONFIG_ASAN
@@ -464,6 +468,15 @@ stats: qjs$(EXE)
microbench: qjs$(EXE)
$(WINE) ./qjs$(EXE) --std tests/microbench.js
+ifeq ($(wildcard test262/features.txt),)
+test2-bootstrap:
+ git clone --single-branch --shallow-since=$(TEST262_SINCE) https://github.com/tc39/test262.git
+ (cd test262 && git checkout -q $(TEST262_COMMIT) && patch -p1 < ../tests/test262.patch && cd ..)
+else
+test2-bootstrap:
+ (cd test262 && git fetch && git reset --hard $(TEST262_COMMIT) && patch -p1 < ../tests/test262.patch && cd ..)
+endif
+
ifeq ($(wildcard test262o/tests.txt),)
test2o test2o-update:
@echo test262o tests not installed
diff --git a/src/couch_quickjs/quickjs/VERSION b/src/couch_quickjs/quickjs/VERSION
index c76e76d1f..433b8f85b 100644
--- a/src/couch_quickjs/quickjs/VERSION
+++ b/src/couch_quickjs/quickjs/VERSION
@@ -1 +1 @@
-2025-04-26
+2025-09-13
diff --git a/src/couch_quickjs/quickjs/cutils.c b/src/couch_quickjs/quickjs/cutils.c
index c038cf44c..52ff1649b 100644
--- a/src/couch_quickjs/quickjs/cutils.c
+++ b/src/couch_quickjs/quickjs/cutils.c
@@ -100,15 +100,20 @@ void dbuf_init(DynBuf *s)
dbuf_init2(s, NULL, NULL);
}
-/* return < 0 if error */
-int dbuf_realloc(DynBuf *s, size_t new_size)
+/* Try to allocate 'len' more bytes. return < 0 if error */
+int dbuf_claim(DynBuf *s, size_t len)
{
- size_t size;
+ size_t new_size, size;
uint8_t *new_buf;
+ new_size = s->size + len;
+ if (new_size < len)
+ return -1; /* overflow case */
if (new_size > s->allocated_size) {
if (s->error)
return -1;
- size = s->allocated_size * 3 / 2;
+ size = s->allocated_size + (s->allocated_size / 2);
+ if (size < s->allocated_size)
+ return -1; /* overflow case */
if (size > new_size)
new_size = size;
new_buf = s->realloc_func(s->opaque, s->buf, new_size);
@@ -122,22 +127,10 @@ int dbuf_realloc(DynBuf *s, size_t new_size)
return 0;
}
-int dbuf_write(DynBuf *s, size_t offset, const uint8_t *data, size_t len)
-{
- size_t end;
- end = offset + len;
- if (dbuf_realloc(s, end))
- return -1;
- memcpy(s->buf + offset, data, len);
- if (end > s->size)
- s->size = end;
- return 0;
-}
-
int dbuf_put(DynBuf *s, const uint8_t *data, size_t len)
{
- if (unlikely((s->size + len) > s->allocated_size)) {
- if (dbuf_realloc(s, s->size + len))
+ if (unlikely((s->allocated_size - s->size) < len)) {
+ if (dbuf_claim(s, len))
return -1;
}
memcpy_no_ub(s->buf + s->size, data, len);
@@ -147,8 +140,8 @@ int dbuf_put(DynBuf *s, const uint8_t *data, size_t len)
int dbuf_put_self(DynBuf *s, size_t offset, size_t len)
{
- if (unlikely((s->size + len) > s->allocated_size)) {
- if (dbuf_realloc(s, s->size + len))
+ if (unlikely((s->allocated_size - s->size) < len)) {
+ if (dbuf_claim(s, len))
return -1;
}
memcpy(s->buf + s->size, s->buf + offset, len);
@@ -156,11 +149,26 @@ int dbuf_put_self(DynBuf *s, size_t offset, size_t len)
return 0;
}
-int dbuf_putc(DynBuf *s, uint8_t c)
+int __dbuf_putc(DynBuf *s, uint8_t c)
{
return dbuf_put(s, &c, 1);
}
+int __dbuf_put_u16(DynBuf *s, uint16_t val)
+{
+ return dbuf_put(s, (uint8_t *)&val, 2);
+}
+
+int __dbuf_put_u32(DynBuf *s, uint32_t val)
+{
+ return dbuf_put(s, (uint8_t *)&val, 4);
+}
+
+int __dbuf_put_u64(DynBuf *s, uint64_t val)
+{
+ return dbuf_put(s, (uint8_t *)&val, 8);
+}
+
int dbuf_putstr(DynBuf *s, const char *str)
{
return dbuf_put(s, (const uint8_t *)str, strlen(str));
@@ -182,7 +190,7 @@ int __attribute__((format(printf, 2, 3))) dbuf_printf(DynBuf *s,
/* fast case */
return dbuf_put(s, (uint8_t *)buf, len);
} else {
- if (dbuf_realloc(s, s->size + len + 1))
+ if (dbuf_claim(s, len + 1))
return -1;
va_start(ap, fmt);
vsnprintf((char *)(s->buf + s->size), s->allocated_size - s->size,
diff --git a/src/couch_quickjs/quickjs/cutils.h b/src/couch_quickjs/quickjs/cutils.h
index 32b97579d..094a8f124 100644
--- a/src/couch_quickjs/quickjs/cutils.h
+++ b/src/couch_quickjs/quickjs/cutils.h
@@ -264,24 +264,58 @@ typedef struct DynBuf {
void dbuf_init(DynBuf *s);
void dbuf_init2(DynBuf *s, void *opaque, DynBufReallocFunc *realloc_func);
-int dbuf_realloc(DynBuf *s, size_t new_size);
-int dbuf_write(DynBuf *s, size_t offset, const uint8_t *data, size_t len);
+int dbuf_claim(DynBuf *s, size_t len);
int dbuf_put(DynBuf *s, const uint8_t *data, size_t len);
int dbuf_put_self(DynBuf *s, size_t offset, size_t len);
-int dbuf_putc(DynBuf *s, uint8_t c);
int dbuf_putstr(DynBuf *s, const char *str);
+int __dbuf_putc(DynBuf *s, uint8_t c);
+int __dbuf_put_u16(DynBuf *s, uint16_t val);
+int __dbuf_put_u32(DynBuf *s, uint32_t val);
+int __dbuf_put_u64(DynBuf *s, uint64_t val);
+
+static inline int dbuf_putc(DynBuf *s, uint8_t val)
+{
+ if (unlikely((s->allocated_size - s->size) < 1)) {
+ return __dbuf_putc(s, val);
+ } else {
+ s->buf[s->size++] = val;
+ return 0;
+ }
+}
+
static inline int dbuf_put_u16(DynBuf *s, uint16_t val)
{
- return dbuf_put(s, (uint8_t *)&val, 2);
+ if (unlikely((s->allocated_size - s->size) < 2)) {
+ return __dbuf_put_u16(s, val);
+ } else {
+ put_u16(s->buf + s->size, val);
+ s->size += 2;
+ return 0;
+ }
}
+
static inline int dbuf_put_u32(DynBuf *s, uint32_t val)
{
- return dbuf_put(s, (uint8_t *)&val, 4);
+ if (unlikely((s->allocated_size - s->size) < 4)) {
+ return __dbuf_put_u32(s, val);
+ } else {
+ put_u32(s->buf + s->size, val);
+ s->size += 4;
+ return 0;
+ }
}
+
static inline int dbuf_put_u64(DynBuf *s, uint64_t val)
{
- return dbuf_put(s, (uint8_t *)&val, 8);
+ if (unlikely((s->allocated_size - s->size) < 8)) {
+ return __dbuf_put_u64(s, val);
+ } else {
+ put_u64(s->buf + s->size, val);
+ s->size += 8;
+ return 0;
+ }
}
+
int __attribute__((format(printf, 2, 3))) dbuf_printf(DynBuf *s,
const char *fmt, ...);
void dbuf_free(DynBuf *s);
@@ -364,4 +398,60 @@ static inline double uint64_as_float64(uint64_t u64)
return u.d;
}
+static inline double fromfp16(uint16_t v)
+{
+ double d;
+ uint32_t v1;
+ v1 = v & 0x7fff;
+ if (unlikely(v1 >= 0x7c00))
+ v1 += 0x1f8000; /* NaN or infinity */
+ d = uint64_as_float64(((uint64_t)(v >> 15) << 63) | ((uint64_t)v1 << (52 - 10)));
+ return d * 0x1p1008;
+}
+
+static inline uint16_t tofp16(double d)
+{
+ uint64_t a, addend;
+ uint32_t v, sgn;
+ int shift;
+
+ a = float64_as_uint64(d);
+ sgn = a >> 63;
+ a = a & 0x7fffffffffffffff;
+ if (unlikely(a > 0x7ff0000000000000)) {
+ /* nan */
+ v = 0x7c01;
+ } else if (a < 0x3f10000000000000) { /* 0x1p-14 */
+ /* subnormal f16 number or zero */
+ if (a <= 0x3e60000000000000) { /* 0x1p-25 */
+ v = 0x0000; /* zero */
+ } else {
+ shift = 1051 - (a >> 52);
+ a = ((uint64_t)1 << 52) | (a & (((uint64_t)1 << 52) - 1));
+ addend = ((a >> shift) & 1) + (((uint64_t)1 << (shift - 1)) - 1);
+ v = (a + addend) >> shift;
+ }
+ } else {
+ /* normal number or infinity */
+ a -= 0x3f00000000000000; /* adjust the exponent */
+ /* round */
+ addend = ((a >> (52 - 10)) & 1) + (((uint64_t)1 << (52 - 11)) - 1);
+ v = (a + addend) >> (52 - 10);
+ /* overflow ? */
+ if (unlikely(v > 0x7c00))
+ v = 0x7c00;
+ }
+ return v | (sgn << 15);
+}
+
+static inline int isfp16nan(uint16_t v)
+{
+ return (v & 0x7FFF) > 0x7C00;
+}
+
+static inline int isfp16zero(uint16_t v)
+{
+ return (v & 0x7FFF) == 0;
+}
+
#endif /* CUTILS_H */
diff --git a/src/couch_quickjs/quickjs/libregexp-opcode.h b/src/couch_quickjs/quickjs/libregexp-opcode.h
index f255e09f2..ebab751df 100644
--- a/src/couch_quickjs/quickjs/libregexp-opcode.h
+++ b/src/couch_quickjs/quickjs/libregexp-opcode.h
@@ -26,11 +26,15 @@
DEF(invalid, 1) /* never used */
DEF(char, 3)
+DEF(char_i, 3)
DEF(char32, 5)
+DEF(char32_i, 5)
DEF(dot, 1)
DEF(any, 1) /* same as dot but match any character including line terminator */
DEF(line_start, 1)
+DEF(line_start_m, 1)
DEF(line_end, 1)
+DEF(line_end_m, 1)
DEF(goto, 5)
DEF(split_goto_first, 5)
DEF(split_next_first, 5)
@@ -42,11 +46,17 @@ DEF(loop, 5) /* decrement the top the stack and goto if != 0 */
DEF(push_i32, 5) /* push integer on the stack */
DEF(drop, 1)
DEF(word_boundary, 1)
+DEF(word_boundary_i, 1)
DEF(not_word_boundary, 1)
+DEF(not_word_boundary_i, 1)
DEF(back_reference, 2)
-DEF(backward_back_reference, 2) /* must come after back_reference */
+DEF(back_reference_i, 2) /* must come after */
+DEF(backward_back_reference, 2) /* must come after */
+DEF(backward_back_reference_i, 2) /* must come after */
DEF(range, 3) /* variable length */
+DEF(range_i, 3) /* variable length */
DEF(range32, 3) /* variable length */
+DEF(range32_i, 3) /* variable length */
DEF(lookahead, 5)
DEF(negative_lookahead, 5)
DEF(push_char_pos, 1) /* push the character position on the stack */
diff --git a/src/couch_quickjs/quickjs/libregexp.c b/src/couch_quickjs/quickjs/libregexp.c
index 8c4738985..118d950eb 100644
--- a/src/couch_quickjs/quickjs/libregexp.c
+++ b/src/couch_quickjs/quickjs/libregexp.c
@@ -71,7 +71,9 @@ typedef struct {
const uint8_t *buf_start;
int re_flags;
BOOL is_unicode;
+ BOOL unicode_sets; /* if set, is_unicode is also set */
BOOL ignore_case;
+ BOOL multi_line;
BOOL dotall;
int capture_count;
int total_capture_count; /* -1 = not computed yet */
@@ -102,11 +104,11 @@ static const REOpCode reopcode_info[REOP_COUNT] = {
};
#define RE_HEADER_FLAGS 0
-#define RE_HEADER_CAPTURE_COUNT 1
-#define RE_HEADER_STACK_SIZE 2
-#define RE_HEADER_BYTECODE_LEN 3
+#define RE_HEADER_CAPTURE_COUNT 2
+#define RE_HEADER_STACK_SIZE 3
+#define RE_HEADER_BYTECODE_LEN 4
-#define RE_HEADER_LEN 7
+#define RE_HEADER_LEN 8
static inline int is_digit(int c) {
return c >= '0' && c <= '9';
@@ -115,13 +117,271 @@ static inline int is_digit(int c) {
/* insert 'len' bytes at position 'pos'. Return < 0 if error. */
static int dbuf_insert(DynBuf *s, int pos, int len)
{
- if (dbuf_realloc(s, s->size + len))
+ if (dbuf_claim(s, len))
return -1;
memmove(s->buf + pos + len, s->buf + pos, s->size - pos);
s->size += len;
return 0;
}
+typedef struct REString {
+ struct REString *next;
+ uint32_t hash;
+ uint32_t len;
+ uint32_t buf[];
+} REString;
+
+typedef struct {
+ /* the string list is the union of 'char_range' and of the strings
+ in hash_table[]. The strings in hash_table[] have a length !=
+ 1. */
+ CharRange cr;
+ uint32_t n_strings;
+ uint32_t hash_size;
+ int hash_bits;
+ REString **hash_table;
+} REStringList;
+
+static uint32_t re_string_hash(int len, const uint32_t *buf)
+{
+ int i;
+ uint32_t h;
+ h = 1;
+ for(i = 0; i < len; i++)
+ h = h * 263 + buf[i];
+ return h * 0x61C88647;
+}
+
+static void re_string_list_init(REParseState *s1, REStringList *s)
+{
+ cr_init(&s->cr, s1->opaque, lre_realloc);
+ s->n_strings = 0;
+ s->hash_size = 0;
+ s->hash_bits = 0;
+ s->hash_table = NULL;
+}
+
+static void re_string_list_free(REStringList *s)
+{
+ REString *p, *p_next;
+ int i;
+ for(i = 0; i < s->hash_size; i++) {
+ for(p = s->hash_table[i]; p != NULL; p = p_next) {
+ p_next = p->next;
+ lre_realloc(s->cr.mem_opaque, p, 0);
+ }
+ }
+ lre_realloc(s->cr.mem_opaque, s->hash_table, 0);
+
+ cr_free(&s->cr);
+}
+
+static void lre_print_char(int c, BOOL is_range)
+{
+ if (c == '\'' || c == '\\' ||
+ (is_range && (c == '-' || c == ']'))) {
+ printf("\\%c", c);
+ } else if (c >= ' ' && c <= 126) {
+ printf("%c", c);
+ } else {
+ printf("\\u{%04x}", c);
+ }
+}
+
+static __maybe_unused void re_string_list_dump(const char *str, const REStringList *s)
+{
+ REString *p;
+ const CharRange *cr;
+ int i, j, k;
+
+ printf("%s:\n", str);
+ printf(" ranges: [");
+ cr = &s->cr;
+ for(i = 0; i < cr->len; i += 2) {
+ lre_print_char(cr->points[i], TRUE);
+ if (cr->points[i] != cr->points[i + 1] - 1) {
+ printf("-");
+ lre_print_char(cr->points[i + 1] - 1, TRUE);
+ }
+ }
+ printf("]\n");
+
+ j = 0;
+ for(i = 0; i < s->hash_size; i++) {
+ for(p = s->hash_table[i]; p != NULL; p = p->next) {
+ printf(" %d/%d: '", j, s->n_strings);
+ for(k = 0; k < p->len; k++) {
+ lre_print_char(p->buf[k], FALSE);
+ }
+ printf("'\n");
+ j++;
+ }
+ }
+}
+
+static int re_string_find2(REStringList *s, int len, const uint32_t *buf,
+ uint32_t h0, BOOL add_flag)
+{
+ uint32_t h = 0; /* avoid warning */
+ REString *p;
+ if (s->n_strings != 0) {
+ h = h0 >> (32 - s->hash_bits);
+ for(p = s->hash_table[h]; p != NULL; p = p->next) {
+ if (p->hash == h0 && p->len == len &&
+ !memcmp(p->buf, buf, len * sizeof(buf[0]))) {
+ return 1;
+ }
+ }
+ }
+ /* not found */
+ if (!add_flag)
+ return 0;
+ /* increase the size of the hash table if needed */
+ if (unlikely((s->n_strings + 1) > s->hash_size)) {
+ REString **new_hash_table, *p_next;
+ int new_hash_bits, i;
+ uint32_t new_hash_size;
+ new_hash_bits = max_int(s->hash_bits + 1, 4);
+ new_hash_size = 1 << new_hash_bits;
+ new_hash_table = lre_realloc(s->cr.mem_opaque, NULL,
+ sizeof(new_hash_table[0]) * new_hash_size);
+ if (!new_hash_table)
+ return -1;
+ memset(new_hash_table, 0, sizeof(new_hash_table[0]) * new_hash_size);
+ for(i = 0; i < s->hash_size; i++) {
+ for(p = s->hash_table[i]; p != NULL; p = p_next) {
+ p_next = p->next;
+ h = p->hash >> (32 - new_hash_bits);
+ p->next = new_hash_table[h];
+ new_hash_table[h] = p;
+ }
+ }
+ lre_realloc(s->cr.mem_opaque, s->hash_table, 0);
+ s->hash_bits = new_hash_bits;
+ s->hash_size = new_hash_size;
+ s->hash_table = new_hash_table;
+ h = h0 >> (32 - s->hash_bits);
+ }
+
+ p = lre_realloc(s->cr.mem_opaque, NULL, sizeof(REString) + len * sizeof(buf[0]));
+ if (!p)
+ return -1;
+ p->next = s->hash_table[h];
+ s->hash_table[h] = p;
+ s->n_strings++;
+ p->hash = h0;
+ p->len = len;
+ memcpy(p->buf, buf, sizeof(buf[0]) * len);
+ return 1;
+}
+
+static int re_string_find(REStringList *s, int len, const uint32_t *buf,
+ BOOL add_flag)
+{
+ uint32_t h0;
+ h0 = re_string_hash(len, buf);
+ return re_string_find2(s, len, buf, h0, add_flag);
+}
+
+/* return -1 if memory error, 0 if OK */
+static int re_string_add(REStringList *s, int len, const uint32_t *buf)
+{
+ if (len == 1) {
+ return cr_union_interval(&s->cr, buf[0], buf[0]);
+ }
+ if (re_string_find(s, len, buf, TRUE) < 0)
+ return -1;
+ return 0;
+}
+
+/* a = a op b */
+static int re_string_list_op(REStringList *a, REStringList *b, int op)
+{
+ int i, ret;
+ REString *p, **pp;
+
+ if (cr_op1(&a->cr, b->cr.points, b->cr.len, op))
+ return -1;
+
+ switch(op) {
+ case CR_OP_UNION:
+ if (b->n_strings != 0) {
+ for(i = 0; i < b->hash_size; i++) {
+ for(p = b->hash_table[i]; p != NULL; p = p->next) {
+ if (re_string_find2(a, p->len, p->buf, p->hash, TRUE) < 0)
+ return -1;
+ }
+ }
+ }
+ break;
+ case CR_OP_INTER:
+ case CR_OP_SUB:
+ for(i = 0; i < a->hash_size; i++) {
+ pp = &a->hash_table[i];
+ for(;;) {
+ p = *pp;
+ if (p == NULL)
+ break;
+ ret = re_string_find2(b, p->len, p->buf, p->hash, FALSE);
+ if (op == CR_OP_SUB)
+ ret = !ret;
+ if (!ret) {
+ /* remove it */
+ *pp = p->next;
+ a->n_strings--;
+ lre_realloc(a->cr.mem_opaque, p, 0);
+ } else {
+ /* keep it */
+ pp = &p->next;
+ }
+ }
+ }
+ break;
+ default:
+ abort();
+ }
+ return 0;
+}
+
+static int re_string_list_canonicalize(REParseState *s1,
+ REStringList *s, BOOL is_unicode)
+{
+ if (cr_regexp_canonicalize(&s->cr, is_unicode))
+ return -1;
+ if (s->n_strings != 0) {
+ REStringList a_s, *a = &a_s;
+ int i, j;
+ REString *p;
+
+ /* XXX: simplify */
+ re_string_list_init(s1, a);
+
+ a->n_strings = s->n_strings;
+ a->hash_size = s->hash_size;
+ a->hash_bits = s->hash_bits;
+ a->hash_table = s->hash_table;
+
+ s->n_strings = 0;
+ s->hash_size = 0;
+ s->hash_bits = 0;
+ s->hash_table = NULL;
+
+ for(i = 0; i < a->hash_size; i++) {
+ for(p = a->hash_table[i]; p != NULL; p = p->next) {
+ for(j = 0; j < p->len; j++) {
+ p->buf[j] = lre_canonicalize(p->buf[j], is_unicode);
+ }
+ if (re_string_add(s, p->len, p->buf)) {
+ re_string_list_free(a);
+ return -1;
+ }
+ }
+ }
+ re_string_list_free(a);
+ }
+ return 0;
+}
+
static const uint16_t char_range_d[] = {
1,
0x0030, 0x0039 + 1,
@@ -170,7 +430,7 @@ static const uint16_t * const char_range_table[] = {
char_range_w,
};
-static int cr_init_char_range(REParseState *s, CharRange *cr, uint32_t c)
+static int cr_init_char_range(REParseState *s, REStringList *cr, uint32_t c)
{
BOOL invert;
const uint16_t *c_pt;
@@ -179,18 +439,18 @@ static int cr_init_char_range(REParseState *s, CharRange *cr, uint32_t c)
invert = c & 1;
c_pt = char_range_table[c >> 1];
len = *c_pt++;
- cr_init(cr, s->opaque, lre_realloc);
+ re_string_list_init(s, cr);
for(i = 0; i < len * 2; i++) {
- if (cr_add_point(cr, c_pt[i]))
+ if (cr_add_point(&cr->cr, c_pt[i]))
goto fail;
}
if (invert) {
- if (cr_invert(cr))
+ if (cr_invert(&cr->cr))
goto fail;
}
return 0;
fail:
- cr_free(cr);
+ re_string_list_free(cr);
return -1;
}
@@ -240,6 +500,7 @@ static __maybe_unused void lre_dump_bytecode(const uint8_t *buf,
printf("%s", reopcode_info[opcode].name);
switch(opcode) {
case REOP_char:
+ case REOP_char_i:
val = get_u16(buf + pos + 1);
if (val >= ' ' && val <= 126)
printf(" '%c'", val);
@@ -247,6 +508,7 @@ static __maybe_unused void lre_dump_bytecode(const uint8_t *buf,
printf(" 0x%04x", val);
break;
case REOP_char32:
+ case REOP_char32_i:
val = get_u32(buf + pos + 1);
if (val >= ' ' && val <= 126)
printf(" '%c'", val);
@@ -273,7 +535,9 @@ static __maybe_unused void lre_dump_bytecode(const uint8_t *buf,
case REOP_save_start:
case REOP_save_end:
case REOP_back_reference:
+ case REOP_back_reference_i:
case REOP_backward_back_reference:
+ case REOP_backward_back_reference_i:
printf(" %u", buf[pos + 1]);
break;
case REOP_save_reset:
@@ -284,6 +548,7 @@ static __maybe_unused void lre_dump_bytecode(const uint8_t *buf,
printf(" %d", val);
break;
case REOP_range:
+ case REOP_range_i:
{
int n, i;
n = get_u16(buf + pos + 1);
@@ -295,6 +560,7 @@ static __maybe_unused void lre_dump_bytecode(const uint8_t *buf,
}
break;
case REOP_range32:
+ case REOP_range32_i:
{
int n, i;
n = get_u16(buf + pos + 1);
@@ -533,8 +799,16 @@ static BOOL is_unicode_char(int c)
(c == '_'));
}
-static int parse_unicode_property(REParseState *s, CharRange *cr,
- const uint8_t **pp, BOOL is_inv)
+/* XXX: memory error test */
+static void seq_prop_cb(void *opaque, const uint32_t *seq, int seq_len)
+{
+ REStringList *sl = opaque;
+ re_string_add(sl, seq_len, seq);
+}
+
+static int parse_unicode_property(REParseState *s, REStringList *cr,
+ const uint8_t **pp, BOOL is_inv,
+ BOOL allow_sequence_prop)
{
const uint8_t *p;
char name[64], value[64];
@@ -574,51 +848,76 @@ static int parse_unicode_property(REParseState *s, CharRange *cr,
} else if (!strcmp(name, "Script_Extensions") || !strcmp(name, "scx")) {
script_ext = TRUE;
do_script:
- cr_init(cr, s->opaque, lre_realloc);
- ret = unicode_script(cr, value, script_ext);
+ re_string_list_init(s, cr);
+ ret = unicode_script(&cr->cr, value, script_ext);
if (ret) {
- cr_free(cr);
+ re_string_list_free(cr);
if (ret == -2)
return re_parse_error(s, "unknown unicode script");
else
goto out_of_memory;
}
} else if (!strcmp(name, "General_Category") || !strcmp(name, "gc")) {
- cr_init(cr, s->opaque, lre_realloc);
- ret = unicode_general_category(cr, value);
+ re_string_list_init(s, cr);
+ ret = unicode_general_category(&cr->cr, value);
if (ret) {
- cr_free(cr);
+ re_string_list_free(cr);
if (ret == -2)
return re_parse_error(s, "unknown unicode general category");
else
goto out_of_memory;
}
} else if (value[0] == '\0') {
- cr_init(cr, s->opaque, lre_realloc);
- ret = unicode_general_category(cr, name);
+ re_string_list_init(s, cr);
+ ret = unicode_general_category(&cr->cr, name);
if (ret == -1) {
- cr_free(cr);
+ re_string_list_free(cr);
goto out_of_memory;
}
if (ret < 0) {
- ret = unicode_prop(cr, name);
- if (ret) {
- cr_free(cr);
- if (ret == -2)
- goto unknown_property_name;
- else
- goto out_of_memory;
+ ret = unicode_prop(&cr->cr, name);
+ if (ret == -1) {
+ re_string_list_free(cr);
+ goto out_of_memory;
+ }
+ }
+ if (ret < 0 && !is_inv && allow_sequence_prop) {
+ CharRange cr_tmp;
+ cr_init(&cr_tmp, s->opaque, lre_realloc);
+ ret = unicode_sequence_prop(name, seq_prop_cb, cr, &cr_tmp);
+ cr_free(&cr_tmp);
+ if (ret == -1) {
+ re_string_list_free(cr);
+ goto out_of_memory;
}
}
+ if (ret < 0)
+ goto unknown_property_name;
} else {
unknown_property_name:
return re_parse_error(s, "unknown unicode property name");
}
+ /* the ordering of case folding and inversion differs with
+ unicode_sets. 'unicode_sets' ordering is more consistent */
+ /* XXX: the spec seems incorrect, we do it as the other engines
+ seem to do it. */
+ if (s->ignore_case && s->unicode_sets) {
+ if (re_string_list_canonicalize(s, cr, s->is_unicode)) {
+ re_string_list_free(cr);
+ goto out_of_memory;
+ }
+ }
if (is_inv) {
- if (cr_invert(cr)) {
- cr_free(cr);
- return -1;
+ if (cr_invert(&cr->cr)) {
+ re_string_list_free(cr);
+ goto out_of_memory;
+ }
+ }
+ if (s->ignore_case && !s->unicode_sets) {
+ if (re_string_list_canonicalize(s, cr, s->is_unicode)) {
+ re_string_list_free(cr);
+ goto out_of_memory;
}
}
*pp = p;
@@ -628,10 +927,61 @@ static int parse_unicode_property(REParseState *s, CharRange *cr,
}
#endif /* CONFIG_ALL_UNICODE */
+static int get_class_atom(REParseState *s, REStringList *cr,
+ const uint8_t **pp, BOOL inclass);
+
+static int parse_class_string_disjunction(REParseState *s, REStringList *cr,
+ const uint8_t **pp)
+{
+ const uint8_t *p;
+ DynBuf str;
+ int c;
+
+ p = *pp;
+ if (*p != '{')
+ return re_parse_error(s, "expecting '{' after \\q");
+
+ dbuf_init2(&str, s->opaque, lre_realloc);
+ re_string_list_init(s, cr);
... 28867 lines suppressed ...
(couchdb) 02/03: Bump version to 3.5.1
Posted by va...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
vatamane pushed a commit to branch 3.5.x
in repository https://gitbox.apache.org/repos/asf/couchdb.git
commit 449f5e2d728ad4cd123ebdab40bb5b4656e8d4a3
Author: Nick Vatamaniuc <va...@gmail.com>
AuthorDate: Thu Oct 30 00:33:51 2025 -0400
Bump version to 3.5.1
---
version.mk | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/version.mk b/version.mk
index 2a199c9ff..fd4879ca0 100644
--- a/version.mk
+++ b/version.mk
@@ -1,3 +1,3 @@
vsn_major=3
vsn_minor=5
-vsn_patch=0
+vsn_patch=1