Github user theburge commented on a diff in the pull request: https://github.com/apache/couchdb-couch/pull/185#discussion_r71323695 --- Diff: src/couch_file.erl --- @@ -524,6 +525,99 @@ handle_info({'EXIT', _, Reason}, Fd) -> {stop, Reason, Fd}. +%% first try to read header at end, falling back to chunked reads on failure +find_last_header(Fd, FileSize) -> + ok = file:advise(Fd, 0, FileSize, dont_need), % minimize disk cache pollution + Pos = (FileSize div ?SIZE_BLOCK) * ?SIZE_BLOCK, + case file:pread(Fd, Pos, FileSize - Pos) of + eof -> + no_valid_header; + {ok, Data} -> + try match_header(Fd, Pos, Data, 0) of + {ok, HeaderBin} -> + {ok, HeaderBin} + catch + error:{badmatch, _} -> + find_header_in_chunks(Fd, Pos, 1) + end + end. + +-define(DEFAULT_CHUNK_MAX_SIZE, ?SIZE_BLOCK). +-define(DEFAULT_CHUNK_EXPONENT_BASE, 1). + +chunk_max_size() -> + config:get_integer("couchdb", "chunk_max_size", ?DEFAULT_CHUNK_MAX_SIZE). + +%% chunk size exponentially increases by iteration, up to some maximum, +%% and should never exceed the current position in the file +chunk_size(Pos, Multiplier) -> + Size = min(Multiplier * ?SIZE_BLOCK, chunk_max_size()), + min(Pos, Size). + +multiplier(Size, Multiplier) -> + case Size < chunk_max_size() of + true -> + Multiplier * config:get_integer( + "couchdb", "chunk_exponent_base", ?DEFAULT_CHUNK_EXPONENT_BASE); + false -> + Multiplier + end. + +find_header_in_chunks(_Fd, Pos, _Multiplier) when Pos < 0 -> + no_valid_header; +find_header_in_chunks(Fd, Pos, Multiplier) -> + Size = chunk_size(Pos, Multiplier), + case Size > 0 of + false -> + no_valid_header; + true -> + {ok, Chunk} = file:pread(Fd, Pos - Size, Size), + case find_header_in_chunk(Fd, Pos, Chunk, Size) of + {ok, HeaderBin, _Offset} -> + %% io:format("found header at ~p multiplier ~p chunksize ~p~n", + %% [Pos - Size + _Offset, Multiplier, Size]), + {ok, HeaderBin}; + not_found -> + NewMultiplier = multiplier(Size, Multiplier), + find_header_in_chunks(Fd, Pos - Size, NewMultiplier) + end + end. + +find_header_in_chunk(_Fd, _Pos, _Chunk, Offset) when Offset < 0 -> --- End diff -- Is that guard correct? Or should it be `=<`? If `Offset = ?SIZE_BLOCK`, it looks to me that it would attempt the second clause of`find_header_in_chunk` twice, and presumably lead to a badmatch in `match_header`.
--- If your project is set up for it, you can reply to this email and have your reply appear on GitHub as well. If your project does not have this feature enabled and wishes so, or if the feature is enabled but not working, please contact infrastructure at infrastruct...@apache.org or file a JIRA ticket with INFRA. ---