pax_global_header00006660000000000000000000000064130126202670014511gustar00rootroot0000000000000052 comment=a717680bf5bf0c3e49810633d8f5534a8a698532 stockpile-0.0.4/000077500000000000000000000000001301262026700135075ustar00rootroot00000000000000stockpile-0.0.4/.gitignore000066400000000000000000000001771301262026700155040ustar00rootroot00000000000000*~ /.lein-* /.nrepl-port /checkouts/ /target/ # clj-i18n /mp-* /resources/locales.clj /resources/puppetlabs/stockpile/*.class stockpile-0.0.4/.travis.yml000066400000000000000000000001561301262026700156220ustar00rootroot00000000000000 language: clojure sudo: required dist: trusty jdk: - openjdk8 - openjdk7 script: ./run-test --use-sudo stockpile-0.0.4/LICENSE000066400000000000000000000261361301262026700145240ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] 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. stockpile-0.0.4/MAINTAINERS000066400000000000000000000006251301262026700152070ustar00rootroot00000000000000{ "version": 1, "file_format": "This MAINTAINERS file format is described at https://github.com/puppetlabs/maintainers", "issues": "https://tickets.puppet.com/browse/PDB", "people": [ { "github": "rbrw", "email": "rlb@puppet.com", "name": "Rob Browning", }, { "github": "senior", "email": "ryan.senior@puppet.com", "name": "Ryan Senior" } ] } stockpile-0.0.4/Makefile000066400000000000000000000000441301262026700151450ustar00rootroot00000000000000include dev-resources/Makefile.i18n stockpile-0.0.4/README.md000066400000000000000000000116431301262026700147730ustar00rootroot00000000000000# stockpile [![Clojars Project](https://img.shields.io/clojars/v/puppetlabs/stockpile.svg)](https://clojars.org/puppetlabs/stockpile) [![Build Status](https://travis-ci.org/puppetlabs/stockpile.svg?branch=master)](https://travis-ci.org/puppetlabs/stockpile) A simple, durable Clojure queueing library. While this is believed to be reasonably solid, it is still relatively new, and the API or behavior may change without warning. Stockpile supports the durable storage and retrieval of data. After storage, stockpile returns an `entry` that can be used to access the data later, and when no longer needed, the data can be atomically `discard`ed. Stockpile is explicitly designed to keep minimal state outside the filesystem. After opening a queue, you can call `reduce` to traverse the existing entries, but stockpile itself does not retain information about the entries. You must preserve any that you might want to access later. The ordering of any two entries can be compared (by `id`), but that ordering is not guaranteed to be exact, only some approximation of their relative insertion order. A metadata string can be provided for each item stored, but the length of that string may be limited by the underlying filesystem. (The string is currently encoded into the queue item's pathname so that it can be retrieved without having to open or read the file itself). The filesystem might also alter the metadata in other ways, for example if it does not preserve case. The path that's ultimately specified to the filesystem by the JVM may be affected by the locale, and on Linux with common filesystems, for example, often produces UTF-8 paths. See the queue `store` docstring for further information. Stockpile is intended to work correctly on any filesystem where rename (ATOMIC\_MOVE) works correctly, and where calling fsync/fdatasync on a file and its parent directory makes the file durable. At last look, [that did not include OS X](https://bugs.openjdk.java.net/browse/JDK-8080589). Unless the items being inserted into the queue are large enough for the sequential transfer rate to dominate, the insertion rate is likely to be limited by the maximum "fsync/fdatasync rate" of the underlying filesystem. The current implementation tracks the queue ids using an AtomicLong, and while that counter could overflow, even at 100,000 stores per second, it should require about 290 million years. Stockpile's behavior given unexpected files inside its directory is undefined. ## Usage See queue.clj and queue_test.clj for the API documentation and sample usage. ## Testing As expected, "lein test" will run the test suite, but there are some additional tests can only be run if `STOCKPILE_TINY_TEST_FS` is set to a directory that resides on an otherwise quiet filesystem with less than 10MB of free space, that is not the current filesystem: STOCKPILE_TINY_TEST_FS=~/tmp/tiny lein test During the tests stockpile may repeatedly fill that filesystem. You can also run the tests via `./run-test`, and if you're on Linux and root, it will automatically set up, use, and tear down a suitable tiny loopback filesystem. Alternately, if you have sudo access to root, you can invoke `./run-test --use-sudo` to do the same. Though invoking `./run-test` outside of a "throwaway" virtual machine is not recommended right now. ## Implementation notes The current implementation follows the the traditional POSIX-oriented approach of storing each entry in its own file, with a name that's guaranteed to be unique, and where durability is provided by this sequence of operations: - Write the entry data to a temp file, - fdatasync() the temp file, - rename() the temp file to the final name, - and fsync() the parent directory. Or rather, stockpile calls JVM functions that are believed to provide that behavior or an equivalent result. The parent directory fsync() is required in order to ensure that the destination file name is also durable. Given this approach, the "fsync rate" of the underlying filesystem will constrain the entry storage rate for a given queue, and so batching multiple items into a single entry (when feasible) may be an effective way to increase performance. ### An overview of relevant concepts: - http://blog.httrack.com/blog/2013/11/15/everything-you-always-wanted-to-know-about-fsync/ ### Related JVM methods and documentation: - https://docs.oracle.com/javase/7/docs/api/java/nio/channels/FileChannel.html#force(boolean) - https://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#move(java.nio.file.Path,%20java.nio.file.Path,%20java.nio.file.CopyOption...) ### Supporting POSIX functions: - http://pubs.opengroup.org/onlinepubs/9699919799/functions/fsync.html - http://pubs.opengroup.org/onlinepubs/9699919799/functions/fdatasync.html - http://pubs.opengroup.org/onlinepubs/9699919799/functions/rename.html ## License Copyright © 2016 Puppet Labs Inc Distributed under the Apache License Version 2.0. See ./LICENSE for details. stockpile-0.0.4/dev-resources/000077500000000000000000000000001301262026700162755ustar00rootroot00000000000000stockpile-0.0.4/dev-resources/Makefile.i18n000066400000000000000000000131321301262026700205130ustar00rootroot00000000000000# -*- Makefile -*- # This file was generated by the i18n leiningen plugin # Do not edit this file; it will be overwritten the next time you run # lein i18n init # # The locale in which our messages are written, and for which we therefore # have messages without any further effort MESSAGE_LOCALE=en # The name of the package into which the translations bundle will be placed BUNDLE=puppetlabs.stockpile # The list of names of packages covered by the translation bundle; # by default it contains a single package - the same where the translations # bundle itself is placed - but this can be overridden - preferably in # the top level Makefile PACKAGES?=$(BUNDLE) LOCALES=$(basename $(notdir $(wildcard locales/*.po))) BUNDLE_DIR=$(subst .,/,$(BUNDLE)) BUNDLE_FILES=$(patsubst %,resources/$(BUNDLE_DIR)/Messages_%.class,$(MESSAGE_LOCALE) $(LOCALES)) FIND_SOURCES=find src -name \*.clj # xgettext before 0.19 does not understand --add-location=file. Even CentOS # 7 ships with an older gettext. We will therefore generate full location # info on those systems, and only file names where xgettext supports it LOC_OPT=$(shell xgettext --add-location=file -f - /dev/null 2>&1 && echo --add-location=file || echo --add-location) LOCALES_CLJ=resources/locales.clj define LOCALES_CLJ_CONTENTS { :locales #{$(patsubst %,"%",$(MESSAGE_LOCALE) $(LOCALES))} :packages [$(patsubst %,"%",$(PACKAGES))] :bundle $(patsubst %,"%",$(BUNDLE).Messages) } endef export LOCALES_CLJ_CONTENTS i18n: update-pot msgfmt # Update locales/messages.pot update-pot: locales/messages.pot locales/messages.pot: $(shell $(FIND_SOURCES)) | locales @tmp=$$(mktemp $@.tmp.XXXX); \ $(FIND_SOURCES) \ | xgettext --from-code=UTF-8 --language=lisp \ --copyright-holder='Puppet ' \ --package-name="$(BUNDLE)" \ --package-version="$(BUNDLE_VERSION)" \ --msgid-bugs-address="docs@puppet.com" \ -k \ -kmark:1 -ki18n/mark:1 \ -ktrs:1 -ki18n/trs:1 \ -ktru:1 -ki18n/tru:1 \ -ktrun:1,2 -ki18n/trun:1,2 \ -ktrsn:1,2 -ki18n/trsn:1,2 \ $(LOC_OPT) \ --add-comments --sort-by-file \ -o $$tmp -f -; \ sed -i.bak -e 's/charset=CHARSET/charset=UTF-8/' $$tmp; \ sed -i.bak -e 's/POT-Creation-Date: [^\\]*/POT-Creation-Date: /' $$tmp; \ rm -f $$tmp.bak; \ if ! diff -q -I POT-Creation-Date $$tmp $@ >/dev/null 2>&1; then \ mv $$tmp $@; \ else \ rm $$tmp; touch $@; \ fi # Run msgfmt over all .po files to generate Java resource bundles # and create the locales.clj file msgfmt: $(BUNDLE_FILES) $(LOCALES_CLJ) # force rebuild of locales.clj if its contents is not the # the desired one ifneq ($(shell cat $(LOCALES_CLJ) 2> /dev/null),$(shell echo '$(subst ','\'',$(LOCALES_CLJ_CONTENTS))')) .PHONY: $(LOCALES_CLJ) endif $(LOCALES_CLJ): | resources @echo "Writing $@" @echo "$$LOCALES_CLJ_CONTENTS" > $@ resources/$(BUNDLE_DIR)/Messages_%.class: locales/%.po | resources msgfmt --java2 -d resources -r $(BUNDLE).Messages -l $(*F) $< resources/$(BUNDLE_DIR)/Messages_$(MESSAGE_LOCALE).class: locales/messages.pot | resources msgfmt --java2 -d resources -r $(BUNDLE).Messages -l $(MESSAGE_LOCALE) $< # Translators use this when they update translations; this copies any # changes in the pot file into their language-specific po file locales/%.po: locales/messages.pot @if [ -f $@ ]; then \ msgmerge -U $@ $< && touch $@; \ else \ touch $@ && msginit --no-translator -l $(*F) -o $@ -i $<; \ fi resources locales: @mkdir $@ help: $(info $(HELP)) @echo .PHONY: help define HELP This Makefile assists in handling i18n related tasks during development. Files that need to be checked into source control are put into the locales/ directory. They are locales/messages.pot - the POT file generated by 'make update-pot' locales/$$LANG.po - the translations for $$LANG Only the $$LANG.po files should be edited manually; this is usually done by translators. You can use the following targets: i18n: refresh all the files in locales/ and recompile resources update-pot: extract strings and update locales/messages.pot locales/LANG.po: refresh or create translations for LANG msgfmt: compile the translations into Java classes; this step is needed to make translations available to the Clojure code and produces Java class files in resources/ endef # @todo lutter 2015-04-20: for projects that use libraries with their own # translation, we need to combine all their translations into one big po # file and then run msgfmt over that so that we only have to deal with one # resource bundle stockpile-0.0.4/ext/000077500000000000000000000000001301262026700143075ustar00rootroot00000000000000stockpile-0.0.4/ext/test/000077500000000000000000000000001301262026700152665ustar00rootroot00000000000000stockpile-0.0.4/ext/test/manage-tinyfs000077500000000000000000000015001301262026700177520ustar00rootroot00000000000000#!/usr/bin/env bash set -euxo pipefail usage() { echo "Usage: $0 create PARENT_TMPDIR UID GID" echo " $0 destroy PARENT_TMPDIR" } create-tinyfs() { local tmpdir="$1" uid="$2" gid="$3" origdir origdir="$(pwd)" cd -P "$tmpdir" dd if=/dev/zero of=tinyfs.img bs=10MB count=1 chmod 600 tinyfs.img mke2fs -F tinyfs.img mkdir tinyfs mount -oloop tinyfs.img tinyfs chown "$uid:$gid" tinyfs cd "$origdir" } destroy-tinyfs() { local tmpdir="$1" umount -l -d "$tmpdir"/tinyfs rm -f "$tmpdir"/tinyfs.img } set -x case "$1" in create) shift if [ "$#" -ne 3 ]; then usage 1>&2 exit 1 fi create-tinyfs "$@" ;; destroy) shift if [ "$#" -ne 1 ]; then usage 1>&2 exit 1 fi destroy-tinyfs "$1" ;; *) usage 1>&2 exit 1 esac stockpile-0.0.4/locales/000077500000000000000000000000001301262026700151315ustar00rootroot00000000000000stockpile-0.0.4/locales/messages.pot000066400000000000000000000021711301262026700174650ustar00rootroot00000000000000# SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR Puppet # This file is distributed under the same license as the puppetlabs.stockpile package. # FIRST AUTHOR , YEAR. # #, fuzzy msgid "" msgstr "" "Project-Id-Version: puppetlabs.stockpile \n" "Report-Msgid-Bugs-To: docs@puppet.com\n" "POT-Creation-Date: \n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" "Language: \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" #: src/puppetlabs/stockpile/queue.clj msgid "id is not an integer: {0}" msgstr "" #: src/puppetlabs/stockpile/queue.clj msgid "metadata is not a string: {0}" msgstr "" #: src/puppetlabs/stockpile/queue.clj msgid "Invalid queue token {0} found in {1}" msgstr "" #: src/puppetlabs/stockpile/queue.clj msgid "unable to delete temp file {0} after error" msgstr "" #: src/puppetlabs/stockpile/queue.clj msgid "unable to commit; leaving stream data in {0}" msgstr "" #: src/puppetlabs/stockpile/queue.clj msgid "No file found for entry {0} at {1}" msgstr "" stockpile-0.0.4/project.clj000066400000000000000000000013571301262026700156550ustar00rootroot00000000000000(defproject puppetlabs/stockpile "0.0.4" :description "Simple, durable Clojure queuing library" :url "https://github.com/puppetlabs/stockpile" :license {:name "Apache License Version 2.0" :url "http://www.apache.org/licenses/LICENSE-2.0"} :dependencies [[puppetlabs/i18n "0.4.3"] [org.clojure/clojure "1.8.0"]] :plugins [[puppetlabs/i18n "0.4.3"]] :profiles {:dev {:dependencies [[org.apache.commons/commons-lang3 "3.4"]]}} :deploy-repositories [["releases" {:url "https://clojars.org/repo" :username :env/clojars_jenkins_username :password :env/clojars_jenkins_password :sign-releases false}]]) stockpile-0.0.4/run-test000077500000000000000000000026431301262026700152230ustar00rootroot00000000000000#!/bin/bash set -euxo pipefail # Make sure we're in the right place test -x ext/test/manage-tinyfs test -f src/puppetlabs/stockpile/queue.clj manage_tinyfs="$(pwd)/ext/test/manage-tinyfs" usage() { echo "Usage: $0 [--use-sudo|--no-sudo] [-- LEIN_TEST_ARGS]" } tmpdir='' destroy_tinyfs='' clean-up() { if test "$destroy_tinyfs"; then as-root "$manage_tinyfs" destroy "$tmpdir" fi if test "$tmpdir"; then rm -rf "$tmpdir" fi } use_sudo='' while test "$#" -ne 0; do case "$1" in --use-sudo) shift use_sudo=true ;; --no-sudo) shift use_sudo='' ;; --) shift break ;; *) usage 1>&2 exit 1 ;; esac done test_tinyfs='' if test "$(uname -s)" != Linux; then echo "Not on Linux; skipping root tests" 1>&2 else if test "$use_sudo"; then as-root() { sudo -i "$@" } test_tinyfs=true elif test "$(id -u)" = 0; then as-root() { "$@" } test_tinyfs=true else echo "Not root, and --use-sudo not specified; skipping root tests" 1>&2 fi fi trap clean-up EXIT if [ "$test_tinyfs" ]; then tmpdir="$(mktemp -d "$(pwd)/target/run-test-XXXXXXX")" destroy_tinyfs=true as-root "$manage_tinyfs" create "$tmpdir" "$(id -u)" "$(id -g)" export STOCKPILE_TINY_TEST_FS="$tmpdir/tinyfs" fi java -version # Don't exec or the trap won't fire lein test "$@" stockpile-0.0.4/src/000077500000000000000000000000001301262026700142765ustar00rootroot00000000000000stockpile-0.0.4/src/puppetlabs/000077500000000000000000000000001301262026700164555ustar00rootroot00000000000000stockpile-0.0.4/src/puppetlabs/stockpile/000077500000000000000000000000001301262026700204525ustar00rootroot00000000000000stockpile-0.0.4/src/puppetlabs/stockpile/queue.clj000066400000000000000000000334261301262026700223000ustar00rootroot00000000000000(ns puppetlabs.stockpile.queue (:refer-clojure :exclude [reduce]) (:require [puppetlabs.i18n.core :refer [trs]]) (:import [clojure.lang BigInt] [java.io ByteArrayInputStream File FileOutputStream InputStream] [java.nio.file AtomicMoveNotSupportedException DirectoryStream FileSystemException NoSuchFileException Path Paths] [java.nio.channels FileChannel] [java.nio.file FileAlreadyExistsException Files OpenOption StandardCopyOption] [java.nio.file.attribute FileAttribute] [java.util.concurrent.atomic AtomicLong])) ;; Queue structure: ;; - qdir/stockpile ;; - qdir/q/INTEGER # message ;; - qdir/q/INTEGER-ENCODED_METADATA # message ;; - qdir/q/tmp-BLARG # pending message (defn- basename [^Path path] (.getName path (dec (.getNameCount path)))) (defn ^Path path-get [^String s & more-strings] (Paths/get s (into-array String more-strings))) (defn- parse-integer [x] (try (Long/parseLong x) (catch NumberFormatException ex nil))) (defprotocol AsPath (as-path ^Path [x])) (extend-protocol AsPath Path (as-path [x] x) String (as-path [x] (path-get x)) File (as-path [x] (.toPath x))) (defprotocol Entry (entry-id [entry]) (entry-meta [entry])) (defrecord MetaEntry [id metadata] Entry (entry-id [this] id) (entry-meta [this] metadata)) (extend-protocol Entry Long (entry-id [this] this) (entry-meta [this] nil)) (defn- create-tmp-file [parent] ;; Don't change the prefix/suffix here casually. Other ;; code below assumes, for example, that a temporary file will never ;; be named "stockpile". (Files/createTempFile (as-path parent) "tmp-" "" (into-array FileAttribute []))) (defn fsync [x metadata?] (with-open [fc (FileChannel/open (as-path x) (into-array OpenOption []))] (.force fc metadata?))) (def ^:private copt-atomic StandardCopyOption/ATOMIC_MOVE) (def ^:private copt-replace StandardCopyOption/REPLACE_EXISTING) (def ^:private copts-type (class (into-array StandardCopyOption []))) (defn ^copts-type copts [opts] (into-array StandardCopyOption opts)) (defn- atomic-move [src dest] (Files/move (as-path src) (as-path dest) (copts [copt-atomic]))) (defn- rename-durably "If possible, atomically renames src to dest (each of which may be a File, Path, or String). If dest already exists, on some platforms the replacement will succeed, and on others it will throw an IOException. The rename may also fail with AtomicMoveNotSupportedException (perhaps if src and dest are on different filesystems). See java.nio.file.Files/move for additional information. fsyncs the dest parent directory to make the final rename durable unless sync-parent? is false (presumably the caller will ensure the sync)." [src dest sync-parent?] (atomic-move src dest) (when sync-parent? (fsync (.getParent (as-path dest)) true))) (defn- delete-if-exists [path] ;; Solely exists for error handling tests (Files/deleteIfExists path)) (defn- write-stream [^InputStream stream ^Path dest] ;; Solely exists for error handling tests (Files/copy stream dest (copts [copt-replace]))) (defn- qpath ^Path [{:keys [^Path directory] :as q}] (.resolve directory "q")) (defn- queue-entry-path [q id metadata] (let [^Path parent (qpath q) ^String entry-name (apply str id (when metadata ["-" metadata]))] (.resolve parent entry-name))) (defn- entry-path [q entry] (queue-entry-path q (entry-id entry) (entry-meta entry))) (defn- filename->entry "Returns an entry if name can be parsed as such, i.e. either as an integer or integer-metadata, nil otherwise." [^String name] (let [dash (.indexOf name (int \-))] (if (= -1 dash) (parse-integer name) ;; Perhaps it has metadata (when-let [id (parse-integer (subs name 0 dash))] (->MetaEntry id (subs name (inc dash))))))) (defrecord Stockpile [directory next-likely-id]) (defn- reduce-paths [f val ^DirectoryStream dirstream] (with-open [_ dirstream] (clojure.core/reduce f val (-> dirstream .iterator iterator-seq)))) (defn- plausible-prefix? [s] (-> #"^[0-9](?:-.)?+" (.matcher s) .find)) ;;; Stable, public interface (defn entry [id metadata] (let [id (if (integer? id) (long id) (throw (IllegalArgumentException. (trs "id is not an integer: {0}" id))))] (cond (nil? metadata) id (not (string? metadata)) (throw (IllegalArgumentException. (trs "metadata is not a string: {0}" (pr-str metadata)))) :else (->MetaEntry id metadata)))) (defn next-likely-id "Returns a likely id for the next message stored in the q. No subsequent entry ids will be less than this value." [{^AtomicLong next :next-likely-id :as q}] (.get next)) (defn create "Creates a new queue in directory, which must not exist, and returns the queue. If an exception is thrown, the directory named may or may not exist and may or may not be empty." [directory] (let [top (as-path directory) q (.resolve top "q")] (Files/createDirectory top (into-array FileAttribute [])) (Files/createDirectory q (into-array FileAttribute [])) ;; This sentinel is last - indicates the queue is *ready* (let [tmp (create-tmp-file top)] (with-open [out (FileOutputStream. (.toFile tmp))] (.write out (.getBytes "0 stockpile" "UTF-8"))) (fsync tmp false) (rename-durably tmp (.resolve top "stockpile") false)) (fsync top true) (->Stockpile top (AtomicLong. 0)))) (defn open "Opens the queue in directory, and returns it. Expects only stockpile created files in the directory, and currently deletes any existing file in the queue whose name starts with \"tmp-\"." [directory] (let [top (as-path directory) q (.resolve top "q")] (let [info-file (.resolve top "stockpile") info (String. (Files/readAllBytes info-file) "UTF-8")] (when-not (= "0 stockpile" info) (throw (IllegalStateException. (trs "Invalid queue token {0} found in {1}" (pr-str info) (pr-str (str info-file))))))) (let [max-id (reduce-paths (fn [result ^Path p] (let [name (str (basename p))] (cond (.startsWith name "tmp-") (do (Files/deleteIfExists p) result) (plausible-prefix? name) (max result (-> name filename->entry entry-id)) :else result))) 0 (Files/newDirectoryStream q))] (->Stockpile top (AtomicLong. (inc max-id)))))) (defn reduce "Calls (f reduction entry) for each existing entry as-per reduce, with val as the initial reduction, and returns the result. The ordering of the calls is unspecified, as is the effect of concurrent discards. The reduction may be escaped by throwing a unique exception (cf. slingshot). For example: (reduce \"foo\" conj [])." [q f val] (reduce-paths (fn [result ^Path p] (let [name (-> p basename str)] (if-not (plausible-prefix? name) result (f result (filename->entry name))))) val (Files/newDirectoryStream (qpath q)))) (defn store "Atomically and durably enqueues the content of stream, and returns an entry that can be used to refer to the content later. An ex-info exception of {:kind ::unable-to-commit :stream-data path} may be thrown if store was able to read the data from the stream, but unable to make it durable. If any other exception is thrown, the state of the stream is unknown. The :stream-data value will be a path to a file containing all of the data that was in the stream. Among other things, it's possible that ::unable-to-commit indicates the metadata was incompatible with the underlying filesystem (it was too long, couldn't be encoded, etc.). That's because the current implementation records the metadata in a file name corresponding to the entry, and may use up to 20 (Unicode Basic Latin block) characters of that file name for internal purposes. The remainder of the filename is available for the metadata, but the maximum length of that remainder depends on the platform and target filesystem. Many common filesystems now allow a file name to be up to 255 characters or bytes, and at least on Linux, the JVM converts the Unicode string path to a filesystem path using an encoding that depends on the locale, often choosing UTF-8. So assuming a UTF-8 encoding and a 255 byte maximum path length (e.g. ext4), after subtracting the 20 (UTF-8 encoded Basic Latin block) bytes reserved for internal use, there may be up to 235 bytes available for the metadata. Of course how many Unicode characters that will allow depends on their size when converted to UTF-8. Whenever there's an error, it's possible that the attempt to clean up may fail and leave behind a temporary file. In that case create throws an ex-info exception of {:kind ::path-cleanup-failure-after-error :path p :exception ex} with the exception produced by the original failure as the cause. To handle that possibility, callers may want to structure invocations with a nested try like this: (try (try+ (stock/create ...) (catch [:kind ::path-cleanup-failure-after-error] {:keys [path exception]} ;; Perhaps log or try to clean up the path more aggressively (throw (:cause &throw-context))) (catch SomeExceptionThatCausedCreateToFail ;; Reached for this exception whether or not there was a ;; cleanup failure ...) ...) Additionally, among other exceptions, the current implementation may throw any documented by java.nio.file.Files/move for an ATOMIC_MOVE within the same directory." ([q stream] (store q stream nil)) ([q ^ByteArrayInputStream stream metadata] (let [^AtomicLong next (:next-likely-id q) qd (qpath q)] (let [^Path tmp-dest (create-tmp-file qd)] ;; It might be possible to optimize some cases with ;; transferFrom/transferTo eventually. (try (write-stream stream tmp-dest) (catch Exception ex (try (delete-if-exists tmp-dest) (catch Exception del-ex (throw (ex-info (trs "unable to delete temp file {0} after error" (pr-str (str tmp-dest))) {:kind ::path-cleanup-failure-after-error :path tmp-dest :exception del-ex} ex)))) (throw ex))) (try (fsync tmp-dest false) (loop [] (let [id (.getAndIncrement next) target (queue-entry-path q id metadata) ;; Can't recur from catch moved? (try (rename-durably tmp-dest target true) true (catch FileAlreadyExistsException ex false))] (if moved? (entry id metadata) (recur)))) (catch Exception ex (throw (ex-info (trs "unable to commit; leaving stream data in {0}" (pr-str (str tmp-dest))) {:kind ::unable-to-commit :stream-data tmp-dest} ex)))))))) (defn stream "Returns an unbuffered stream of the entry's data. Throws an ex-info exception of {:kind ::no-such-entry :entry e :source s} if the requested entry does not exist. Currently the :source will always be a Path." [q entry] (let [path (entry-path q entry)] (try (Files/newInputStream path (make-array OpenOption 0)) (catch NoSuchFileException ex (let [m (entry-meta entry) id (entry-id entry)] (throw (ex-info (trs "No file found for entry {0} at {1}" (if-not m id (pr-str [id m])) (pr-str (str path))) {:kind ::no-such-entry :entry entry :source path} ex))))))) (defn discard "Atomically and durably discards the entry (returned by store) from the queue. The discarded data will be placed at the destination path (durably if possible), when one is provided. This should be much more efficient, and likely safer if the destination is at least on the same filesystem as the queue. The results of calling this more than once for a given entry are undefined." ;; Not entirely certain the queue parent dir syncs are necessary *if* ;; everyone guarantees that you either see the file or not, and if ;; we're OK with the possibility of spurious redelivery. ([q entry] (Files/deleteIfExists (entry-path q entry)) (fsync (qpath q) true)) ([q entry destination] (let [^Path src (entry-path q entry) ^Path destination (as-path destination) moved? (try (Files/move src destination (copts [copt-atomic])) true (catch UnsupportedOperationException ex false) (catch AtomicMoveNotSupportedException ex false))] (when-not moved? (Files/copy src destination (copts [copt-replace])) (Files/delete src)) (fsync (.getParent destination) true) (fsync (qpath q) true)))) stockpile-0.0.4/test/000077500000000000000000000000001301262026700144665ustar00rootroot00000000000000stockpile-0.0.4/test/puppetlabs/000077500000000000000000000000001301262026700166455ustar00rootroot00000000000000stockpile-0.0.4/test/puppetlabs/stockpile/000077500000000000000000000000001301262026700206425ustar00rootroot00000000000000stockpile-0.0.4/test/puppetlabs/stockpile/queue_test.clj000066400000000000000000000441121301262026700235210ustar00rootroot00000000000000(ns puppetlabs.stockpile.queue-test (:require [puppetlabs.stockpile.queue :as stock] [clojure.java.io :as io] [clojure.java.shell :as shell] [clojure.test :refer :all]) (:import [org.apache.commons.lang3 RandomStringUtils] [java.io ByteArrayInputStream File IOException] [java.nio.file Files NoSuchFileException OpenOption Path StandardOpenOption] [java.nio.file.attribute FileAttribute] [puppetlabs.stockpile.queue MetaEntry])) (defn relativize-file [wrt-path f] (.relativize wrt-path (.toPath f))) (defn relative-pathstr-seq [parent] (map #(str (relativize-file parent %)) (file-seq (.toFile parent)))) (def small-test-fs (if-let [v (System/getenv "STOCKPILE_TINY_TEST_FS")] (stock/path-get v) (binding [*out* *err*] (println "STOCKPILE_TINY_TEST_FS not defined; skipping related tests") false))) (defn random-path-segment [n] (loop [s (RandomStringUtils/random n)] (if (and (= -1 (.indexOf s java.io.File/separator)) (= -1 (.indexOf s (int \u0000)))) s (recur (RandomStringUtils/random n))))) (defn rm-r [pathstr] ;; Life's too short... (let [rm (shell/sh "rm" "-r" pathstr)] (when-not (zero? (:exit rm)) (throw (-> "'rm -r %s' failed: %s" (format (pr-str pathstr) (pr-str rm)) Exception.))))) (defn call-with-temp-dir-path [f] (let [tempdir (Files/createTempDirectory (.toPath (File. "target")) "stockpile-test-" (into-array FileAttribute [])) tempdirstr (str (.toAbsolutePath tempdir)) result (try (f (.toAbsolutePath tempdir)) (catch Exception ex (binding [*out* *err*] (println "Error: leaving temp dir" tempdirstr)) (throw ex)))] (rm-r tempdirstr) result)) (defn entry-path [q entry] (#'stock/queue-entry-path q (stock/entry-id entry) (stock/entry-meta entry))) (defn slurp-entry [q entry] (slurp (stock/stream q entry))) (defn store-str ([q s] (let [ent (stock/store q (-> s (.getBytes "UTF-8") ByteArrayInputStream.)) id (stock/entry-id ent)] (is (integer? ent)) (is (integer? id)) (is (not (stock/entry-meta ent))) ent)) ([q s metadata] (let [ent (stock/store q (-> s (.getBytes "UTF-8") ByteArrayInputStream.) metadata) id (stock/entry-id ent) meta (stock/entry-meta ent)] (is (integer? id)) (if metadata (do (is (instance? MetaEntry ent)) (is (= metadata (stock/entry-meta ent)))) (is (not (stock/entry-meta ent)))) ent))) (defn purge-queue [qdir] (let [q (stock/open qdir) entries (stock/reduce q conj ())] (doseq [entry entries] (stock/discard entry)))) (deftest bad-entries (is (thrown? IllegalArgumentException (stock/entry "foo"))) (is (thrown? IllegalArgumentException (stock/entry "foo" 1))) (is (thrown? IllegalArgumentException (stock/entry 1 2)))) (deftest entry-ids (call-with-temp-dir-path (fn [tmpdir] ;; Expectations specific to the current implementation (let [q (stock/create (.toFile (.resolve tmpdir "queue")))] (is (zero? (stock/next-likely-id q))) (let [e (store-str q "first")] (is (zero? (stock/entry-id e))) (is (= 1 (stock/next-likely-id q))) (let [e (store-str q "second")] (is (= 1 (stock/entry-id e))) (is (= 2 (stock/next-likely-id q))))))))) (deftest basics (call-with-temp-dir-path (fn [tmpdir] (let [q (stock/create (.toFile (.resolve tmpdir "queue")))] (let [entry-1 (store-str q "foo") entry-2 (store-str q "bar" "*so* meta") id-1 (stock/entry-id entry-1) id-2 (stock/entry-id entry-2)] (is (< id-1 id-2)) (is (> id-2 id-1)) (is (= "foo" (slurp-entry q entry-1))) (is (= "bar" (slurp-entry q entry-2))) (stock/discard q entry-1) (is (= "bar" (slurp-entry q entry-2))) (try (slurp-entry q entry-1) (catch Exception ex (= {:entry entry-1 :source (entry-path q entry-1)} (ex-data ex)))))) (is (= #{"" "queue" "queue/q" "queue/q/1-*so* meta" "queue/stockpile"} (set (relative-pathstr-seq tmpdir))))))) (deftest basic-persistence ;; Some of the validation is handled implicitly by store-str (call-with-temp-dir-path (fn [tmpdir] (let [qdir (.toFile (.resolve tmpdir "queue")) reduction-0 (stock/reduce (stock/create qdir) #(throw (Exception. "unexpected")) :empty) ent-1 (-> (stock/open qdir) (store-str "foo")) ent-1-id (stock/entry-id ent-1) reduction-1 (stock/reduce (stock/open qdir) conj #{})] (is (= :empty reduction-0)) ;; Check first reduction (should be one element) (is (= #{ent-1} reduction-1)) (is (= #{(stock/entry ent-1-id nil)} reduction-1)) (let [ent (first reduction-1)] (is (= ent-1-id (stock/entry-id ent))) (is (not (stock/entry-meta ent)))) (is (= "foo" (slurp-entry (stock/open qdir) ent-1))) (let [ent-2 (-> (stock/open qdir) (store-str "bar" "meta bar")) ent-2-id (stock/entry-id ent-2) reduction-2 (stock/reduce (stock/open qdir) conj #{})] ;; Check second reduction (should be two elements) (is (= #{ent-1 ent-2} reduction-2)) (is (= #{(stock/entry ent-1-id nil) (stock/entry ent-2-id "meta bar")} reduction-2)) (let [ent (get reduction-2 ent-2)] (is (= ent-2-id (stock/entry-id ent))) (is (= "meta bar" (stock/entry-meta ent)))) (let [q (stock/open qdir)] (is (= "foo" (slurp-entry q ent-1))) (is (= "bar" (slurp-entry q ent-2)))))) (is (= #{"" "queue" "queue/q" "queue/q/1" "queue/q/2-meta bar" "queue/stockpile"} (set (relative-pathstr-seq tmpdir))))))) (deftest entry-manipulation (call-with-temp-dir-path (fn [tmpdir] (let [qdir (.toFile (.resolve tmpdir "queue")) q (stock/create qdir) inputs (for [i (range 10)] [(str i) (str "meta-" i)]) entries (for [[data metadata] inputs] (store-str q data metadata))] (doall (map (fn [input entry] (let [id (stock/entry-id entry) metadata (stock/entry-meta entry) reconstituted (stock/entry id metadata)] (is (= entry reconstituted)) (is (= (first input) (slurp-entry q reconstituted))))) inputs entries)))))) (deftest cleanup-failure-after-store-failure (call-with-temp-dir-path (fn [tmpdir] (let [qdir (.toFile (.resolve tmpdir "queue")) delete-failed (Exception. "delete") write-failed (Exception. "write") q (stock/create qdir) ex (try (with-redefs [stock/delete-if-exists (fn [& args] (throw delete-failed)) stock/write-stream (fn [& args] (throw write-failed))] (store-str q "first")) (catch Exception ex ex)) data (ex-data ex)] (is (= ::stock/path-cleanup-failure-after-error (:kind data))) (is (= delete-failed (:exception data))) (is (instance? Path (:path data))) (is (.exists (.toFile (:path data)))) (is (= write-failed (.getCause ex))))))) (deftest streaming-missing-entry (call-with-temp-dir-path (fn [tmpdir] (let [qdir (.toFile (.resolve tmpdir "queue")) delete-failed (Exception. "delete") write-failed (Exception. "write") q (stock/create qdir) entry (stock/entry 0 nil) ex (try (stock/stream q entry) (catch Exception ex ex)) data (ex-data ex)] (is (= ::stock/no-such-entry (:kind data))) (is (= entry (:entry data))) (is (= (entry-path q entry) (:source data))) (is (not (.exists (.toFile (:source data))))) (is (instance? NoSuchFileException (.getCause ex))))))) (deftest commit-failure-during-store (call-with-temp-dir-path (fn [tmpdir] (let [qdir (.toFile (.resolve tmpdir "queue")) rename-failed (Exception. "rename") q (stock/create qdir) ex (try (with-redefs [stock/rename-durably (fn [& args] (throw rename-failed))] (store-str q "first")) (catch Exception ex ex)) data (ex-data ex)] (is (= ::stock/unable-to-commit (:kind data))) (is (instance? Path (:stream-data data))) (is (= "first" (slurp (.toFile (:stream-data data))))) (is (= rename-failed (.getCause ex))))))) (deftest meta-encoding-round-trip (call-with-temp-dir-path (fn [tmpdir] (let [qdir (.toFile (.resolve tmpdir "queue")) q (stock/create qdir) batch-size 100] (dotimes [i batch-size] ;; We need to use a very short length here to avoid falling ;; afoul of path length limits since 8 random unicode ;; chars could expand to say 36 encoded bytes. (let [metadata (random-path-segment (rand-int 8))] (store-str q metadata metadata))))))) (deftest existing-tmp-removal (call-with-temp-dir-path (fn [tmpdir] (let [qdir (.toFile (.resolve tmpdir "queue")) garbage (File. qdir "q/tmp-garbage")] (stock/create qdir) (io/copy "foo" (File. qdir "q/tmp-garbage")) (let [q (stock/open qdir) entries (stock/reduce q conj ())] (is (= [] entries)) (is (not (.exists garbage)))))))) (defn test-discard-entry-to [destination tmpdir q-name] (let [qdir (.resolve tmpdir q-name) newq (stock/create qdir)] (let [entry (store-str newq "foo") q (stock/open qdir) read-entries (stock/reduce q conj ())] (is (= [entry] read-entries)) (stock/discard q entry destination) (is (= "foo" (String. (Files/readAllBytes destination) "UTF-8")))))) (deftest discard-to-destination (call-with-temp-dir-path (fn [tmpdir] (test-discard-entry-to (.resolve tmpdir "discarded") tmpdir "q1") (when small-test-fs (let [dest (Files/createTempFile small-test-fs "discarded-" "" (into-array FileAttribute []))] (try (test-discard-entry-to dest tmpdir "q2") (finally (Files/delete dest)))))))) (defn fill-filesystem [path] "Returns truish value if the filesystem containing path is likely full." (let [append StandardOpenOption/APPEND buf (byte-array (* 64 1024) (byte \?)) write-chunks (fn [write-chunk open-opts] (with-open [out (Files/newOutputStream path (into-array OpenOption open-opts))] (try (while true (write-chunk out)) (catch IOException ex true))))] ;; Write smaller and smaller chunks; finish up with single bytes. (write-chunks #(.write % buf 0 (* 64 1024)) []) (write-chunks #(.write % buf 0 1024) [append]) (write-chunks #(.write % (int \?)) [append]))) (deftest full-filesystem-behavior (when small-test-fs (let [qdir (.resolve small-test-fs "full-q") nopedir (.resolve small-test-fs "no-q") q (stock/create qdir) balloon (Files/createTempFile small-test-fs "balloon-" "" (into-array FileAttribute []))] (try (let [firehose (future (fill-filesystem balloon)) result (deref firehose (* 30 1000) nil)] (is result) (if-not result (future-cancel firehose) (let [free (.getUsableSpace (Files/getFileStore balloon))] (is (= 0 free)) (when (zero? free) (is (thrown? IOException (stock/create nopedir))) (is (thrown? IOException (store-str q "foo"))))))) (finally (Files/delete balloon))) (let [q (stock/open qdir) read-entries (stock/reduce q conj ())] (is (= [] read-entries)))))) (def billion 1000000000) (deftest uncontended-performance ;; This also tests random metadata round trips (call-with-temp-dir-path (fn [tmpdir] (let [qdir (.toFile (.resolve tmpdir "queue"))] (doall (for [make-meta [nil #(random-path-segment 4)] batch-size [100 1000] i (range 3)] (do (let [q (stock/create qdir) ;; Uncontended enqueue start (System/nanoTime) items (doall (for [i (range batch-size)] (let [m (and make-meta (make-meta)) ent (store-str q (str i) m)] (when m (is (= m (stock/entry-meta ent)))) [m ent]))) stop (System/nanoTime) _ (binding [*out* *err*] (printf "Enqueued %d tiny messages %s metadata at %.2f/s\n" batch-size (if make-meta "with" "without") (double (/ batch-size (/ (- stop start) billion)))) (flush)) ;; Uncontended streams start (System/nanoTime) _ (is (= (set (map str (range batch-size))) (set (for [[metadata entry] items] (slurp-entry q entry))))) stop (System/nanoTime) _ (binding [*out* *err*] (printf "Streamed %d tiny messages %s metadata at %.2f/s\n" batch-size (if make-meta "with" "without") (double (/ batch-size (/ (- stop start) billion)))) (flush)) ;; Uncontended discard start (System/nanoTime) _ (doseq [[metadata entry] items] (stock/discard q entry)) stop (System/nanoTime) _ (binding [*out* *err*] (printf "Discarded %d tiny messages %s metadata at %.2f/s\n" batch-size (if make-meta "with" "without") (double (/ batch-size (/ (- stop start) billion)))) (flush))] (is (= #{"" "q" "stockpile"} (set (relative-pathstr-seq (.toPath qdir)))))) (rm-r (.getAbsolutePath qdir))))))))) (deftest contending-enqueue-dequeue-performance (call-with-temp-dir-path (fn [tmpdir] (let [qdir (.toFile (.resolve tmpdir "queue")) q (stock/create qdir) batch-size 2000 start (System/nanoTime) entries (seque (int (max 100 (/ batch-size 10))) (for [i (range batch-size)] (store-str q (str i))))] (doall (map (fn [i entry] (is (= (str i) (slurp-entry q entry))) (stock/discard q entry) (try (slurp-entry q entry) (catch Exception ex (= {:entry entry :source (entry-path q entry)} (ex-data ex))))) (range batch-size) entries)) (binding [*out* *err*] (printf "Enqueued and dequeued %d tiny messages in parallel at %.2f/s\n" batch-size (double (/ batch-size (/ (- (System/nanoTime) start) billion)))) (flush)) (is (= #{"" "q" "stockpile"} (set (relative-pathstr-seq (.toPath qdir))))))))) (deftest simple-race (call-with-temp-dir-path (fn [tmpdir] (let [batch-size 300 qdir (.toFile (.resolve tmpdir "queue")) q (stock/create qdir) state (atom {:entries () :victim nil}) finished? (atom false) writer (future (dotimes [i batch-size] (swap! state update :entries conj [i (store-str q (str i) (str "meta-" i))]))) reader (future (while (not @finished?) (let [{:keys [victim]} (swap! state (fn [{[v & r] :entries}] {:entries r :victim v})) [val entry] victim] (when victim (is (= (str val) (slurp-entry q entry))) (swap! state update :entries conj victim))))) discarder (future (loop [i 0] (when (< i batch-size) (let [{:keys [victim]} (swap! state (fn [{[v & r] :entries}] {:entries r :victim v})) [val entry] victim] (if entry (do (stock/discard q entry) (recur (inc i))) (recur i))))))] @writer @discarder (reset! finished? true) @reader (is (= #{"" "q" "stockpile"} (set (relative-pathstr-seq (.toPath qdir)))))))))