repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
poise/poise-python | https://github.com/poise/poise-python/blob/eeb0fc0ee50e8baef15ab4f91601994e5b40a272/lib/poise_python/python_providers/portable_pypy3.rb | lib/poise_python/python_providers/portable_pypy3.rb | #
# Copyright 2015-2017, Noah Kantrowitz
#
# 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.
#
require 'poise_languages/static'
require 'poise_python/error'
require 'poise_python/python_providers/base'
module PoisePython
module PythonProviders
class PortablePyPy3 < Base
provides(:portable_pypy3)
include PoiseLanguages::Static(
name: 'pypy3',
# Don't put prereleases first so they aren't used for prefix matches on ''.
versions: %w{2.4 5.7.1-beta 5.7-beta 5.5-alpha-20161014 5.5-alpha-20161013 5.2-alpha-20160602 2.3.1},
machines: %w{linux-i686 linux-x86_64},
url: 'https://bitbucket.org/squeaky/portable-pypy/downloads/pypy3-%{version}-%{kernel}_%{machine}-portable.tar.bz2'
)
def self.default_inversion_options(node, resource)
super.tap do |options|
if resource.version && resource.version =~ /^(pypy3-)?5(\.\d)?/
# We need a different default base URL for pypy3.3
# This is the same as before but `/pypy3.3` as the prefix on the filename.
basename = if $2 == '.2' || $2 == '.5'
'pypy3.3'
else
'pypy3.5'
end
options['url'] = "https://bitbucket.org/squeaky/portable-pypy/downloads/#{basename}-%{version}-%{kernel}_%{machine}-portable.tar.bz2"
end
end
end
def python_binary
::File.join(static_folder, 'bin', 'pypy')
end
private
def install_python
install_static
end
def uninstall_python
uninstall_static
end
end
end
end
| ruby | Apache-2.0 | eeb0fc0ee50e8baef15ab4f91601994e5b40a272 | 2026-01-04T17:52:09.242542Z | false |
poise/poise-python | https://github.com/poise/poise-python/blob/eeb0fc0ee50e8baef15ab4f91601994e5b40a272/lib/poise_python/python_providers/msi.rb | lib/poise_python/python_providers/msi.rb | #
# Copyright 2016-2017, Noah Kantrowitz
#
# 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.
#
require 'chef/resource'
require 'poise_python/error'
require 'poise_python/python_providers/base'
module PoisePython
module PythonProviders
class Msi < Base
provides(:msi)
MSI_VERSIONS = %w{3.4.4 3.3.5 3.2.5 3.1.4 3.0.1 2.7.10 2.6.5 2.5.4}
def self.provides_auto?(node, resource)
# Only enable by default on Windows and not for Python 3.5 because that
# uses the win_binaries provider.
node.platform_family?('windows') #&& resource.version != '3' && ::Gem::Requirement.create('< 3.5').satisfied_by(::Gem::Version.create(new_resource.version))
end
def python_binary
return options['python_binary'] if options['python_binary']
if package_version =~ /^(\d+)\.(\d+)\./
::File.join(ENV['SystemDrive'], "Python#{$1}#{$2}", 'python.exe')
else
raise "Can't find Python binary for #{package_version}"
end
end
private
def install_python
version = package_version
windows_package 'python' do
source "https://www.python.org/ftp/python/#{version}/python-#{version}#{node['machine'] == 'x86_64' ? '.amd64' : ''}.msi"
end
end
def uninstall_python
raise NotImplementedError
end
def package_version
MSI_VERSIONS.find {|ver| ver.start_with?(new_resource.version) } || new_resource.version
end
end
end
end
| ruby | Apache-2.0 | eeb0fc0ee50e8baef15ab4f91601994e5b40a272 | 2026-01-04T17:52:09.242542Z | false |
poise/poise-python | https://github.com/poise/poise-python/blob/eeb0fc0ee50e8baef15ab4f91601994e5b40a272/lib/poise_python/utils/python_encoder.rb | lib/poise_python/utils/python_encoder.rb | #
# Copyright 2015-2017, Noah Kantrowitz
#
# 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.
#
require 'json'
module PoisePython
module Utils
# Convert Ruby data structures to a Python literal. Overall similar to JSON
# but just different enough that I need to write this. Thanks Obama.
#
# @since 1.0.0
# @api private
class PythonEncoder
def initialize(root, depth_limit: 100)
@root = root
@depth_limit = depth_limit
end
def encode
encode_obj(@root, 0)
end
private
def encode_obj(obj, depth)
raise ArgumentError.new("Depth limit exceeded") if depth > @depth_limit
case obj
when Hash
encode_hash(obj, depth)
when Array
encode_array(obj, depth)
when true
'True'
when false
'False'
when nil
'None'
else
obj.to_json
end
end
def encode_hash(obj, depth)
middle = obj.map do |key, value|
"#{encode_obj(key, depth+1)}:#{encode_obj(value, depth+1)}"
end
"{#{middle.join(',')}}"
end
def encode_array(obj, depth)
middle = obj.map do |value|
encode_obj(value, depth+1)
end
"[#{middle.join(',')}]"
end
end
end
end
| ruby | Apache-2.0 | eeb0fc0ee50e8baef15ab4f91601994e5b40a272 | 2026-01-04T17:52:09.242542Z | false |
poise/poise-python | https://github.com/poise/poise-python/blob/eeb0fc0ee50e8baef15ab4f91601994e5b40a272/lib/poise_python/resources/python_execute.rb | lib/poise_python/resources/python_execute.rb | #
# Copyright 2015-2017, Noah Kantrowitz
#
# 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.
#
require 'chef/mixin/which'
require 'chef/provider/execute'
require 'chef/resource/execute'
require 'poise'
require 'poise_python/python_command_mixin'
module PoisePython
module Resources
# (see PythonExecute::Resource)
# @since 1.0.0
module PythonExecute
# A `python_execute` resource to run Python scripts and commands.
#
# @provides python_execute
# @action run
# @example
# python_execute 'myapp.py' do
# user 'myuser'
# end
class Resource < Chef::Resource::Execute
include PoisePython::PythonCommandMixin
provides(:python_execute)
actions(:run)
end
# The default provider for `python_execute`.
#
# @see Resource
# @provides python_execute
class Provider < Chef::Provider::Execute
include Chef::Mixin::Which
provides(:python_execute)
private
# Command to pass to shell_out.
#
# @return [String, Array<String>]
def command
if new_resource.command.is_a?(Array)
[new_resource.python] + new_resource.command
else
"#{new_resource.python} #{new_resource.command}"
end
end
# Environment variables to pass to shell_out.
#
# @return [Hash]
def environment
if new_resource.parent_python
environment = new_resource.parent_python.python_environment
if new_resource.environment
environment = environment.merge(new_resource.environment)
end
environment
else
new_resource.environment
end
end
end
end
end
end
| ruby | Apache-2.0 | eeb0fc0ee50e8baef15ab4f91601994e5b40a272 | 2026-01-04T17:52:09.242542Z | false |
poise/poise-python | https://github.com/poise/poise-python/blob/eeb0fc0ee50e8baef15ab4f91601994e5b40a272/lib/poise_python/resources/python_runtime_pip.rb | lib/poise_python/resources/python_runtime_pip.rb | #
# Copyright 2015-2017, Noah Kantrowitz
#
# 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.
#
require 'fileutils'
require 'tempfile'
require 'chef/resource'
require 'poise'
module PoisePython
module Resources
# (see PythonRuntimePip::Resource)
# @since 1.0.0
# @api private
module PythonRuntimePip
# Earliest version of pip we will try upgrading in-place.
PIP_INPLACE_VERSION = Gem::Version.create('7.0.0')
# Version to trigger the automatic get-pip.py URL fixup on for 2.6 compat.
PY26_FIXUP_VERSION = Gem::Version.create('2.7')
# Replacement URL for 2.6 compat.
PY26_FIXUP_GETPIP_URL = 'https://bootstrap.pypa.io/2.6/get-pip.py'
# A `python_runtime_pip` resource to install/upgrade pip itself. This is
# used internally by `python_runtime` and is not intended to be a public
# API.
#
# @provides python_runtime_pip
# @action install
# @action uninstall
class Resource < Chef::Resource
include Poise(parent: :python_runtime)
provides(:python_runtime_pip)
actions(:install, :uninstall)
# @!attribute version
# Version of pip to install. Only kind of works due to
# https://github.com/pypa/pip/issues/1087.
# @return [String]
attribute(:version, kind_of: String)
# @!attribute get_pip_url
# URL to the get-pip.py script.
# @return [String]
attribute(:get_pip_url, kind_of: String, required: true)
end
# The default provider for `python_runtime_pip`.
#
# @see Resource
# @provides python_runtime_pip
class Provider < Chef::Provider
include Poise
provides(:python_runtime_pip)
# @api private
def load_current_resource
super.tap do |current_resource|
# Try to find the current version if possible.
current_resource.version(pip_version)
end
end
# The `install` action for the `python_runtime_pip` resource.
#
# @return [void]
def action_install
Chef::Log.debug("[#{new_resource}] Installing pip #{new_resource.version || 'latest'}, currently #{current_resource.version || 'not installed'}")
if new_resource.version && current_resource.version == new_resource.version
Chef::Log.debug("[#{new_resource}] Pip #{current_resource.version} is already at requested version")
return # Desired version is installed, even if ancient.
# If you have older than 7.0.0, we're re-bootstraping because lolno.
elsif current_resource.version && Gem::Version.create(current_resource.version) >= PIP_INPLACE_VERSION
install_pip
else
bootstrap_pip
end
end
# The `uninstall` action for the `python_runtime_pip` resource.
#
# @return [void]
def action_uninstall
notifying_block do
python_package 'pip' do
action :uninstall
parent_python new_resource.parent
end
end
end
private
# Bootstrap pip using get-pip.py.
#
# @return [void]
def bootstrap_pip
# If we're on Python 2.6 and using the default get_pip_url, we need to
# switch to a 2.6-compatible version. This kind of sucks because it
# makes the default a magic value but it seems like the safest option.
get_pip_url = new_resource.get_pip_url
if get_pip_url == 'https://bootstrap.pypa.io/get-pip.py'
python_version_cmd = poise_shell_out!([new_resource.parent.python_binary, '--version'], environment: new_resource.parent.python_environment)
# Python 2 puts the output on stderr, 3 is on stdout. You can't make this shit up.
python_version = (python_version_cmd.stdout + python_version_cmd.stderr)[/Python (\S+)/, 1]
Chef::Log.debug("[#{new_resource}] Checking for Python 2.6 fixup of get-pip URL, found Python version #{python_version || '(unknown)'}")
if python_version && Gem::Version.create(python_version) < PY26_FIXUP_VERSION
Chef::Log.debug("[#{new_resource}] Detected old Python, enabling fixup")
get_pip_url = PY26_FIXUP_GETPIP_URL
end
end
# Always updated if we have hit this point.
converge_by("Bootstrapping pip #{new_resource.version || 'latest'} from #{get_pip_url}") do
# Use a temp file to hold the installer.
# Put `Tempfile.create` back when Chef on Windows has a newer Ruby.
# Tempfile.create(['get-pip', '.py']) do |temp|
temp = Tempfile.new(['get-pip', '.py'])
begin
# Download the get-pip.py.
get_pip = Chef::HTTP.new(get_pip_url).get('')
# Write it to the temp file.
temp.write(get_pip)
# Close the file to flush it.
temp.close
# Run the install. This probably needs some handling for proxies et
# al. Disable setuptools and wheel as we will install those later.
# Use the environment vars instead of CLI arguments so I don't have
# to deal with bootstrap versions that don't support --no-wheel.
boostrap_cmd = [new_resource.parent.python_binary, temp.path, '--upgrade', '--force-reinstall']
boostrap_cmd << "pip==#{new_resource.version}" if new_resource.version
Chef::Log.debug("[#{new_resource}] Running pip bootstrap command: #{boostrap_cmd.join(' ')}")
# Gross is_a? hacks but because python_runtime is a container, it
# gets the full DSL and this has user and group methods from that.
user = new_resource.parent.is_a?(PoisePython::Resources::PythonVirtualenv::Resource) ? new_resource.parent.user : nil
group = new_resource.parent.is_a?(PoisePython::Resources::PythonVirtualenv::Resource) ? new_resource.parent.group : nil
FileUtils.chown(user, group, temp.path) if user || group
poise_shell_out!(boostrap_cmd, environment: new_resource.parent.python_environment.merge('PIP_NO_SETUPTOOLS' => '1', 'PIP_NO_WHEEL' => '1'), group: group, user: user)
ensure
temp.close unless temp.closed?
temp.unlink
end
new_pip_version = pip_version
if new_resource.version && new_pip_version != new_resource.version
# We probably want to downgrade, which is silly but ¯\_(ツ)_/¯.
# Can be removed once https://github.com/pypa/pip/issues/1087 is fixed.
# That issue is fixed, leaving a bit longer for older vendored scripts.
Chef::Log.debug("[#{new_resource}] Pip bootstrap installed #{new_pip_version}, trying to install again for #{new_resource.version}")
current_resource.version(new_pip_version)
install_pip
end
end
end
# Upgrade (or downgrade) pip using itself. Should work back at least
# pip 1.5.
#
# @return [void]
def install_pip
if new_resource.version
# Already up to date, we're done here.
return if current_resource.version == new_resource.version
else
# We don't wany a specific version, so just make a general check.
return if current_resource.version
end
Chef::Log.debug("[#{new_resource}] Installing pip #{new_resource.version} via itself")
notifying_block do
# Use pip to upgrade (or downgrade) itself.
python_package 'pip' do
action :upgrade
parent_python new_resource.parent
version new_resource.version if new_resource.version
allow_downgrade true
end
end
end
# Find the version of pip currently installed in this Python runtime.
# Returns nil if not installed.
#
# @return [String, nil]
def pip_version
version_cmd = [new_resource.parent.python_binary, '-m', 'pip.__main__', '--version']
Chef::Log.debug("[#{new_resource}] Running pip version command: #{version_cmd.join(' ')}")
cmd = poise_shell_out(version_cmd, environment: new_resource.parent.python_environment)
if cmd.error?
# Not installed, probably.
nil
else
cmd.stdout[/pip ([\d.a-z]+)/, 1]
end
end
end
end
end
end
| ruby | Apache-2.0 | eeb0fc0ee50e8baef15ab4f91601994e5b40a272 | 2026-01-04T17:52:09.242542Z | false |
poise/poise-python | https://github.com/poise/poise-python/blob/eeb0fc0ee50e8baef15ab4f91601994e5b40a272/lib/poise_python/resources/pip_requirements.rb | lib/poise_python/resources/pip_requirements.rb | #
# Copyright 2015-2017, Noah Kantrowitz
#
# 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.
#
require 'shellwords'
require 'chef/provider'
require 'chef/resource'
require 'poise'
require 'poise_python/python_command_mixin'
module PoisePython
module Resources
# (see PipRequirements::Resource)
# @since 1.0.0
module PipRequirements
# A `pip_requirements` resource to install packages from a requirements.txt
# file using pip.
#
# @provides pip_requirements
# @action install
# @action upgrade
# @example
# pip_requirements '/opt/myapp/requirements.txt'
class Resource < Chef::Resource
include PoisePython::PythonCommandMixin
provides(:pip_requirements)
actions(:install, :upgrade)
# @!attribute path
# Path to the requirements file, or a folder containing the
# requirements file.
# @return [String]
attribute(:path, kind_of: String, name_attribute: true)
# @!attribute cwd
# Directory to run pip from. Defaults to the folder containing the
# requirements.txt.
# @return [String]
attribute(:cwd, kind_of: String, default: lazy { default_cwd })
# @!attribute group
# System group to install the package.
# @return [String, Integer, nil]
attribute(:group, kind_of: [String, Integer, NilClass])
# @!attribute options
# Options string to be used with `pip install`.
# @return [String, nil, false]
attribute(:options, kind_of: [String, NilClass, FalseClass])
# @!attribute user
# System user to install the package.
# @return [String, Integer, nil]
attribute(:user, kind_of: [String, Integer, NilClass])
private
# Default value for the {#cwd} property.
#
# @return [String]
def default_cwd
if ::File.directory?(path)
path
else
::File.dirname(path)
end
end
end
# The default provider for `pip_requirements`.
#
# @see Resource
# @provides pip_requirements
class Provider < Chef::Provider
include Poise
include PoisePython::PythonCommandMixin
provides(:pip_requirements)
# The `install` action for the `pip_requirements` resource.
#
# @return [void]
def action_install
install_requirements(upgrade: false)
end
# The `upgrade` action for the `pip_requirements` resource.
#
# @return [void]
def action_upgrade
install_requirements(upgrade: true)
end
private
# Run an install --requirements command and parse the output.
#
# @param upgrade [Boolean] If we should use the --upgrade flag.
# @return [void]
def install_requirements(upgrade: false)
if new_resource.options
# Use a string because we have some options.
cmd = '-m pip.__main__ install'
cmd << ' --upgrade' if upgrade
cmd << " #{new_resource.options}"
cmd << " --requirement #{Shellwords.escape(requirements_path)}"
else
# No options, use an array to be slightly faster.
cmd = %w{-m pip.__main__ install}
cmd << '--upgrade' if upgrade
cmd << '--requirement'
cmd << requirements_path
end
output = python_shell_out!(cmd, user: new_resource.user, group: new_resource.group, cwd: new_resource.cwd).stdout
if output.include?('Successfully installed')
new_resource.updated_by_last_action(true)
end
end
# Find the true path to the requirements file.
#
# @return [String]
def requirements_path
if ::File.directory?(new_resource.path)
::File.join(new_resource.path, 'requirements.txt')
else
new_resource.path
end
end
end
end
end
end
| ruby | Apache-2.0 | eeb0fc0ee50e8baef15ab4f91601994e5b40a272 | 2026-01-04T17:52:09.242542Z | false |
poise/poise-python | https://github.com/poise/poise-python/blob/eeb0fc0ee50e8baef15ab4f91601994e5b40a272/lib/poise_python/resources/python_runtime.rb | lib/poise_python/resources/python_runtime.rb | #
# Copyright 2015-2017, Noah Kantrowitz
#
# 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.
#
require 'chef/resource'
require 'poise'
module PoisePython
module Resources
# (see PythonRuntime::Resource)
# @since 1.0.0
module PythonRuntime
# A `python_runtime` resource to manage Python installations.
#
# @provides python_runtime
# @action install
# @action uninstall
# @example
# python_runtime '2.7'
class Resource < Chef::Resource
include Poise(inversion: true, container: true)
provides(:python_runtime)
actions(:install, :uninstall)
# @!attribute version
# Version of Python to install. The version is prefix-matched so `'2'`
# will install the most recent Python 2.x, and so on.
# @return [String]
# @example Install any version
# python_runtime 'any' do
# version ''
# end
# @example Install Python 2.7
# python_runtime '2.7'
attribute(:version, kind_of: String, name_attribute: true)
# @!attribute get_pip_url
# URL to download the get-pip.py script from. If not sure, the default
# of https://bootstrap.pypa.io/get-pip.py is used. If you want to skip
# the pip installer entirely, set {#pip_version} to `false`.
# @return [String]
# If this default value changes, fix ths 2.6-compat logic in python_runtime_pip.
attribute(:get_pip_url, kind_of: String, default: 'https://bootstrap.pypa.io/get-pip.py')
# @!attribute pip_version
# Version of pip to install. If set to `true`, the latest available
# pip will be used. If set to `false`, pip will not be installed. If
# set to a URL, that will be used as the URL to get-pip.py instead of
# {#get_pip_url}.
# @note Disabling the pip install may result in other resources being
# non-functional.
# @return [String, Boolean]
attribute(:pip_version, kind_of: [String, TrueClass, FalseClass], default: true)
# @!attribute setuptools_version
# Version of Setuptools to install. It set to `true`, the latest
# available version will be used. If set to `false`, setuptools will
# not be installed.
# @return [String, Boolean]
attribute(:setuptools_version, kind_of: [String, TrueClass, FalseClass], default: true)
# @!attribute virtualenv_version
# Version of Virtualenv to install. It set to `true`, the latest
# available version will be used. If set to `false`, virtualenv will
# not be installed. Virtualenv will never be installed if the built-in
# venv module is available.
# @note Disabling the virtualenv install may result in other resources
# being non-functional.
# @return [String, Boolean]
attribute(:virtualenv_version, kind_of: [String, TrueClass, FalseClass], default: true)
# @!attribute wheel_version
# Version of Wheel to install. It set to `true`, the latest
# available version will be used. If set to `false`, wheel will not
# be installed.
# @return [String, Boolean]
attribute(:wheel_version, kind_of: [String, TrueClass, FalseClass], default: true)
# The path to the `python` binary for this Python installation. This is
# an output property.
#
# @return [String]
# @example
# execute "#{resources('python_runtime[2.7]').python_binary} myapp.py"
def python_binary
provider_for_action(:python_binary).python_binary
end
# The environment variables for this Python installation. This is an
# output property.
#
# @return [Hash<String, String>]
# @example
# execute '/opt/myapp.py' do
# environment resources('python_runtime[2.7]').python_environment
# end
def python_environment
provider_for_action(:python_environment).python_environment
end
end
# Providers can be found under lib/poise_python/python_providers/
end
end
end
| ruby | Apache-2.0 | eeb0fc0ee50e8baef15ab4f91601994e5b40a272 | 2026-01-04T17:52:09.242542Z | false |
poise/poise-python | https://github.com/poise/poise-python/blob/eeb0fc0ee50e8baef15ab4f91601994e5b40a272/lib/poise_python/resources/python_package.rb | lib/poise_python/resources/python_package.rb | #
# Copyright 2015-2017, Noah Kantrowitz
#
# 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.
#
require 'shellwords'
require 'chef/mixin/which'
require 'chef/provider/package'
require 'chef/resource/package'
require 'poise'
require 'poise_python/python_command_mixin'
module PoisePython
module Resources
# (see PythonPackage::Resource)
# @since 1.0.0
module PythonPackage
# A Python snippet to check which versions of things pip would try to
# install. Probably not 100% bulletproof.
PIP_HACK_SCRIPT = <<-EOH
import json
import re
import sys
import pip
# Don't use pkg_resources because I don't want to require it before this anyway.
if re.match(r'0\\.|1\\.|6\\.0', pip.__version__):
sys.stderr.write('The python_package resource requires pip >= 6.1.0, currently '+pip.__version__+'\\n')
sys.exit(1)
try:
from pip.commands import InstallCommand
from pip.index import PackageFinder
from pip.req import InstallRequirement
install_req_from_line = InstallRequirement.from_line
except ImportError:
# Pip 10 moved all internals to their own package.
from pip._internal.commands import InstallCommand
from pip._internal.index import PackageFinder
try:
# Pip 18.1 moved from_line to the constructors
from pip._internal.req.constructors import install_req_from_line
except ImportError:
from pip._internal.req import InstallRequirement
install_req_from_line = InstallRequirement.from_line
packages = {}
cmd = InstallCommand()
options, args = cmd.parse_args(sys.argv[1:])
with cmd._build_session(options) as session:
if options.no_index:
index_urls = []
else:
index_urls = [options.index_url] + options.extra_index_urls
finder_options = dict(
find_links=options.find_links,
index_urls=index_urls,
allow_all_prereleases=options.pre,
process_dependency_links=options.process_dependency_links,
trusted_hosts=options.trusted_hosts,
session=session,
)
if getattr(options, 'format_control', None):
finder_options['format_control'] = options.format_control
finder = PackageFinder(**finder_options)
find_all = getattr(finder, 'find_all_candidates', getattr(finder, '_find_all_versions', None))
for arg in args:
req = install_req_from_line(arg)
found = finder.find_requirement(req, True)
all_candidates = find_all(req.name)
candidate = [c for c in all_candidates if c.location == found]
if candidate:
packages[candidate[0].project.lower()] = str(candidate[0].version)
json.dump(packages, sys.stdout)
EOH
# A `python_package` resource to manage Python installations using pip.
#
# @provides python_package
# @action install
# @action upgrade
# @action uninstall
# @example
# python_package 'django' do
# python '2'
# version '1.8.3'
# end
class Resource < Chef::Resource::Package
include PoisePython::PythonCommandMixin
provides(:python_package)
# Manually create matchers because #actions is unreliable.
%i{install upgrade remove}.each do |action|
Poise::Helpers::ChefspecMatchers.create_matcher(:python_package, action)
end
# @!attribute group
# System group to install the package.
# @return [String, Integer, nil]
attribute(:group, kind_of: [String, Integer, NilClass], default: lazy { default_group })
# @!attribute install_options
# Options string to be used with `pip install`.
# @return [String, Array<String>, nil, false]
attribute(:install_options, kind_of: [String, Array, NilClass, FalseClass], default: nil)
# @!attribute list_options
# Options string to be used with `pip list`.
# @return [String, Array<String>, nil, false]
attribute(:list_options, kind_of: [String, Array, NilClass, FalseClass], default: nil)
# @!attribute user
# System user to install the package.
# @return [String, Integer, nil]
attribute(:user, kind_of: [String, Integer, NilClass], default: lazy { default_user })
# This should probably be in the base class but ¯\_(ツ)_/¯.
# @!attribute allow_downgrade
# Allow downgrading the package.
# @return [Boolean]
attribute(:allow_downgrade, kind_of: [TrueClass, FalseClass], default: false)
def initialize(*args)
super
# For older Chef.
@resource_name = :python_package
# We don't have these actions.
@allowed_actions.delete(:purge)
@allowed_actions.delete(:reconfig)
end
# Upstream attribute we don't support. Sets are an error and gets always
# return nil.
#
# @api private
# @param arg [Object] Ignored
# @return [nil]
def response_file(arg=nil)
raise NoMethodError if arg
end
# (see #response_file)
def response_file_variables(arg=nil)
raise NoMethodError if arg && arg != {}
end
# (see #response_file)
def source(arg=nil)
raise NoMethodError if arg
end
private
# Find a default group, if any, from the parent Python.
#
# @api private
# @return [String, Integer, nil]
def default_group
# Use an explicit is_a? hack because python_runtime is a container so
# it gets the whole DSL and this will always respond_to?(:group).
if parent_python && parent_python.is_a?(PoisePython::Resources::PythonVirtualenv::Resource)
parent_python.group
else
nil
end
end
# Find a default user, if any, from the parent Python.
#
# @api private
# @return [String, Integer, nil]
def default_user
# See default_group for explanation of is_a? hack grossness.
if parent_python && parent_python.is_a?(PoisePython::Resources::PythonVirtualenv::Resource)
parent_python.user
else
nil
end
end
end
# The default provider for the `python_package` resource.
#
# @see Resource
class Provider < Chef::Provider::Package
include PoisePython::PythonCommandMixin
provides(:python_package)
# Load current and candidate versions for all needed packages.
#
# @api private
# @return [Chef::Resource]
def load_current_resource
@current_resource = new_resource.class.new(new_resource.name, run_context)
current_resource.package_name(new_resource.package_name)
check_package_versions(current_resource)
Chef::Log.debug("[#{new_resource}] Current version: #{current_resource.version}, candidate version: #{@candidate_version}")
current_resource
end
# Populate current and candidate versions for all needed packages.
#
# @api private
# @param resource [PoisePython::Resources::PythonPackage::Resource]
# Resource to load for.
# @param version [String, Array<String>] Current version(s) of package(s).
# @return [void]
def check_package_versions(resource, version=new_resource.version)
version_data = Hash.new {|hash, key| hash[key] = {current: nil, candidate: nil} }
# Get the version for everything currently installed.
list = pip_command('list', :list, [], environment: {'PIP_FORMAT' => 'json'}).stdout
parse_pip_list(list).each do |name, current|
# Merge current versions in to the data.
version_data[name][:current] = current
end
# Check for newer candidates.
outdated = pip_outdated(pip_requirements(resource.package_name, version, parse: true)).stdout
Chef::JSONCompat.parse(outdated).each do |name, candidate|
# Merge candidates in to the existing versions.
version_data[name][:candidate] = candidate
end
# Populate the current resource and candidate versions. Youch this is
# a gross mix of data flow.
if(resource.package_name.is_a?(Array))
@candidate_version = []
versions = []
[resource.package_name].flatten.each do |name|
ver = version_data[parse_package_name(name)]
versions << ver[:current]
@candidate_version << ver[:candidate]
end
resource.version(versions)
else
ver = version_data[parse_package_name(resource.package_name)]
resource.version(ver[:current])
@candidate_version = ver[:candidate]
end
end
# Install package(s) using pip.
#
# @param name [String, Array<String>] Name(s) of package(s).
# @param version [String, Array<String>] Version(s) of package(s).
# @return [void]
def install_package(name, version)
pip_install(name, version, upgrade: false)
end
# Upgrade package(s) using pip.
#
# @param name [String, Array<String>] Name(s) of package(s).
# @param version [String, Array<String>] Version(s) of package(s).
# @return [void]
def upgrade_package(name, version)
pip_install(name, version, upgrade: true)
end
# Uninstall package(s) using pip.
#
# @param name [String, Array<String>] Name(s) of package(s).
# @param version [String, Array<String>] Version(s) of package(s).
# @return [void]
def remove_package(name, version)
pip_command('uninstall', :install, %w{--yes} + [name].flatten)
end
private
# Convert name(s) and version(s) to an array of pkg_resources.Requirement
# compatible strings. These are strings like "django" or "django==1.0".
#
# @param name [String, Array<String>] Name or names for the packages.
# @param version [String, Array<String>] Version or versions for the
# packages.
# @param parse [Boolean] Use parsed package names.
# @return [Array<String>]
def pip_requirements(name, version, parse: false)
[name].flatten.zip([version].flatten).map do |n, v|
n = parse_package_name(n) if parse
v = v.to_s.strip
if n =~ /:\/\//
# Probably a URI.
n
elsif v.empty?
# No version requirement, send through unmodified.
n
elsif v =~ /^\d/
"#{n}==#{v}"
else
# If the first character isn't a digit, assume something fancy.
n + v
end
end
end
# Run a pip command.
#
# @param pip_command [String, nil] The pip subcommand to run (eg. install).
# @param options_type [Symbol] Either `:install` to `:list` to select
# which extra options to use.
# @param pip_options [Array<String>] Options for the pip command.
# @param opts [Hash] Mixlib::ShellOut options.
# @return [Mixlib::ShellOut]
def pip_command(pip_command, options_type, pip_options=[], opts={})
runner = opts.delete(:pip_runner) || %w{-m pip.__main__}
type_specific_options = new_resource.send(:"#{options_type}_options")
full_cmd = if new_resource.options || type_specific_options
if (new_resource.options && new_resource.options.is_a?(String)) || (type_specific_options && type_specific_options.is_a?(String))
# We have to use a string for this case to be safe because the
# options are a string and I don't want to try and parse that.
global_options = new_resource.options.is_a?(Array) ? Shellwords.join(new_resource.options) : new_resource.options.to_s
type_specific_options = type_specific_options.is_a?(Array) ? Shellwords.join(type_specific_options) : type_specific_options.to_s
"#{runner.join(' ')} #{pip_command} #{global_options} #{type_specific_options} #{Shellwords.join(pip_options)}"
else
runner + (pip_command ? [pip_command] : []) + (new_resource.options || []) + (type_specific_options || []) + pip_options
end
else
# No special options, use an array to skip the extra /bin/sh.
runner + (pip_command ? [pip_command] : []) + pip_options
end
# Set user and group.
opts[:user] = new_resource.user if new_resource.user
opts[:group] = new_resource.group if new_resource.group
python_shell_out!(full_cmd, opts)
end
# Run `pip install` to install a package(s).
#
# @param name [String, Array<String>] Name(s) of package(s) to install.
# @param version [String, Array<String>] Version(s) of package(s) to
# install.
# @param upgrade [Boolean] Use upgrade mode?
# @return [Mixlib::ShellOut]
def pip_install(name, version, upgrade: false)
cmd = pip_requirements(name, version)
# Prepend --upgrade if needed.
cmd = %w{--upgrade} + cmd if upgrade
pip_command('install', :install, cmd)
end
# Run my hacked version of `pip list --outdated` with a specific set of
# package requirements.
#
# @see #pip_requirements
# @param requirements [Array<String>] Pip-formatted package requirements.
# @return [Mixlib::ShellOut]
def pip_outdated(requirements)
pip_command(nil, :list, requirements, input: PIP_HACK_SCRIPT, pip_runner: %w{-})
end
# Parse the output from `pip list`. Returns a hash of package key to
# current version.
#
# @param text [String] Output to parse.
# @return [Hash<String, String>]
def parse_pip_list(text)
if text[0] == '['
# Pip 9 or newer, so it understood $PIP_FORMAT=json.
Chef::JSONCompat.parse(text).each_with_object({}) do |data, memo|
memo[parse_package_name(data['name'])] = data['version']
end
else
# Pip 8 or earlier, which doesn't support JSON output.
text.split(/\r?\n/).each_with_object({}) do |line, memo|
# Example of a line:
# boto (2.25.0)
if md = line.match(/^(\S+)\s+\(([^\s,]+).*\)$/i)
memo[parse_package_name(md[1])] = md[2]
else
Chef::Log.debug("[#{new_resource}] Unparsable line in pip list: #{line}")
end
end
end
end
# Regexp for package URLs.
PACKAGE_NAME_URL = /:\/\/.*?#egg=(.*)$/
# Regexp for extras.
PACKAGE_NAME_EXTRA = /^(.*?)\[.*?\]$/
# Find the underlying name from a pip input sequence.
#
# @param raw_name [String] Raw package name.
# @return [String]
def parse_package_name(raw_name)
case raw_name
when PACKAGE_NAME_URL, PACKAGE_NAME_EXTRA
$1
else
raw_name
end.downcase.gsub(/_/, '-')
end
end
end
end
end
| ruby | Apache-2.0 | eeb0fc0ee50e8baef15ab4f91601994e5b40a272 | 2026-01-04T17:52:09.242542Z | false |
poise/poise-python | https://github.com/poise/poise-python/blob/eeb0fc0ee50e8baef15ab4f91601994e5b40a272/lib/poise_python/resources/python_virtualenv.rb | lib/poise_python/resources/python_virtualenv.rb | #
# Copyright 2015-2017, Noah Kantrowitz
#
# 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.
#
require 'poise'
# Break a require loop by letting autoload work its magic.
require 'poise_python'
module PoisePython
module Resources
# (see PythonVirtualenv::Resource)
# @since 1.0.0
module PythonVirtualenv
# A `python_virtualenv` resource to manage Python virtual environments.
#
# @provides python_virtualenv
# @action create
# @action delete
# @example
# python_virtualenv '/opt/myapp'
class Resource < PoisePython::Resources::PythonRuntime::Resource
include PoisePython::PythonCommandMixin
provides(:python_virtualenv)
# Add create and delete actions as more semantically relevant aliases.
default_action(:create)
actions(:create, :delete)
# @!attribute path
# Path to create the environment at.
# @return [String]
attribute(:path, kind_of: String, name_attribute: true)
# @!attribute group
# System group to create the virtualenv.
# @return [String, Integer, nil]
attribute(:group, kind_of: [String, Integer, NilClass])
# @!attribute system_site_packages
# Enable or disable visibilty of system packages in the environment.
# @return [Boolean]
attribute(:system_site_packages, equal_to: [true, false], default: false)
# @!attribute user
# System user to create the virtualenv.
# @return [String, Integer, nil]
attribute(:user, kind_of: [String, Integer, NilClass])
# Lock the default provider.
#
# @api private
def initialize(*args)
super
# Sidestep all the normal provider lookup stuffs. This is kind of
# gross but it will do for now. The hard part is that the base classes
# for the resource and provider are using Poise::Inversion, which we
# don't want to use for python_virtualenv.
@provider = Provider
end
# Upstream attribute we don't support. Sets are an error and gets always
# return nil.
#
# @api private
# @param arg [Object] Ignored
# @return [nil]
def version(arg=nil)
raise NoMethodError if arg
end
# (see #version)
def virtualenv_version(arg=nil)
raise NoMethodError if arg
end
end
# The default provider for `python_virtualenv`.
#
# @see Resource
# @provides python_virtualenv
class Provider < PoisePython::PythonProviders::Base
include PoisePython::PythonCommandMixin
provides(:python_virtualenv)
# Alias our actions. Slightly annoying that they will show in
# tracebacks with the original names, but oh well.
alias_method :action_create, :action_install
alias_method :action_delete, :action_uninstall
def python_binary
if node.platform_family?('windows')
::File.join(new_resource.path, 'Scripts', 'python.exe')
else
::File.join(new_resource.path, 'bin', 'python')
end
end
def python_environment
if new_resource.parent_python
new_resource.parent_python.python_environment
else
{}
end
end
private
def install_python
return if ::File.exist?(python_binary)
cmd = python_shell_out(%w{-m venv -h})
if cmd.error?
converge_by("Creating virtualenv at #{new_resource.path}") do
create_virtualenv(%w{virtualenv})
end
else
converge_by("Creating venv at #{new_resource.path}") do
use_withoutpip = cmd.stdout.include?('--without-pip')
create_virtualenv(use_withoutpip ? %w{venv --without-pip} : %w{venv})
end
end
end
def uninstall_python
directory new_resource.path do
action :delete
recursive true
end
end
# Don't install virtualenv inside virtualenv.
#
# @api private
# @return [void]
def install_virtualenv
# This space left intentionally blank.
end
# Create a virtualenv using virtualenv or venv.
#
# @param driver [Array<String>] Command snippet to actually make it.
# @return [void]
def create_virtualenv(driver)
cmd = %w{-m} + driver
cmd << '--system-site-packages' if new_resource.system_site_packages
cmd << new_resource.path
python_shell_out!(cmd, environment: {
# Use the environment variables to cope with older virtualenv not
# supporting --no-wheel. The env var will be ignored if unsupported.
'VIRTUALENV_NO_PIP' => '1',
'VIRTUALENV_NO_SETUPTOOLS' => '1',
'VIRTUALENV_NO_WHEEL' => '1',
}, group: new_resource.group, user: new_resource.user)
end
end
end
end
end
| ruby | Apache-2.0 | eeb0fc0ee50e8baef15ab4f91601994e5b40a272 | 2026-01-04T17:52:09.242542Z | false |
poise/poise-python | https://github.com/poise/poise-python/blob/eeb0fc0ee50e8baef15ab4f91601994e5b40a272/lib/poise_python/resources/python_runtime_test.rb | lib/poise_python/resources/python_runtime_test.rb | #
# Copyright 2015-2017, Noah Kantrowitz
#
# 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.
#
require 'chef/provider'
require 'chef/resource'
require 'poise'
module PoisePython
module Resources
# (see PythonRuntimeTest::Resource)
# @since 1.0.0
# @api private
module PythonRuntimeTest
# A `python_runtime_test` resource for integration testing of this
# cookbook. This is an internal API and can change at any time.
#
# @provides python_runtime_test
# @action run
class Resource < Chef::Resource
include Poise
provides(:python_runtime_test)
actions(:run)
attribute(:version, kind_of: String, name_attribute: true)
attribute(:runtime_provider, kind_of: Symbol)
attribute(:path, kind_of: String, default: lazy { default_path })
def default_path
::File.join('', "python_test_#{name}")
end
end
# The default provider for `python_runtime_test`.
#
# @see Resource
# @provides python_runtime_test
class Provider < Chef::Provider
include Poise
provides(:python_runtime_test)
# The `run` action for the `python_runtime_test` resource.
#
# @return [void]
def action_run
notifying_block do
# Top level directory for this test.
directory new_resource.path do
mode '777'
end
# Install and log the version.
python_runtime new_resource.name do
provider new_resource.runtime_provider if new_resource.runtime_provider
version new_resource.version
end
test_version
# Test python_package.
python_package 'argparse' do
# Needed for sqlparse but not in the stdlib until 2.7.
python new_resource.name
end
python_package 'sqlparse remove before' do
action :remove
package_name 'sqlparse'
python new_resource.name
end
test_import('sqlparse', 'sqlparse_before')
python_package 'sqlparse' do
python new_resource.name
notifies :create, sentinel_file('sqlparse'), :immediately
end
test_import('sqlparse', 'sqlparse_mid')
python_package 'sqlparse again' do
package_name 'sqlparse'
python new_resource.name
notifies :create, sentinel_file('sqlparse2'), :immediately
end
python_package 'sqlparse remove after' do
action :remove
package_name 'sqlparse'
python new_resource.name
end
test_import('sqlparse', 'sqlparse_after')
# Use setuptools to test something that should always be installed.
python_package 'setuptools' do
python new_resource.name
notifies :create, sentinel_file('setuptools'), :immediately
end
# Multi-package install.
python_package ['pep8', 'pytz'] do
python new_resource.name
end
test_import('pep8')
test_import('pytz')
# Create a virtualenv.
python_virtualenv ::File.join(new_resource.path, 'venv') do
python new_resource.name
end
# Install a package inside a virtualenv.
python_package 'Pytest' do
virtualenv ::File.join(new_resource.path, 'venv')
end
test_import('pytest')
test_import('pytest', 'pytest_venv', python: nil, virtualenv: ::File.join(new_resource.path, 'venv'))
# Create and install a requirements file.
# Running this in a venv because of pip 8.0 and Ubuntu packaing
# both requests and six.
python_virtualenv ::File.join(new_resource.path, 'venv2') do
python new_resource.name
end
file ::File.join(new_resource.path, 'requirements.txt') do
content <<-EOH
requests==2.7.0
six==1.8.0
EOH
end
pip_requirements ::File.join(new_resource.path, 'requirements.txt') do
virtualenv ::File.join(new_resource.path, 'venv2')
end
test_import('requests', python: nil, virtualenv: ::File.join(new_resource.path, 'venv2'))
test_import('six', python: nil, virtualenv: ::File.join(new_resource.path, 'venv2'))
# Install a non-latest version of a package.
python_virtualenv ::File.join(new_resource.path, 'venv3') do
python new_resource.name
end
python_package 'requests' do
version '2.8.0'
virtualenv ::File.join(new_resource.path, 'venv3')
end
test_import('requests', 'requests_version', python: nil, virtualenv: ::File.join(new_resource.path, 'venv3'))
# Don't run the user tests on Windows.
unless node.platform_family?('windows')
# Create a non-root user and test installing with it.
test_user = "py#{new_resource.name}"
test_home = ::File.join('', 'home', test_user)
group 'g'+test_user do
system true
end
user test_user do
comment "Test user for python_runtime_test #{new_resource.name}"
gid 'g'+test_user
home test_home
shell '/bin/false'
system true
end
directory test_home do
mode '700'
group 'g'+test_user
user test_user
end
test_venv = python_virtualenv ::File.join(test_home, 'env') do
python new_resource.name
user test_user
end
python_package 'docopt' do
user test_user
virtualenv test_venv
end
test_import('docopt', python: nil, virtualenv: test_venv, user: test_user)
end
end
end
def sentinel_file(name)
file ::File.join(new_resource.path, "sentinel_#{name}") do
action :nothing
end
end
private
def test_version(python: new_resource.name, virtualenv: nil)
# Only queue up this resource once, the ivar is just for tracking.
@python_version_test ||= file ::File.join(new_resource.path, 'python_version.py') do
user node.platform_family?('windows') ? Poise::Utils::Win32.admin_user : 'root'
group node['root_group']
mode '644'
content <<-EOH
import sys, platform
open(sys.argv[1], 'w').write(platform.python_version())
EOH
end
python_execute "#{@python_version_test.path} #{::File.join(new_resource.path, 'version')}" do
python python if python
virtualenv virtualenv if virtualenv
end
end
def test_import(name, path=name, python: new_resource.name, virtualenv: nil, user: nil)
# Only queue up this resource once, the ivar is just for tracking.
@python_import_test ||= file ::File.join(new_resource.path, 'import_version.py') do
user node.platform_family?('windows') ? Poise::Utils::Win32.admin_user : 'root'
group node['root_group']
mode '644'
content <<-EOH
try:
import sys
mod = __import__(sys.argv[1])
open(sys.argv[2], 'w').write(mod.__version__)
except ImportError:
pass
EOH
end
python_execute "#{@python_import_test.path} #{name} #{::File.join(new_resource.path, "import_#{path}")}" do
python python if python
user user if user
virtualenv virtualenv if virtualenv
end
end
end
end
end
end
| ruby | Apache-2.0 | eeb0fc0ee50e8baef15ab4f91601994e5b40a272 | 2026-01-04T17:52:09.242542Z | false |
holiday-jp/holiday_jp | https://github.com/holiday-jp/holiday_jp/blob/f9d2e3c5c1347103ead5f12c588e4a69178b911c/spec/holidays_detailed_spec.rb | spec/holidays_detailed_spec.rb | # -*- coding: utf-8 -*-
require 'spec_helper'
require 'yaml'
require 'json'
require 'date'
context 'Emperor\'s Birthday' do
before do
@holidays_detailed = YAML.load_file(File.expand_path('../../holidays_detailed.yml', __FILE__), permitted_classes: [Date])
end
it 'holidays_detail.yml should have holiday in Showa Emperor\'s Birthday' do
1970.upto(1988) do |year|
expect(@holidays_detailed.key?(Date.new(year, 4, 29))).to eq true
end
end
it 'holidays_detail.yml should have holiday in Heisei Emperor\'s Birthday' do
1989.upto(2018) do |year|
expect(@holidays_detailed.key?(Date.new(year, 12, 23))).to eq true
end
end
it 'holidays_detail.yml should have no holiday in 2019 Emperor\'s Birthday' do
expect(@holidays_detailed.key?(Date.new(2019, 2, 23))).to eq false
expect(@holidays_detailed.key?(Date.new(2019, 12, 23))).to eq false
end
it 'holidays_detail.yml should have holiday in New Emperor\'s Birthday' do
2020.upto(2050) do |year|
expect(@holidays_detailed.key?(Date.new(year, 2, 23))).to eq true
end
end
end
context 'Holiday in lieu' do
before do
@holidays_detailed = YAML.load_file(File.expand_path('../../holidays_detailed.yml', __FILE__), permitted_classes: [Date])
end
it 'If holiday is Sunday, Holiday in lieu should exist. (>= 1973.4.30)' do
@holidays_detailed.each do |date, detail|
if date >= Date.new(1973, 4, 30) && date.wday == 0 && !detail['name'].match(/振替休日/)
expect(@holidays_detailed.key?(date + 1)).to eq true
end
end
end
end
context 'Tokyo Olympic' do
before do
@holidays_detailed = YAML.load_file(File.expand_path('../../holidays_detailed.yml', __FILE__), permitted_classes: [Date])
end
it 'If tokyo olympic year, 海の日 should be moved' do
expect(@holidays_detailed.key?(Date::parse('2020-07-20'))).to eq false
expect(@holidays_detailed.key?(Date::parse('2020-07-23'))).to eq true
end
it 'If tokyo olympic year, 山の日 should be moved' do
expect(@holidays_detailed.key?(Date::parse('2020-08-11'))).to eq false
expect(@holidays_detailed.key?(Date::parse('2020-08-10'))).to eq true
end
it 'If tokyo olympic year, 体育の日 should be moved' do
expect(@holidays_detailed.key?(Date::parse('2020-10-12'))).to eq false
expect(@holidays_detailed.key?(Date::parse('2020-07-24'))).to eq true
end
it 'If tokyo olympic 2021, 海の日 should be moved' do
expect(@holidays_detailed.key?(Date::parse('2021-07-19'))).to eq false
expect(@holidays_detailed.key?(Date::parse('2021-07-22'))).to eq true
end
it 'If tokyo olympic 2021, 山の日 should be moved' do
expect(@holidays_detailed.key?(Date::parse('2021-08-11'))).to eq false
expect(@holidays_detailed.key?(Date::parse('2021-08-08'))).to eq true
expect(@holidays_detailed.key?(Date::parse('2021-08-09'))).to eq true
end
it 'If tokyo olympic 2021, スポーツの日 should be moved' do
expect(@holidays_detailed.key?(Date::parse('2021-10-11'))).to eq false
expect(@holidays_detailed.key?(Date::parse('2021-07-23'))).to eq true
end
end
context 'Coronation Day / 天皇の即位の日及び即位礼正殿の儀の行われる日を休日とする法律' do
before do
@holidays_detailed = YAML.load_file(File.expand_path('../../holidays_detailed.yml', __FILE__), permitted_classes: [Date])
end
it '天皇の即位の日の平成31年(2019年)5月1日及び即位礼正殿の儀が行われる日の平成31年(2019年)10月22日は、休日となります' do
expect(@holidays_detailed.key?(Date::parse('2019-05-01'))).to eq true
expect(@holidays_detailed.key?(Date::parse('2019-10-22'))).to eq true
end
it 'また、これらの休日は国民の祝日扱いとなるため、平成31年(2019年)4月30日と5月2日も休日となります' do
expect(@holidays_detailed.key?(Date::parse('2019-04-30'))).to eq true
expect(@holidays_detailed.key?(Date::parse('2019-05-02'))).to eq true
end
end
context 'holiday.yml' do
before do
@holidays_detailed = YAML.load_file(File.expand_path('../../holidays_detailed.yml', __FILE__), permitted_classes: [Date])
end
it 'holidays_detailed.yml should have date of holiday.yml and holiday.yml should have of holiday_detail.yml' do
holidays = YAML.load_file(File.expand_path('../../holidays.yml', __FILE__), permitted_classes: [Date])
holidays.each do |date, name|
expect(@holidays_detailed.key?(date)).to eq true
expect(@holidays_detailed[date]['name']).to eq name
end
@holidays_detailed.each do |date, detail|
expect(holidays.key?(date)).to eq true
expect(holidays[date]).to eq detail['name']
end
expect(holidays.length).to eq @holidays_detailed.length
end
end
| ruby | MIT | f9d2e3c5c1347103ead5f12c588e4a69178b911c | 2026-01-04T17:52:20.035353Z | false |
holiday-jp/holiday_jp | https://github.com/holiday-jp/holiday_jp/blob/f9d2e3c5c1347103ead5f12c588e4a69178b911c/spec/syukujitsu_csv_spec.rb | spec/syukujitsu_csv_spec.rb | # -*- coding: utf-8 -*-
require 'spec_helper'
require 'yaml'
require 'csv'
require 'open-uri'
require 'date'
require 'uri'
context 'Check holidays.yml by syukujitsu.csv' do
before do
@holidays = YAML.load_file(File.expand_path('../../holidays.yml', __FILE__), permitted_classes: [Date])
csv_url = 'https://www8.cao.go.jp/chosei/shukujitsu/syukujitsu.csv'
csv = URI.open(csv_url).read
@cholidays = CSV.parse(csv, headers: true, encoding: 'Shift_JIS')
end
it '3条1項 「国民の祝日」は、休日とする。' do
@cholidays.each do |row|
d = Date::parse(row[0])
next if d < Date.new(2005, 5, 20) # 最終改正:平成17年5月20日
expect(@holidays.key?(d)).to eq true
expect(@holidays[d]).to eq(row[1].encode('UTF-8', 'Shift_JIS')).or match(/振替休日/)
end
end
it '3条2項 「国民の祝日」が日曜日に当たるときは、その日後においてその日に最も近い「国民の祝日」でない日を休日とする。' do
@cholidays.each do |row|
d = Date::parse(row[0])
next if d < Date.new(2005, 5, 20) # 最終改正:平成17年5月20日
expect(@holidays.key?(d + 1)).to eq true if d.sunday?
end
end
it '3条3項 その前日及び翌日が「国民の祝日」である日(「国民の祝日」でない日に限る。)は、休日とする。' do
@cholidays.each do |row|
d = Date::parse(row[0])
next if d < Date.new(2005, 5, 20) # 最終改正:平成17年5月20日
key = (d + 2).strftime('%Y-%m-%d')
expect(@holidays.key?(d + 1)).to eq true if @cholidays.find do |r|
r[0] == key
end
end
end
it 'Check all holidays since 1970' do
@cholidays.each do |row|
d = Date::parse(row[0])
next if d < Date.new(1970, 1, 1)
expect(@holidays.key?(d)).to eq true
expect(@holidays[d]).to eq(row[1].encode('UTF-8', 'Shift_JIS')).or match(/振替休日/)
end
end
end
| ruby | MIT | f9d2e3c5c1347103ead5f12c588e4a69178b911c | 2026-01-04T17:52:20.035353Z | false |
holiday-jp/holiday_jp | https://github.com/holiday-jp/holiday_jp/blob/f9d2e3c5c1347103ead5f12c588e4a69178b911c/spec/spec_helper.rb | spec/spec_helper.rb | ruby | MIT | f9d2e3c5c1347103ead5f12c588e4a69178b911c | 2026-01-04T17:52:20.035353Z | false | |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/app/jobs/sbmt/outbox/delete_stale_outbox_items_job.rb | app/jobs/sbmt/outbox/delete_stale_outbox_items_job.rb | # frozen_string_literal: true
module Sbmt
module Outbox
class DeleteStaleOutboxItemsJob < BaseDeleteStaleItemsJob
queue_as :outbox
class << self
def item_classes
Outbox.outbox_item_classes
end
end
end
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/app/jobs/sbmt/outbox/base_delete_stale_items_job.rb | app/jobs/sbmt/outbox/base_delete_stale_items_job.rb | # frozen_string_literal: true
require "redlock"
module Sbmt
module Outbox
class BaseDeleteStaleItemsJob < Outbox.active_job_base_class
LOCK_TTL = 10_800_000
class << self
def enqueue
item_classes.each do |item_class|
delay = rand(15).seconds
set(wait: delay).perform_later(item_class.to_s)
end
end
def item_classes
raise NotImplementedError
end
end
delegate :config, :logger, to: "Sbmt::Outbox"
delegate :box_type, :box_name, to: :item_class
attr_accessor :item_class, :lock_timer
def perform(item_class_name)
self.item_class = item_class_name.constantize
client = if Gem::Version.new(Redlock::VERSION) >= Gem::Version.new("2.0.0")
Sbmt::Outbox.redis
else
Redis.new(config.redis)
end
self.lock_timer = Cutoff.new(LOCK_TTL / 1000)
lock_manager = Redlock::Client.new([client], retry_count: 0)
lock_manager.lock("#{self.class.name}:#{item_class_name}:lock", LOCK_TTL) do |locked|
if locked
duration_failed = item_class.config.retention
duration_delivered = item_class.config.retention_delivered_items
validate_retention!(duration_delivered, duration_failed)
logger.with_tags(box_type: box_type, box_name: box_name) do
delete_stale_items(Time.current - duration_failed, Time.current - duration_delivered)
end
else
logger.log_info("Failed to acquire lock #{self.class.name}:#{item_class_name}")
end
end
rescue Cutoff::CutoffExceededError
logger.log_info("Lock timeout while processing #{item_class_name}")
end
private
def validate_retention!(duration_delivered, duration_failed)
validate_retention_for!(
duration: duration_delivered,
min_period: item_class.config.delivered_min_retention_period,
error_message: "Retention period for #{box_name} must be longer than #{item_class.config.delivered_min_retention_period.inspect}"
)
validate_retention_for!(
duration: duration_failed,
min_period: item_class.config.min_retention_period,
error_message: "Retention period for #{box_name} must be longer than #{item_class.config.min_retention_period.inspect}"
)
end
def validate_retention_for!(duration:, min_period:, error_message:)
raise error_message if duration < min_period
end
def delete_stale_items(waterline_failed, waterline_delivered)
logger.log_info("Start deleting #{box_type} items for #{box_name} older than: failed and discarded items #{waterline_failed} and delivered items #{waterline_delivered}")
case database_type
when :postgresql
postgres_delete_in_batches(waterline_failed, waterline_delivered)
when :mysql
mysql_delete_in_batches(waterline_failed, waterline_delivered)
else
raise "Unsupported database type"
end
logger.log_info("Successfully deleted #{box_type} items for #{box_name} older than: failed and discarded items #{waterline_failed} and delivered items #{waterline_delivered}")
end
# Deletes stale items from PostgreSQL database in batches
#
# This method efficiently deletes items older than the given waterline
# using a subquery approach to avoid locking large portions of the table.
#
#
# Example SQL generated for deletion:
# DELETE FROM "items"
# WHERE "items"."id" IN (
# SELECT "items"."id"
# FROM "items"
# WHERE (
# "items"."status" IN (2) AND "items"."created_at" BETWEEN "2025-01-29 12:18:32.917836" AND "2025-01-29 12:18:32.927596" LIMIT 1000
# )
# )
def postgres_delete_in_batches(waterline_failed, waterline_delivered)
status_delivered = item_class.statuses[:delivered]
status_failed_discarded = item_class.statuses.values_at(:failed, :discarded)
delete_items_in_batches_with_between(waterline_delivered, status_delivered)
delete_items_in_batches_with_between(waterline_failed, status_failed_discarded)
end
def delete_items_in_batches_with_between(waterline, statuses)
table = item_class.arel_table
batch_size = item_class.config.deletion_batch_size
time_window = item_class.config.deletion_time_window
min_date = Outbox.database_switcher.use_slave do
# This query assumes that record with minimum 'id' also has minimum 'created_at'.
# We use it because it should be faster than plain 'SELECT MIN(created_at) ...'.
min_id = item_class.select(table[:id].minimum).where(status: statuses)
item_class.select(:created_at).where(table[:id].eq(min_id.arel)).first&.created_at
end
deleted_count = nil
while min_date && min_date < waterline
max_date = [min_date + time_window, waterline].min
loop do
subquery = table
.project(table[:id])
.where(table[:status].in(statuses))
.where(table[:created_at].between(min_date..max_date))
.take(batch_size)
delete_statement = Arel::Nodes::DeleteStatement.new
delete_statement.relation = table
delete_statement.wheres = [table[:id].in(subquery)]
track_deleted_latency do
deleted_count = item_class.connection.execute(delete_statement.to_sql).cmd_tuples
end
track_deleted_counter(deleted_count)
logger.log_info("Deleted #{deleted_count} #{box_type} items for #{box_name} between #{min_date} and #{max_date}")
break if deleted_count < batch_size
lock_timer.checkpoint!
sleep(item_class.config.deletion_sleep_time) if deleted_count > 0
end
min_date = max_date
end
end
# Deletes stale items from MySQL database in batches
#
# This method efficiently deletes items older than the given waterline
# using MySQL's built-in LIMIT clause for DELETE statements.
#
# The main difference from the PostgreSQL method is that MySQL allows
# direct use of LIMIT in DELETE statements, simplifying the query.
# This approach doesn't require a subquery, making it more straightforward.
#
# Example SQL generated for deletion:
# DELETE FROM "items"
# WHERE (
# "items"."status" IN (2) AND "items"."created_at" BETWEEN "2024-12-29 18:34:25.369234" AND "2024-12-29 22:34:25.369234" LIMIT 1000
# )
def mysql_delete_in_batches(waterline_failed, waterline_delivered)
status_delivered = item_class.statuses[:delivered]
status_failed_discarded = [item_class.statuses.values_at(:failed, :discarded)]
delete_items_in_batches_with_between_mysql(waterline_delivered, status_delivered)
delete_items_in_batches_with_between_mysql(waterline_failed, status_failed_discarded)
end
def delete_items_in_batches_with_between_mysql(waterline, statuses)
table = item_class.arel_table
batch_size = item_class.config.deletion_batch_size
time_window = item_class.config.deletion_time_window
min_date = Outbox.database_switcher.use_slave do
# This query assumes that record with minimum 'id' also has minimum 'created_at'.
# We use it because plain 'SELECT MIN(created_at) ...' is VERY slow in MySQL.
min_id = item_class.select(table[:id].minimum).where(status: statuses)
item_class.select(:created_at).where(table[:id].eq(min_id.arel)).first&.created_at
end
deleted_count = nil
while min_date && min_date < waterline
max_date = [min_date + time_window, waterline].min
loop do
track_deleted_latency do
deleted_count = item_class
.where(status: statuses, created_at: min_date..max_date)
.limit(batch_size)
.delete_all
end
track_deleted_counter(deleted_count)
logger.log_info("Deleted #{deleted_count} #{box_type} items for #{box_name} between #{min_date} and #{max_date}")
break if deleted_count < batch_size
lock_timer.checkpoint!
sleep(item_class.config.deletion_sleep_time) if deleted_count > 0
end
min_date = max_date
end
end
def database_type
adapter_name = item_class.connection.adapter_name.downcase
case adapter_name
when "postgresql", "postgis"
:postgresql
when "mysql2"
:mysql
else
:unknown
end
end
def track_deleted_counter(deleted_count)
::Yabeda
.outbox
.deleted_counter
.increment({box_type: box_type, box_name: box_name}, by: deleted_count)
end
def track_deleted_latency
::Yabeda
.outbox
.delete_latency
.measure({box_type: box_type, box_name: box_name}) do
yield
end
end
end
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/app/jobs/sbmt/outbox/delete_stale_inbox_items_job.rb | app/jobs/sbmt/outbox/delete_stale_inbox_items_job.rb | # frozen_string_literal: true
module Sbmt
module Outbox
class DeleteStaleInboxItemsJob < BaseDeleteStaleItemsJob
queue_as :inbox
class << self
def item_classes
Outbox.inbox_item_classes
end
end
end
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/app/controllers/sbmt/outbox/root_controller.rb | app/controllers/sbmt/outbox/root_controller.rb | # frozen_string_literal: true
module Sbmt
module Outbox
class RootController < Sbmt::Outbox.action_controller_base_class
def index
@local_endpoint = Outbox.config.ui.local_endpoint
@cdn_url = Outbox.config.ui.cdn_url
end
end
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/app/controllers/sbmt/outbox/api/outbox_classes_controller.rb | app/controllers/sbmt/outbox/api/outbox_classes_controller.rb | # frozen_string_literal: true
module Sbmt
module Outbox
module Api
class OutboxClassesController < BaseController
def index
render_list(Sbmt::Outbox.outbox_item_classes.map do |item|
Api::OutboxClass.find_or_initialize(item.box_id)
end)
end
def show
render_one Api::OutboxClass.find_or_initialize(params.require(:id))
end
def update
record = Api::OutboxClass.find_or_initialize(params.require(:id))
record.assign_attributes(
params.require(:outbox_class).permit(:polling_enabled)
)
record.save
render_one record
end
def destroy
record = Api::OutboxClass.find(params.require(:id))
unless record
render_ok
return
end
record.destroy
render_one record
end
end
end
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/app/controllers/sbmt/outbox/api/inbox_classes_controller.rb | app/controllers/sbmt/outbox/api/inbox_classes_controller.rb | # frozen_string_literal: true
module Sbmt
module Outbox
module Api
class InboxClassesController < BaseController
def index
render_list(Sbmt::Outbox.inbox_item_classes.map do |item|
Sbmt::Outbox::Api::InboxClass.find_or_initialize(item.box_id)
end)
end
def show
render_one Sbmt::Outbox::Api::InboxClass.find_or_initialize(params.require(:id))
end
def update
record = Sbmt::Outbox::Api::InboxClass.find_or_initialize(params.require(:id))
record.assign_attributes(
params.require(:inbox_class).permit(:polling_enabled)
)
record.save
render_one record
end
def destroy
record = Sbmt::Outbox::Api::InboxClass.find(params.require(:id))
unless record
render_ok
return
end
record.destroy
render_one record
end
end
end
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/app/controllers/sbmt/outbox/api/base_controller.rb | app/controllers/sbmt/outbox/api/base_controller.rb | # frozen_string_literal: true
module Sbmt
module Outbox
module Api
class BaseController < Sbmt::Outbox.action_controller_api_base_class
private
def render_ok
render json: "OK"
end
def render_one(record)
render json: record
end
def render_list(records)
response.headers["X-Total-Count"] = records.size
render json: records
end
end
end
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/app/models/sbmt/outbox/base_item.rb | app/models/sbmt/outbox/base_item.rb | # frozen_string_literal: true
# For compatibility with rails < 7
# Remove when drop support of Rails < 7
require_relative "../../../../lib/sbmt/outbox/enum_refinement"
using Sbmt::Outbox::EnumRefinement
module Sbmt
module Outbox
class BaseItem < Outbox.active_record_base_class
self.abstract_class = true
delegate :retriable?, to: :class
class << self
delegate :owner, :strict_order, to: :config
def box_type
raise NotImplementedError
end
def box_name
@box_name ||= name.underscore
end
def box_id
@box_id ||= name.underscore.tr("/", "-").dasherize
end
def config
@config ||= lookup_config.new(box_id: box_id, box_name: box_name)
end
def calc_bucket_partitions(count)
(0...count).to_a
.index_with do |x|
(0...config.bucket_size).to_a
.select { |p| p % count == x }
end
end
def partition_buckets
@partition_buckets ||= calc_bucket_partitions(config.partition_size)
end
def bucket_partitions
@bucket_partitions ||=
partition_buckets.each_with_object({}) do |(partition, buckets), m|
buckets.each do |bucket|
m[bucket] = partition
end
end
end
def max_retries_exceeded?(count)
return false if config.strict_order
return true unless retriable?
count > config.max_retries
end
def retriable?
config.max_retries > 0
end
end
enum :status, {
pending: 0,
failed: 1,
delivered: 2,
discarded: 3
}
scope :for_processing, -> { where(status: :pending) }
validates :uuid, :event_key, :bucket, :payload, presence: true
delegate :box_name, :config, to: "self.class"
after_initialize do
self.uuid ||= SecureRandom.uuid if has_attribute?(:uuid)
end
def proto_payload
if has_attribute?(:payload)
payload
else
self[:proto_payload]
end
end
def proto_payload=(value)
if has_attribute?(:payload)
self.payload = value
else
self[:proto_payload] = value
end
end
def payload
if has_attribute?(:proto_payload)
proto_payload
else
self[:payload]
end
end
def payload=(value)
if has_attribute?(:proto_payload)
self.proto_payload = value
else
self[:payload] = value
end
end
def for_processing?
pending?
end
def options
options = (self[:options] || {}).symbolize_keys
options = default_options.deep_merge(extra_options).deep_merge(options)
options.symbolize_keys
end
def transports
if config.transports.empty?
raise Error, "Transports are not defined"
end
if has_attribute?(:event_name)
config.transports.fetch(event_name)
else
config.transports.fetch(:_all_)
end
end
def log_details
default_log_details.deep_merge(extra_log_details)
end
def payload_builder
nil
end
def touch_processed_at
self.processed_at = Time.current
end
def max_retries_exceeded?
self.class.max_retries_exceeded?(errors_count)
end
def increment_errors_counter
increment(:errors_count)
end
def set_errors_count(count)
self.errors_count = count
end
def add_error(ex_or_msg)
increment_errors_counter
return unless has_attribute?(:error_log)
self.error_log = "-----\n#{Time.zone.now} \n #{ex_or_msg}\n #{add_backtrace(ex_or_msg)}"
end
def partition
self.class.bucket_partitions.fetch(bucket)
end
private
def default_options
raise NotImplementedError
end
# Override in descendants
def extra_options
{}
end
def default_log_details
raise NotImplementedError
end
# Override in descendants
def extra_log_details
{}
end
def add_backtrace(ex)
return unless ex.respond_to?(:backtrace)
return if ex.backtrace.nil?
ex.backtrace.first(30).join("\n")
end
end
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/app/models/sbmt/outbox/outbox_item_config.rb | app/models/sbmt/outbox/outbox_item_config.rb | # frozen_string_literal: true
module Sbmt
module Outbox
class OutboxItemConfig < BaseItemConfig
def polling_enabled?
polling_enabled_for?(Sbmt::Outbox::Api::OutboxClass)
end
private
def lookup_config
yaml_config.dig(:outbox_items, box_name)
end
end
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/app/models/sbmt/outbox/inbox_item.rb | app/models/sbmt/outbox/inbox_item.rb | # frozen_string_literal: true
module Sbmt
module Outbox
class InboxItem < BaseItem
self.abstract_class = true
class << self
alias_method :inbox_name, :box_name
def box_type
:inbox
end
def lookup_config
Sbmt::Outbox::InboxItemConfig
end
end
delegate :inbox_name, :config, to: "self.class"
private
def default_options
{}
end
def default_log_details
{
uuid: uuid,
status: status,
created_at: created_at.to_datetime.rfc3339(6),
errors_count: errors_count
}
end
end
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/app/models/sbmt/outbox/inbox_item_config.rb | app/models/sbmt/outbox/inbox_item_config.rb | # frozen_string_literal: true
module Sbmt
module Outbox
class InboxItemConfig < BaseItemConfig
def polling_enabled?
polling_enabled_for?(Sbmt::Outbox::Api::InboxClass)
end
private
def lookup_config
yaml_config.dig(:inbox_items, box_name)
end
end
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/app/models/sbmt/outbox/base_item_config.rb | app/models/sbmt/outbox/base_item_config.rb | # frozen_string_literal: true
module Sbmt
module Outbox
class BaseItemConfig
DEFAULT_BUCKET_SIZE = 16
DEFAULT_PARTITION_STRATEGY = :number
delegate :yaml_config, :memory_store, to: "Sbmt::Outbox"
def initialize(box_id:, box_name:)
self.box_id = box_id
self.box_name = box_name
validate!
end
def owner
return @owner if defined?(@owner)
@owner = options[:owner].presence || yaml_config[:owner].presence
end
def bucket_size
@bucket_size ||= (options[:bucket_size] || yaml_config.fetch(:bucket_size, DEFAULT_BUCKET_SIZE)).to_i
end
def partition_size
@partition_size ||= (partition_size_raw || 1).to_i
end
def partition_size_raw
@partition_size_raw ||= options[:partition_size]
end
def retention
@retention ||= ActiveSupport::Duration.parse(options[:retention] || "P1W")
end
def retention_delivered_items
@retention_delivered_items ||= begin
value = options[:retention_delivered_items] || retention
value.is_a?(String) ? ActiveSupport::Duration.parse(value) : value
end
end
def deletion_batch_size
@deletion_batch_size ||= (options[:deletion_batch_size] || 1_000).to_i
end
def deletion_sleep_time
@deletion_sleep_time ||= (options[:deletion_sleep_time] || 0.5).to_f
end
def min_retention_period
@min_retention_period ||= ActiveSupport::Duration.parse(options[:min_retention_period] || "P1D")
end
def delivered_min_retention_period
@delivered_min_retention_period ||= ActiveSupport::Duration.parse(options[:delivered_min_retention_period] || "PT1H")
end
def deletion_time_window
@deletion_time_window ||= ActiveSupport::Duration.parse(options[:deletion_time_window] || "PT4H")
end
def max_retries
@max_retries ||= (options[:max_retries] || 0).to_i
end
def minimal_retry_interval
@minimal_retry_interval ||= (options[:minimal_retry_interval] || 10).to_i
end
def maximal_retry_interval
@maximal_retry_interval ||= (options[:maximal_retry_interval] || 600).to_i
end
def multiplier_retry_interval
@multiplier_retry_interval ||= (options[:multiplier_retry_interval] || 2).to_i
end
def retry_strategies
return @retry_strategies if defined?(@retry_strategies)
configured_strategies = options[:retry_strategies]
raise ConfigError, "You cannot use retry_strategies and the strict_order option at the same time." if strict_order.present? && configured_strategies.present?
strategies = if strict_order.present? && configured_strategies.nil?
[]
else
configured_strategies.presence || %w[exponential_backoff latest_available]
end
@retry_strategies ||= Array.wrap(strategies).map do |str_name|
"Sbmt::Outbox::RetryStrategies::#{str_name.camelize}".constantize
end
end
def partition_strategy
return @partition_strategy if defined?(@partition_strategy)
str_name = options.fetch(:partition_strategy, DEFAULT_PARTITION_STRATEGY).to_s
@partition_strategy = "Sbmt::Outbox::PartitionStrategies::#{str_name.camelize}Partitioning".constantize
end
def transports
return @transports if defined?(@transports)
values = options.fetch(:transports, [])
if values.is_a?(Hash)
values = values.each_with_object([]) do |(key, params), memo|
memo << params.merge!(class: key)
end
end
@transports = values.each_with_object({}) do |params, memo|
params = params.symbolize_keys
event_name = params.delete(:event_name) || :_all_
memo[event_name] ||= []
namespace = params.delete(:class)&.camelize
raise ArgumentError, "Transport name cannot be blank" if namespace.blank?
disposable = params.key?(:disposable) ? params.delete(:disposable) : Outbox.config.disposable_transports
factory = "#{namespace}::OutboxTransportFactory".safe_constantize
memo[event_name] << if factory
if disposable
->(*args) { factory.build(**params).call(*args) }
else
factory.build(**params)
end
else
klass = namespace.constantize
if disposable
->(*args) { klass.new(**params).call(*args) }
else
klass.new(**params)
end
end
end
end
def strict_order
return @strict_order if defined?(@strict_order)
@strict_order = options[:strict_order].presence
end
private
attr_accessor :box_id, :box_name
def options
@options ||= lookup_config || {}
end
def lookup_config
raise NotImplementedError
end
def validate!
raise ConfigError, "Bucket size should be greater or equal to partition size" if partition_size > bucket_size
end
def polling_auto_disabled?
return @polling_auto_disabled if defined?(@polling_auto_disabled)
@polling_auto_disabled = yaml_config.fetch(:polling_auto_disabled, false)
end
def polling_enabled_for?(api_model)
record = memory_store.fetch("sbmt/outbox/outbox_item_config/#{box_id}", expires_in: 10) do
api_model.find(box_id)
end
if record.nil?
!polling_auto_disabled?
else
record.polling_enabled?
end
end
end
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/app/models/sbmt/outbox/outbox_item.rb | app/models/sbmt/outbox/outbox_item.rb | # frozen_string_literal: true
module Sbmt
module Outbox
class OutboxItem < BaseItem
self.abstract_class = true
IDEMPOTENCY_HEADER_NAME = "Idempotency-Key"
SEQUENCE_HEADER_NAME = "Sequence-ID"
EVENT_TIME_HEADER_NAME = "Created-At"
OUTBOX_HEADER_NAME = "Outbox-Name"
DISPATCH_TIME_HEADER_NAME = "Dispatched-At"
class << self
alias_method :outbox_name, :box_name
def box_type
:outbox
end
def lookup_config
Sbmt::Outbox::OutboxItemConfig
end
end
delegate :outbox_name, :config, to: "self.class"
private
def default_options
{
headers: {
OUTBOX_HEADER_NAME => outbox_name,
IDEMPOTENCY_HEADER_NAME => uuid,
SEQUENCE_HEADER_NAME => id.to_s,
EVENT_TIME_HEADER_NAME => created_at&.to_datetime&.rfc3339(6),
DISPATCH_TIME_HEADER_NAME => Time.current.to_datetime.rfc3339(6)
}
}
end
def default_log_details
{
uuid: uuid,
status: status,
created_at: created_at.to_datetime.rfc3339(6),
errors_count: errors_count
}
end
end
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/app/models/sbmt/outbox/api/outbox_class.rb | app/models/sbmt/outbox/api/outbox_class.rb | # frozen_string_literal: true
module Sbmt
module Outbox
module Api
class OutboxClass < Api::BoxClass
end
end
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/app/models/sbmt/outbox/api/box_class.rb | app/models/sbmt/outbox/api/box_class.rb | # frozen_string_literal: true
module Sbmt
module Outbox
module Api
class BoxClass < Api::ApplicationRecord
attribute :id, :string
attribute :polling_enabled, :boolean, default: -> { !Outbox.yaml_config.fetch(:polling_auto_disabled, false) }
end
end
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/app/models/sbmt/outbox/api/application_record.rb | app/models/sbmt/outbox/api/application_record.rb | # frozen_string_literal: true
module Sbmt
module Outbox
module Api
class ApplicationRecord
include ActiveModel::Model
include ActiveModel::Attributes
delegate :redis, to: "Sbmt::Outbox"
class << self
delegate :redis, to: "Sbmt::Outbox"
def find(id)
attributes = redis.call "HGETALL", redis_key(id)
return nil if attributes.empty?
new(attributes)
end
def find_or_initialize(id, params = {})
record = find(id)
record || new(params.merge(id: id))
end
def delete(id)
redis.call "DEL", redis_key(id)
end
def attributes(*attrs)
attrs.each do |name|
attribute name
end
end
def attribute(name, type = ActiveModel::Type::Value.new, **options)
super
# Add predicate methods for boolean types
alias_method :"#{name}?", name if type == :boolean || type.is_a?(ActiveModel::Type::Boolean)
end
def redis_key(id)
"#{name}:#{id}"
end
end
def initialize(params)
super
assign_attributes(params)
end
def save
redis.call "HMSET", redis_key, attributes.to_a.flatten.map(&:to_s)
end
def destroy
self.class.delete(id)
end
def as_json(*)
attributes
end
def eql?(other)
return false unless other.is_a?(self.class)
id == other.id
end
alias_method :==, :eql?
private
def redis_key
self.class.redis_key(id)
end
end
end
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/app/models/sbmt/outbox/api/inbox_class.rb | app/models/sbmt/outbox/api/inbox_class.rb | # frozen_string_literal: true
module Sbmt
module Outbox
module Api
class InboxClass < Api::BoxClass
end
end
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/app/interactors/sbmt/outbox/create_outbox_item.rb | app/interactors/sbmt/outbox/create_outbox_item.rb | # frozen_string_literal: true
module Sbmt
module Outbox
# Classes are the same now, but they may differ,
# hence we should have separate API entrypoints
class CreateOutboxItem < Sbmt::Outbox::BaseCreateItem
end
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/app/interactors/sbmt/outbox/dry_interactor.rb | app/interactors/sbmt/outbox/dry_interactor.rb | # frozen_string_literal: true
module Sbmt
module Outbox
class DryInteractor
extend Dry::Initializer
include Dry::Monads[:result, :do, :maybe, :list, :try]
class << self
def call(*args, **kwargs)
new(*args, **kwargs).call
end
end
end
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/app/interactors/sbmt/outbox/create_outbox_batch.rb | app/interactors/sbmt/outbox/create_outbox_batch.rb | # frozen_string_literal: true
require "sbmt/outbox/metrics/utils"
# Provides ability to insert records in batches.
# It allows to have different headers, event_key and partition_by between set of attributes,
# but for predictability of metrics results better to have same headers across items
module Sbmt
module Outbox
class CreateOutboxBatch < Outbox::DryInteractor
param :item_class, reader: :private
option :batch_attributes, reader: :private
delegate :box_type, :box_name, :owner, to: :item_class
delegate :create_batch_middlewares, to: "Sbmt::Outbox"
def call
middlewares = Middleware::Builder.new(create_batch_middlewares)
middlewares.call(item_class, batch_attributes) do
attributes_to_insert = batch_attributes.map do |attributes|
event_key = attributes[:event_key]
partition_by = attributes.delete(:partition_by) || event_key
return Failure(:missing_partition_by) unless partition_by
return Failure(:missing_event_key) unless event_key
# to get default values for some attributes, including uuid
record = item_class.new(attributes)
res = item_class.config.partition_strategy
.new(partition_by, item_class.config.bucket_size)
.call
record.bucket = res.value! if res.success?
# those 2 lines needed for rails 6, as it does not set timestamps
record.created_at ||= Time.zone.now
record.updated_at ||= record.created_at
record.attributes.reject { |_, value| value.nil? }
end
inserted_items = item_class.insert_all(attributes_to_insert, returning: [:id, :bucket])
inserted_items.rows.each do |(record_id, bucket)|
partition = item_class.bucket_partitions.fetch(bucket)
track_last_stored_id(record_id, partition)
track_counter(partition)
end
Success(inserted_items.rows.map(&:first))
rescue => e
Failure(e.message)
end
end
private
def track_last_stored_id(item_id, partition)
Yabeda
.outbox
.last_stored_event_id
.set({type: box_type, name: Sbmt::Outbox::Metrics::Utils.metric_safe(box_name), owner: owner, partition: partition}, item_id)
end
def track_counter(partition)
Yabeda
.outbox
.created_counter
.increment({type: box_type, name: Sbmt::Outbox::Metrics::Utils.metric_safe(box_name), owner: owner, partition: partition}, by: 1)
end
end
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/app/interactors/sbmt/outbox/base_create_item.rb | app/interactors/sbmt/outbox/base_create_item.rb | # frozen_string_literal: true
require "sbmt/outbox/metrics/utils"
module Sbmt
module Outbox
class BaseCreateItem < Outbox::DryInteractor
param :item_class, reader: :private
option :attributes, reader: :private
option :event_key, reader: :private, optional: true, default: -> { attributes[:event_key] }
option :partition_by, reader: :private, optional: true, default: -> { attributes[:event_key] }
delegate :box_type, :box_name, :owner, to: :item_class
delegate :create_item_middlewares, to: "Sbmt::Outbox"
def call
middlewares = Middleware::Builder.new(create_item_middlewares)
middlewares.call(item_class, attributes) do
record = item_class.new(attributes)
return Failure(:missing_event_key) unless event_key
return Failure(:missing_partition_by) unless partition_by
res = item_class.config.partition_strategy
.new(partition_by, item_class.config.bucket_size)
.call
record.bucket = res.value! if res.success?
if record.save
track_last_stored_id(record.id, record.partition)
track_counter(record.partition)
Success(record)
else
Failure(record.errors)
end
end
end
private
def track_last_stored_id(item_id, partition)
Yabeda
.outbox
.last_stored_event_id
.set({type: box_type, name: Sbmt::Outbox::Metrics::Utils.metric_safe(box_name), owner: owner, partition: partition}, item_id)
end
def track_counter(partition)
Yabeda
.outbox
.created_counter
.increment({type: box_type, name: Sbmt::Outbox::Metrics::Utils.metric_safe(box_name), owner: owner, partition: partition}, by: 1)
end
end
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/app/interactors/sbmt/outbox/create_inbox_item.rb | app/interactors/sbmt/outbox/create_inbox_item.rb | # frozen_string_literal: true
module Sbmt
module Outbox
# Classes are the same now, but they may differ,
# hence we should have separate API entrypoints
class CreateInboxItem < Sbmt::Outbox::BaseCreateItem
end
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/app/interactors/sbmt/outbox/process_item.rb | app/interactors/sbmt/outbox/process_item.rb | # frozen_string_literal: true
require "sbmt/outbox/metrics/utils"
require "sbmt/outbox/v2/redis_item_meta"
module Sbmt
module Outbox
class ProcessItem < Sbmt::Outbox::DryInteractor
param :item_class, reader: :private
param :item_id, reader: :private
option :worker_version, reader: :private, optional: true, default: -> { 1 }
option :cache_ttl_sec, reader: :private, optional: true, default: -> { 5 * 60 }
option :redis, reader: :private, optional: true, default: -> {}
METRICS_COUNTERS = %i[error_counter retry_counter sent_counter fetch_error_counter discarded_counter].freeze
delegate :log_success, :log_info, :log_failure, :log_debug, to: "Sbmt::Outbox.logger"
delegate :item_process_middlewares, to: "Sbmt::Outbox"
delegate :box_type, :box_name, :owner, to: :item_class
attr_accessor :process_latency, :retry_latency
def call
log_success(
"Start processing #{box_type} item.\n" \
"Record: #{item_class.name}##{item_id}"
)
item = nil
item_class.transaction do
item = yield fetch_item_and_lock_for_update
cached_item = fetch_redis_item_meta(redis_item_key(item_id))
if cached_retries_exceeded?(cached_item)
msg = "max retries exceeded: marking item as failed based on cached data: #{cached_item}"
item.set_errors_count(cached_item.errors_count)
track_failed(msg, item)
next Failure(msg)
end
if cached_greater_errors_count?(item, cached_item)
log_failure("inconsistent item: cached_errors_count:#{cached_item.errors_count} > db_errors_count:#{item.errors_count}: setting errors_count based on cached data:#{cached_item}")
item.set_errors_count(cached_item.errors_count)
end
if item.processed_at?
self.retry_latency = Time.current - item.created_at
item.config.retry_strategies.each do |retry_strategy|
yield check_retry_strategy(item, retry_strategy)
end
else
self.process_latency = Time.current - item.created_at
end
middlewares = Middleware::Builder.new(item_process_middlewares)
payload = yield build_payload(item)
transports = yield fetch_transports(item)
middlewares.call(item) do
transports.each do |transport|
yield process_item(transport, item, payload)
end
track_successed(item)
Success(item)
end
rescue Dry::Monads::Do::Halt => e
e.result
rescue => e
track_failed(e, item)
Failure(e.message)
end
ensure
report_metrics(item)
end
# rubocop:enable Metrics/MethodLength, Metrics/AbcSize
private
def cached_retries_exceeded?(cached_item)
return false unless cached_item
item_class.max_retries_exceeded?(cached_item.errors_count)
end
def cached_greater_errors_count?(db_item, cached_item)
return false unless cached_item
cached_item.errors_count > db_item.errors_count
end
def fetch_redis_item_meta(redis_key)
return if worker_version < 2
data = redis.call("GET", redis_key)
return if data.blank?
Sbmt::Outbox::V2::RedisItemMeta.deserialize!(data)
rescue => ex
log_debug("error while fetching redis meta: #{ex.message}")
nil
end
def set_redis_item_meta(item, ex)
return if worker_version < 2
return if item.nil?
redis_key = redis_item_key(item.id)
error_msg = format_exception_error(ex, extract_cause: false)
data = Sbmt::Outbox::V2::RedisItemMeta.new(errors_count: item.errors_count, error_msg: error_msg)
redis.call("SET", redis_key, data.to_s, "EX", cache_ttl_sec)
rescue => ex
log_debug("error while fetching redis meta: #{ex.message}")
nil
end
def redis_item_key(item_id)
"#{box_type}:#{item_class.box_name}:#{item_id}"
end
def fetch_item_and_lock_for_update
item = item_class
.lock("FOR UPDATE")
.find_by(id: item_id)
unless item
track_failed("not found")
return Failure(:not_found)
end
unless item.for_processing?
log_info("already processed")
counters[:fetch_error_counter] += 1
return Failure(:already_processed)
end
Success(item)
end
def check_retry_strategy(item, retry_strategy)
result = retry_strategy.call(item)
return Success() if result.success?
case result.failure
when :skip_processing
Failure(:skip_processing)
when :discard_item
track_discarded(item)
Failure(:discard_item)
else
track_failed("retry strategy returned unknown failure: #{result.failure}")
Failure(:retry_strategy_failure)
end
end
def build_payload(item)
builder = item.payload_builder
if builder
payload = item.payload_builder.call(item)
return payload if payload.success?
track_failed("payload builder returned failure: #{payload.failure}", item)
Failure(:payload_failure)
else
Success(item.payload)
end
end
def fetch_transports(item)
transports = item.transports
return Success(transports) if transports.present?
track_failed("missing transports", item)
Failure(:missing_transports)
end
# rubocop:disable Metrics/MethodLength
def process_item(transport, item, payload)
transport_error = nil
result = item_class.transaction(requires_new: true) do
transport.call(item, payload)
rescue => e
transport_error = e
raise ActiveRecord::Rollback
end
if transport_error
track_failed(transport_error, item)
return Failure(:transport_failure)
end
case result
when Dry::Monads::Result
if result.failure?
track_failed("transport #{transport} returned failure: #{result.failure}", item)
Failure(:transport_failure)
else
Success()
end
when false
track_failed("transport #{transport} returned #{result.inspect}", item)
Failure(:transport_failure)
else
Success()
end
end
# rubocop:enable Metrics/MethodLength
def track_failed(ex_or_msg, item = nil)
log_processing_error(ex_or_msg, item)
item&.touch_processed_at
item&.add_error(ex_or_msg)
if item.nil?
report_error(ex_or_msg)
counters[:fetch_error_counter] += 1
elsif item.max_retries_exceeded?
report_error(ex_or_msg, item)
counters[:error_counter] += 1
item.failed!
else
counters[:retry_counter] += 1
item.pending!
end
rescue => e
set_redis_item_meta(item, e)
log_error_handling_error(e, item)
end
def track_successed(item)
msg = "Successfully delivered #{box_type} item.\n" \
"Record: #{item_class.name}##{item_id}.\n" \
"#{item.log_details.to_json}"
log_success(msg)
item.touch_processed_at
item.delivered!
counters[:sent_counter] += 1
end
def track_discarded(item)
msg = "Skipped and discarded #{box_type} item.\n" \
"Record: #{item_class.name}##{item_id}.\n" \
"#{item.log_details.to_json}"
log_success(msg)
item.touch_processed_at
item.discarded!
counters[:discarded_counter] += 1
end
def log_processing_error(ex_or_msg, item = nil)
text = format_exception_error(ex_or_msg)
msg = "Failed processing #{box_type} item with error: #{text}.\n" \
"Record: #{item_class.name}##{item_id}.\n" \
"#{item&.log_details&.to_json}"
log_failure(msg, stacktrace: format_backtrace(ex_or_msg))
end
def log_error_handling_error(handling_error, item = nil)
text = format_exception_error(handling_error, extract_cause: false)
msg = "Could not persist status of failed #{box_type} item due to error: #{text}.\n" \
"Record: #{item_class.name}##{item_id}.\n" \
"#{item&.log_details&.to_json}"
log_failure(msg, stacktrace: format_backtrace(handling_error))
end
def format_exception_error(e, extract_cause: true)
text = if extract_cause && e.respond_to?(:cause) && !e.cause.nil?
"#{format_exception_error(e.cause)}. "
else
""
end
if e.respond_to?(:message)
"#{text}#{e.class.name} #{e.message}"
else
"#{text}#{e}"
end
end
def format_backtrace(e)
if e.respond_to?(:backtrace) && !e.backtrace.nil?
e.backtrace.join("\n")
end
end
def report_error(ex_or_msg, item = nil)
Outbox.error_tracker.error(
ex_or_msg,
box_name: item_class.box_name,
item_class: item_class.name,
item_id: item_id,
item_details: item&.log_details&.to_json
)
end
def report_metrics(item)
labels = labels_for(item)
METRICS_COUNTERS.each do |counter_name|
Yabeda
.outbox
.send(counter_name)
.increment(labels, by: counters[counter_name])
end
track_process_latency(labels) if process_latency
track_retry_latency(labels) if retry_latency
return unless counters[:sent_counter].positive?
Yabeda
.outbox
.last_sent_event_id
.set(labels, item_id)
end
def labels_for(item)
{worker_version: worker_version, type: box_type, name: Sbmt::Outbox::Metrics::Utils.metric_safe(box_name), owner: owner, partition: item&.partition}
end
def counters
@counters ||= Hash.new(0)
end
def track_process_latency(labels)
Yabeda.outbox.process_latency.measure(labels, process_latency.round(3))
end
def track_retry_latency(labels)
Yabeda.outbox.retry_latency.measure(labels, retry_latency.round(3))
end
end
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/app/interactors/sbmt/outbox/retry_strategies/latest_available.rb | app/interactors/sbmt/outbox/retry_strategies/latest_available.rb | # frozen_string_literal: true
module Sbmt
module Outbox
module RetryStrategies
class LatestAvailable < Base
def call
unless item.has_attribute?(:event_key)
return Failure(:missing_event_key)
end
if item.event_key.nil?
return Failure(:empty_event_key)
end
if delivered_later?
Failure(:discard_item)
else
Success()
end
end
private
def delivered_later?
scope = item.class
.where("id > ?", item)
.where(event_key: item.event_key)
if item.has_attribute?(:event_name) && item.event_name.present?
scope = scope.where(event_name: item.event_name)
end
scope.exists?
end
end
end
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/app/interactors/sbmt/outbox/retry_strategies/compacted_log.rb | app/interactors/sbmt/outbox/retry_strategies/compacted_log.rb | # frozen_string_literal: true
module Sbmt
module Outbox
module RetryStrategies
class CompactedLog < LatestAvailable
# exists only as alias for backward compatibility
end
end
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/app/interactors/sbmt/outbox/retry_strategies/no_delay.rb | app/interactors/sbmt/outbox/retry_strategies/no_delay.rb | # frozen_string_literal: true
module Sbmt
module Outbox
module RetryStrategies
class NoDelay < Base
def call
Success()
end
end
end
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/app/interactors/sbmt/outbox/retry_strategies/base.rb | app/interactors/sbmt/outbox/retry_strategies/base.rb | # frozen_string_literal: true
module Sbmt
module Outbox
module RetryStrategies
class Base < Outbox::DryInteractor
param :item
def call
raise NotImplementedError, "Implement #call for Sbmt::Outbox::RetryStrategies::Base"
end
end
end
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/app/interactors/sbmt/outbox/retry_strategies/exponential_backoff.rb | app/interactors/sbmt/outbox/retry_strategies/exponential_backoff.rb | # frozen_string_literal: true
module Sbmt
module Outbox
module RetryStrategies
class ExponentialBackoff < Base
def call
delay = backoff(item.config).interval_at(item.errors_count - 1)
still_early = item.processed_at + delay.seconds > Time.current
if still_early
Failure(:skip_processing)
else
Success()
end
end
private
def backoff(config)
@backoff ||= ::ExponentialBackoff.new([
config.minimal_retry_interval,
config.maximal_retry_interval
]).tap do |x|
x.multiplier = config.multiplier_retry_interval
end
end
end
end
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/app/interactors/sbmt/outbox/partition_strategies/number_partitioning.rb | app/interactors/sbmt/outbox/partition_strategies/number_partitioning.rb | # frozen_string_literal: true
module Sbmt
module Outbox
module PartitionStrategies
class NumberPartitioning < Outbox::DryInteractor
param :key
param :bucket_size
def call
parsed_key =
case key
when Integer
key
else
key.delete("^0-9").to_i
end
Success(
parsed_key % bucket_size
)
end
end
end
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/app/interactors/sbmt/outbox/partition_strategies/hash_partitioning.rb | app/interactors/sbmt/outbox/partition_strategies/hash_partitioning.rb | # frozen_string_literal: true
require "digest/sha1"
module Sbmt
module Outbox
module PartitionStrategies
class HashPartitioning < Outbox::DryInteractor
param :key
param :bucket_size
def call
Success(
Digest::SHA1.hexdigest(key.to_s).to_i(16) % bucket_size
)
end
end
end
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/spec/rails_helper.rb | spec/rails_helper.rb | # frozen_string_literal: true
# Engine root is used by rails_configuration to correctly
# load fixtures and support files
require "pathname"
ENGINE_ROOT = Pathname.new(File.expand_path("..", __dir__))
ENV["RAILS_ENV"] = "test"
require "combustion"
begin
Combustion.initialize! :active_record, :active_job, :action_controller do
if ENV["LOG"].to_s.empty?
config.logger = ActiveSupport::TaggedLogging.new(Logger.new(nil))
config.log_level = :fatal
else
config.logger = ActiveSupport::TaggedLogging.new(Logger.new($stdout))
config.log_level = :debug
end
config.active_record.logger = config.logger
config.i18n.available_locales = [:ru, :en]
config.i18n.default_locale = :ru
config.active_job.queue_adapter = :test
end
rescue => e
# Fail fast if application couldn't be loaded
if e.message.include?("Unknown database")
warn "💥 Database must be reseted by passing env variable `DB_RESET=1`"
else
warn "💥 Failed to load the app: #{e.message}\n#{e.backtrace.join("\n")}"
end
exit(1)
end
Rails.application.load_tasks
ActiveRecord::Base.logger = Rails.logger
require "rspec/rails"
# Add additional requires below this line. Rails is not loaded until this point!
require "factory_bot"
require "yabeda/rspec"
RSpec::Matchers.define_negated_matcher :not_increment_yabeda_counter, :increment_yabeda_counter
RSpec::Matchers.define_negated_matcher :not_update_yabeda_gauge, :update_yabeda_gauge
RSpec::Matchers.define_negated_matcher :not_measure_yabeda_histogram, :measure_yabeda_histogram
RSpec::Matchers.define_negated_matcher :not_change, :change
require "sbmt/outbox/instrumentation/open_telemetry_loader"
Dir[Sbmt::Outbox::Engine.root.join("spec/support/**/*.rb")].sort.each { |f| require f }
Dir[Sbmt::Outbox::Engine.root.join("spec/factories/**/*.rb")].sort.each { |f| require f }
RSpec.configure do |config|
config.include FactoryBot::Syntax::Methods
config.include ActiveSupport::Testing::TimeHelpers
config.use_transactional_fixtures = true
config.infer_spec_type_from_file_location!
config.filter_rails_from_backtrace!
redis = RedisClient.new(url: ENV["REDIS_URL"])
config.before do
redis.call("FLUSHDB")
Sbmt::Outbox.memory_store.clear
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/spec/spec_helper.rb | spec/spec_helper.rb | # frozen_string_literal: true
ENV["RAILS_ENV"] = "test"
require "bundler/setup"
require "rspec"
require "rspec_junit_formatter"
RSpec.configure do |config|
config.expect_with :rspec do |expectations|
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
config.mock_with :rspec do |mocks|
mocks.verify_partial_doubles = true
end
config.filter_run_when_matching :focus
config.example_status_persistence_file_path = "tmp/rspec_examples.txt"
config.run_all_when_everything_filtered = true
if config.files_to_run.one?
# Use the documentation formatter for detailed output,
# unless a formatter has already been configured
# (e.g. via a command-line flag).
config.default_formatter = "doc"
end
config.order = :random
Kernel.srand config.seed
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/spec/jobs/sbmt/outbox/delete_stale_outbox_items_job_spec.rb | spec/jobs/sbmt/outbox/delete_stale_outbox_items_job_spec.rb | # frozen_string_literal: true
describe Sbmt::Outbox::DeleteStaleOutboxItemsJob do
it { expect(described_class.item_classes).to eq [OutboxItem, Combined::OutboxItem] }
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/spec/jobs/sbmt/outbox/delete_stale_inbox_items_job_spec.rb | spec/jobs/sbmt/outbox/delete_stale_inbox_items_job_spec.rb | # frozen_string_literal: true
describe Sbmt::Outbox::DeleteStaleInboxItemsJob do
it { expect(described_class.item_classes).to eq [InboxItem] }
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/spec/jobs/sbmt/outbox/base_delete_stale_items_job_spec.rb | spec/jobs/sbmt/outbox/base_delete_stale_items_job_spec.rb | # frozen_string_literal: true
describe Sbmt::Outbox::BaseDeleteStaleItemsJob do
let(:job_class) do
Class.new(described_class) do
class << self
def item_classes
[OutboxItem]
end
end
end
end
let!(:item_delivered) { create(:outbox_item, created_at: created_at, status: :delivered) }
let!(:item_failed) { create(:outbox_item, created_at: created_at, status: :failed) }
let(:created_at) { 1.month.ago }
describe ".enqueue" do
it "enqueue all item classes" do
expect { job_class.enqueue }.to have_enqueued_job(job_class).with("OutboxItem")
end
end
describe "#perform" do
context "when all items exceed retention periods" do
it "deletes items and tracks metrics" do
expect { job_class.perform_now("OutboxItem") }
.to change(OutboxItem, :count).by(-2)
.and increment_yabeda_counter(Yabeda.outbox.deleted_counter).with_tags(box_name: "outbox_item", box_type: :outbox).by(2)
.and measure_yabeda_histogram(Yabeda.outbox.delete_latency).with_tags(box_name: "outbox_item", box_type: :outbox)
end
end
context "when items do not exceed the minimum retention period" do
let(:created_at) { 6.hours.ago }
it "does not delete items below the retention period but deletes others and tracks metrics" do
expect { job_class.perform_now("OutboxItem") }
.to change(OutboxItem, :count).by(-1)
.and increment_yabeda_counter(Yabeda.outbox.deleted_counter).with_tags(box_name: "outbox_item", box_type: :outbox).by(1)
.and measure_yabeda_histogram(Yabeda.outbox.delete_latency).with_tags(box_name: "outbox_item", box_type: :outbox)
end
end
context "when retention period is invalid" do
before do
allow(OutboxItem.config).to receive_messages(retention: 6.hours, min_retention_period: 1.day)
end
it "raises an error" do
expect { job_class.perform_now("OutboxItem") }
.to raise_error("Retention period for outbox_item must be longer than 1 day")
end
end
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/spec/services/sbmt/outbox/retry_strategies/exponential_backoff_spec.rb | spec/services/sbmt/outbox/retry_strategies/exponential_backoff_spec.rb | # frozen_string_literal: true
describe Sbmt::Outbox::RetryStrategies::ExponentialBackoff do
subject(:result) { described_class.call(outbox_item) }
let(:outbox_item) { create(:outbox_item, processed_at: processed_at) }
let(:processed_at) { Time.zone.now }
context "when the next processing time is greater than the current time" do
it "skips processing" do
expect(result).to be_failure
expect(result.failure).to eq :skip_processing
end
end
context "when the next processing time is less than the current time" do
let(:processed_at) { 1.hour.ago }
it "allows processing" do
expect(result).to be_success
end
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/spec/factories/outbox_item_factory.rb | spec/factories/outbox_item_factory.rb | # frozen_string_literal: true
FactoryBot.define do
factory :outbox_item, class: "OutboxItem" do
payload { "test" }
sequence(:event_key)
bucket { 0 }
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/spec/factories/combined_outbox_item_factory.rb | spec/factories/combined_outbox_item_factory.rb | # frozen_string_literal: true
FactoryBot.define do
factory :combined_outbox_item, class: "Combined::OutboxItem" do
payload { "test" }
event_name { "order_created" }
sequence(:event_key)
bucket { 0 }
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/spec/factories/inbox_item_factory.rb | spec/factories/inbox_item_factory.rb | # frozen_string_literal: true
FactoryBot.define do
factory :inbox_item, class: "InboxItem" do
payload { "test" }
sequence(:event_key)
bucket { 0 }
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/spec/controllers/sbmt/outbox/api/inbox_classes_controller_spec.rb | spec/controllers/sbmt/outbox/api/inbox_classes_controller_spec.rb | # frozen_string_literal: true
describe Sbmt::Outbox::Api::InboxClassesController do
routes { Sbmt::Outbox::Engine.routes }
let(:box_id) { InboxItem.box_name }
describe "#index" do
it "returns raw inbox items" do
get :index
expect(response).to be_successful
data = response.parsed_body
expect(data).not_to be_empty
expect(data.pluck("id")).to include("inbox-item")
end
end
describe "#show" do
it "represents inbox item" do
get :show, params: {id: box_id}
expect(response).to be_successful
expect(response.parsed_body["id"]).to eq box_id
end
end
describe "#update" do
it "updates API config for inbox item" do
put :update, params: {id: box_id, inbox_class: {polling_enabled: "false"}}
expect(response).to be_successful
expect(response.parsed_body["id"]).to eq box_id
expect(response.parsed_body["polling_enabled"]).to be false
end
end
describe "#destroy" do
it "deletes API config for inbox item" do
delete :destroy, params: {id: box_id}
expect(response).to be_successful
end
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/spec/controllers/sbmt/outbox/api/outbox_classes_controller_spec.rb | spec/controllers/sbmt/outbox/api/outbox_classes_controller_spec.rb | # frozen_string_literal: true
describe Sbmt::Outbox::Api::OutboxClassesController do
routes { Sbmt::Outbox::Engine.routes }
let(:box_id) { OutboxItem.box_name }
describe "#index" do
it "returns raw outbox items" do
get :index
expect(response).to be_successful
data = response.parsed_body
expect(data).not_to be_empty
expect(data.pluck("id")).to include("outbox-item", "combined-outbox-item")
end
end
describe "#show" do
it "represents outbox item" do
get :show, params: {id: box_id}
expect(response).to be_successful
expect(response.parsed_body["id"]).to eq box_id
end
end
describe "#update" do
it "updates API config for outbox item" do
put :update, params: {id: box_id, outbox_class: {polling_enabled: "false"}}
expect(response).to be_successful
expect(response.parsed_body["id"]).to eq box_id
expect(response.parsed_body["polling_enabled"]).to be false
end
end
describe "#destroy" do
it "deletes API config for outbox item" do
delete :destroy, params: {id: box_id}
expect(response).to be_successful
end
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/spec/models/sbmt/outbox/base_item_spec.rb | spec/models/sbmt/outbox/base_item_spec.rb | # frozen_string_literal: true
describe Sbmt::Outbox::BaseItem do
describe "#max_retries_exceeded?" do
let(:outbox_item) { create(:outbox_item) }
before do
allow(outbox_item.config).to receive(:max_retries).and_return(1)
end
it "has available retries" do
expect(outbox_item).not_to be_max_retries_exceeded
end
context "when item was retried" do
let(:outbox_item) { create(:outbox_item, errors_count: 2) }
it "has not available retries" do
expect(outbox_item).to be_max_retries_exceeded
end
end
context "when strict order is enabled" do
before do
allow(outbox_item.config).to receive(:strict_order).and_return(true)
end
it "does not consider retries when strict order is enabled" do
expect(outbox_item).not_to be_max_retries_exceeded
end
end
end
describe "#retry_strategies" do
let(:outbox_item) { create(:combined_outbox_item) }
let(:config) { Sbmt::Outbox::OutboxItemConfig.new(box_id: Combined::OutboxItem.box_id, box_name: Combined::OutboxItem.box_name) }
before { allow(outbox_item).to receive(:config).and_return(config) }
context "when retry_strategies are not configured" do
it "uses default retry strategies" do
expect(outbox_item.config.retry_strategies).to eq([
Sbmt::Outbox::RetryStrategies::ExponentialBackoff,
Sbmt::Outbox::RetryStrategies::LatestAvailable
])
end
end
context "when both retry_strategies and strict_order are present" do
before do
allow(outbox_item.config).to receive_messages(strict_order: true, options: {retry_strategies: ["exponential_backoff"]})
end
it "raises a ConfigError" do
expect { outbox_item.config.retry_strategies }.to raise_error(Sbmt::Outbox::ConfigError, "You cannot use retry_strategies and the strict_order option at the same time.")
end
end
context "when only strict_order is configured without retry_strategies" do
before do
allow(outbox_item.config).to receive_messages(strict_order: true, options: {})
end
it "retry strategies are not used" do
expect(outbox_item.config.retry_strategies).to eq([])
end
end
end
describe "#options" do
let(:outbox_item) { create(:outbox_item) }
let(:dispatched_at_header_name) { Sbmt::Outbox::OutboxItem::DISPATCH_TIME_HEADER_NAME }
it "returns valid options" do
def outbox_item.extra_options
{
foo: true,
bar: true
}
end
outbox_item.options = {bar: false}
expect(outbox_item.options).to include(:headers, :foo, :bar)
expect(outbox_item.options[:bar]).to be false
end
it "has 'Dispatched-At' header" do
expect(outbox_item.options[:headers].has_key?(dispatched_at_header_name)).to be(true)
end
end
describe "#add_error" do
let(:outbox_item) { create(:outbox_item) }
it "saves exception message to record" do
error = StandardError.new("test-error")
outbox_item.add_error(error)
outbox_item.save!
outbox_item.reload
expect(outbox_item.error_log).to include("test-error")
expect(outbox_item.errors_count).to eq(1)
error = StandardError.new("another-error")
outbox_item.add_error(error)
outbox_item.save!
outbox_item.reload
expect(outbox_item.error_log).to include("another-error")
expect(outbox_item.error_log).not_to include("test-error")
expect(outbox_item.errors_count).to eq(2)
end
end
describe "#partition" do
let(:outbox_item) { build(:outbox_item, bucket: 3) }
it "returns valid partition" do
expect(outbox_item.partition).to eq 1
end
end
describe ".partition_buckets" do
it "returns buckets of partitions" do
expect(OutboxItem.partition_buckets).to eq(0 => [0, 2], 1 => [1, 3])
end
context "when the number of partitions is not a multiple of the number of buckets" do
before do
if OutboxItem.instance_variable_defined?(:@partition_buckets)
OutboxItem.remove_instance_variable(:@partition_buckets)
end
allow(OutboxItem.config).to receive_messages(partition_size: 2, bucket_size: 5)
end
after do
OutboxItem.remove_instance_variable(:@partition_buckets)
end
it "returns buckets of partitions" do
expect(OutboxItem.partition_buckets).to eq(0 => [0, 2, 4], 1 => [1, 3])
end
end
end
describe ".bucket_partitions" do
it "returns buckets of partitions" do
expect(OutboxItem.bucket_partitions).to eq(0 => 0, 1 => 1, 2 => 0, 3 => 1)
end
end
describe "#transports" do
context "when transport was built by factory" do
let(:outbox_item) { build(:outbox_item) }
it "returns disposable transport" do
# init transports for the first time
outbox_item.transports
transport = instance_double(Producer)
expect(Producer)
.to receive(:new)
.with(topic: "outbox_item_topic", kafka: {"required_acks" => -1}).and_return(transport)
expect(transport).to receive(:call)
expect(outbox_item.transports.size).to eq 1
outbox_item.transports.first.call(outbox_item, "payload")
end
end
context "when transport was built by name" do
let(:inbox_item) { build(:inbox_item) }
it "returns valid transports" do
# init transports for the first time
inbox_item.transports
expect(ImportOrder).not_to receive(:new)
expect(inbox_item.transports.first).to be_a(ImportOrder)
expect(inbox_item.transports.first.source).to eq "kafka_consumer"
inbox_item.transports.first.call(inbox_item, "payload")
end
end
context "when transports were selected by event name" do
let(:outbox_item) { build(:combined_outbox_item, event_name: "orders_completed") }
it "returns disposable transport" do
# init transports for the first time
outbox_item.transports
transport = instance_double(Producer)
expect(Producer)
.to receive(:new)
.with(topic: "orders_completed_topic", kafka: {}).and_return(transport)
expect(transport).to receive(:call)
expect(outbox_item.transports.size).to eq 1
outbox_item.transports.first.call(outbox_item, "payload")
end
end
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/spec/models/sbmt/outbox/inbox_item_config_spec.rb | spec/models/sbmt/outbox/inbox_item_config_spec.rb | # frozen_string_literal: true
describe Sbmt::Outbox::InboxItemConfig do
let(:config) { InboxItem.config }
describe "polling auto enabled by default" do
it { expect(config.polling_enabled?).to be true }
end
context "when polling is disabled" do
before { Sbmt::Outbox::Api::InboxClass.new(id: InboxItem.box_id, polling_enabled: false).save }
it { expect(config.polling_enabled?).to be false }
end
context "when polling is auto disabled" do
before { allow(config).to receive(:polling_auto_disabled?).and_return(true) }
it { expect(config.polling_enabled?).to be false }
context "when polling is enabled on the box" do
before { Sbmt::Outbox::Api::InboxClass.new(id: InboxItem.box_id, polling_enabled: true).save }
it { expect(config.polling_enabled?).to be true }
end
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/spec/models/sbmt/outbox/outbox_item_config_spec.rb | spec/models/sbmt/outbox/outbox_item_config_spec.rb | # frozen_string_literal: true
describe Sbmt::Outbox::OutboxItemConfig do
let(:config) { OutboxItem.config }
describe "polling auto enabled by default" do
it { expect(config.polling_enabled?).to be true }
end
context "when polling is disabled" do
before { Sbmt::Outbox::Api::OutboxClass.new(id: OutboxItem.box_id, polling_enabled: false).save }
it { expect(config.polling_enabled?).to be false }
end
context "when polling is auto disabled" do
before { allow(config).to receive(:polling_auto_disabled?).and_return(true) }
it { expect(config.polling_enabled?).to be false }
context "when polling is enabled on the box" do
before { Sbmt::Outbox::Api::OutboxClass.new(id: OutboxItem.box_id, polling_enabled: true).save }
it { expect(config.polling_enabled?).to be true }
end
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/spec/models/sbmt/outbox/api/application_record_spec.rb | spec/models/sbmt/outbox/api/application_record_spec.rb | # frozen_string_literal: true
describe Sbmt::Outbox::Api::ApplicationRecord do
let(:model) do
Class.new(described_class) do
attribute :id, :integer
end
end
describe ".find" do
context "when record exists" do
let!(:record) { model.new(id: 14).tap(&:save) }
it { expect(model.find(14)).to eq record }
end
context "when no record" do
it { expect(model.find(14)).to be_nil }
end
end
describe ".find_or_initialize" do
context "when record exists" do
let!(:record) { model.new(id: 14).tap(&:save) }
it { expect(model.find_or_initialize(14, id: 14)).to eq record }
end
context "when no record" do
it { expect(model.find_or_initialize(14, id: 14)).to have_attributes(id: 14) }
end
end
describe ".delete" do
context "when record exists" do
let!(:record) { model.new(id: 14).tap(&:save) }
before { model.delete(14) }
it { expect(model.find(14)).to be_nil }
end
context "when no record" do
it { expect(model.delete(14)).to be_zero }
end
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/spec/interactors/sbmt/outbox/process_item_spec.rb | spec/interactors/sbmt/outbox/process_item_spec.rb | # frozen_string_literal: true
require "ostruct"
describe Sbmt::Outbox::ProcessItem do
describe "#call" do
subject(:result) { described_class.call(OutboxItem, outbox_item.id, worker_version: worker_version, redis: redis) }
let(:redis) { nil }
let(:worker_version) { 1 }
let(:max_retries) { 0 }
let(:producer) { instance_double(Producer, call: true) }
let(:dummy_middleware_class) { instance_double(Class, new: dummy_middleware) }
let(:dummy_middleware) { ->(*_args, &b) { b.call } }
before do
allow(Producer).to receive(:new).and_return(producer)
allow_any_instance_of(Sbmt::Outbox::OutboxItemConfig).to receive(:max_retries).and_return(max_retries)
allow(Sbmt::Outbox).to receive(:item_process_middlewares).and_return([dummy_middleware_class])
allow(dummy_middleware).to receive(:call).and_call_original
end
context "when outbox item is not found in db" do
let(:outbox_item) { OpenStruct.new(id: 1, options: {}) }
it "returns error" do
expect(Sbmt::Outbox.error_tracker).to receive(:error)
expect(Sbmt::Outbox.logger).to receive(:log_failure)
.with(/Failed processing outbox item with error: not found/, stacktrace: nil)
expect(result).not_to be_success
expect(dummy_middleware).not_to have_received(:call)
expect(result.failure).to eq :not_found
end
it "tracks Yabeda error counter" do
expect { result }.to increment_yabeda_counter(Yabeda.outbox.fetch_error_counter).by(1)
end
end
context "when outbox item is being processed concurrently" do
let(:outbox_item) { create(:outbox_item) }
let(:error_msg) { "Mysql2::Error::TimeoutError: Lock wait timeout exceeded; try restarting transaction" }
before do
allow(OutboxItem).to receive(:lock).and_raise(
ActiveRecord::LockWaitTimeout.new(error_msg)
)
end
it "logs failure" do
expect(Sbmt::Outbox.error_tracker).to receive(:error)
allow(Sbmt::Outbox.logger).to receive(:log_failure)
expect(result.failure).to eq(error_msg)
expect(Sbmt::Outbox.logger)
.to have_received(:log_failure)
.with(/#{error_msg}/, stacktrace: kind_of(String))
end
it "does not call middleware" do
result
expect(dummy_middleware).not_to have_received(:call)
end
it "tracks Yabeda error counter" do
expect { result }.to increment_yabeda_counter(Yabeda.outbox.fetch_error_counter).by(1)
end
end
context "when there is cached item data" do
let(:redis) { RedisClient.new(url: ENV["REDIS_URL"]) }
let(:cached_errors_count) { 99 }
let(:db_errors_count) { 1 }
let(:max_retries) { 7 }
before do
data = Sbmt::Outbox::V2::RedisItemMeta.new(errors_count: cached_errors_count, error_msg: "Some error")
redis.call("SET", "outbox:outbox_item:#{outbox_item.id}", data.to_s)
allow_any_instance_of(Sbmt::Outbox::OutboxItemConfig).to receive(:max_retries).and_return(max_retries)
end
context "when worker_version is 1" do
let(:outbox_item) { create(:outbox_item) }
let(:worker_version) { 1 }
it "does not use cached data" do
expect { result }.not_to change { outbox_item.reload.errors_count }
end
end
context "when worker_version is 2" do
let(:outbox_item) { create(:outbox_item, errors_count: db_errors_count) }
let(:worker_version) { 2 }
before do
allow(Sbmt::Outbox.logger).to receive(:log_failure)
end
context "when cached errors_count exceed max retries" do
it "increments cached errors count and marks items as failed" do
expect(Sbmt::Outbox.logger).to receive(:log_failure).with(/max retries exceeded: marking item as failed based on cached data/, any_args)
expect { result }
.to change { outbox_item.reload.errors_count }.from(1).to(100)
.and change { outbox_item.reload.status }.from("pending").to("failed")
end
end
context "when cached errors_count is greater" do
let(:cached_errors_count) { 2 }
it "sets errors_count based on cached data" do
expect(Sbmt::Outbox.logger).to receive(:log_failure).with(/inconsistent item: cached_errors_count:2 > db_errors_count:1: setting errors_count based on cached data/, any_args)
expect { result }
.to change { outbox_item.reload.errors_count }.from(1).to(2)
.and change { outbox_item.reload.status }.from("pending").to("delivered")
end
end
context "when cached errors_count is less" do
let(:cached_errors_count) { 0 }
it "sets errors_count based on db data" do
expect { result }
.to not_change { outbox_item.reload.errors_count }
.and change { outbox_item.reload.status }.from("pending").to("delivered")
end
end
end
end
context "when outbox item is not in pending state" do
let(:outbox_item) do
create(
:outbox_item,
status: Sbmt::Outbox::BaseItem.statuses[:failed]
)
end
it "doesn't report error" do
expect(Sbmt::Outbox.error_tracker).not_to receive(:error)
allow(Sbmt::Outbox.logger).to receive(:log_info)
expect(result).not_to be_success
expect(Sbmt::Outbox.logger).to have_received(:log_info).with("already processed")
expect(dummy_middleware).not_to have_received(:call)
expect(result.failure).to eq :already_processed
end
end
context "when there is no any transport" do
let!(:outbox_item) { create(:outbox_item) }
before do
allow_any_instance_of(OutboxItem).to receive(:transports).and_return(nil)
end
it "returns error" do
expect(result).not_to be_success
end
it "changes status to failed" do
result
expect(outbox_item.reload).to be_failed
end
it "does not call middleware" do
result
expect(dummy_middleware).not_to have_received(:call)
end
it "tracks error" do
expect(Sbmt::Outbox.error_tracker).to receive(:error)
expect(Sbmt::Outbox.logger).to receive(:log_failure)
expect(result.failure).to eq :missing_transports
end
it "does not remove outbox item" do
expect { result }.not_to change(OutboxItem, :count)
end
end
context "when outbox item produce to transport successfully" do
let!(:outbox_item) { create(:outbox_item) }
it "returns success" do
expect(Sbmt::Outbox.error_tracker).not_to receive(:error)
allow(Sbmt::Outbox.logger).to receive(:log_success)
expect(Sbmt::Outbox.logger).to receive(:log_success).with(/delivered/, any_args)
expect(result).to be_success
expect(dummy_middleware).to have_received(:call).with(outbox_item)
expect(outbox_item.reload).to be_delivered
end
it "tracks Yabeda sent counter and last_sent_event_id and process_latency" do
expect { result }.to increment_yabeda_counter(Yabeda.outbox.sent_counter).by(1)
.and update_yabeda_gauge(Yabeda.outbox.last_sent_event_id)
.and measure_yabeda_histogram(Yabeda.outbox.process_latency)
end
end
context "when combined outbox item produce to transport successfully" do
let!(:outbox_item) { create(:combined_outbox_item) }
it "tracks Yabeda sent counter and last_sent_event_id and process_latency with proper box name" do
expect { described_class.call(Combined::OutboxItem, outbox_item.id) }
.to increment_yabeda_counter(Yabeda.outbox.sent_counter).with_tags(name: "combined-outbox_item", owner: nil, partition: 0, type: :outbox, worker_version: 1).by(1)
.and update_yabeda_gauge(Yabeda.outbox.last_sent_event_id).with_tags(name: "combined-outbox_item", owner: nil, partition: 0, type: :outbox, worker_version: 1)
.and measure_yabeda_histogram(Yabeda.outbox.process_latency).with_tags(name: "combined-outbox_item", owner: nil, partition: 0, type: :outbox, worker_version: 1)
end
end
context "when outbox item produce to transport unsuccessfully" do
let!(:outbox_item) { create(:outbox_item) }
before do
allow(producer).to receive(:call).and_return(false)
end
it "returns error" do
expect(result).not_to be_success
end
it "changes status to failed" do
result
expect(outbox_item.reload).to be_failed
end
it "calls middleware" do
result
expect(dummy_middleware).to have_received(:call).with(outbox_item)
end
it "tracks error" do
expect(Sbmt::Outbox.error_tracker).to receive(:error)
expect(Sbmt::Outbox.logger).to receive(:log_failure)
expect(result.failure).to eq :transport_failure
end
it "does not remove outbox item" do
expect { result }.not_to change(OutboxItem, :count)
end
it "tracks Yabeda error counter" do
expect { result }.to increment_yabeda_counter(Yabeda.outbox.error_counter).by(1)
end
context "when has one retry available" do
let(:max_retries) { 1 }
it "doesn't change status to failed" do
expect(Sbmt::Outbox.error_tracker).not_to receive(:error)
expect(Sbmt::Outbox.logger).to receive(:log_failure)
result
expect(dummy_middleware).to have_received(:call).with(outbox_item)
expect(outbox_item.reload).to be_pending
expect(outbox_item.errors_count).to eq 1
end
it "tracks Yabeda retry counter" do
expect { result }.to increment_yabeda_counter(Yabeda.outbox.retry_counter).by(1)
end
end
context "when retry process" do
let!(:outbox_item) { create(:outbox_item, processed_at: Time.current) }
it "doesn't track process_latency" do
expect { result }.to measure_yabeda_histogram(Yabeda.outbox.retry_latency)
.and not_measure_yabeda_histogram(Yabeda.outbox.process_latency)
end
end
end
context "when item processing raised exception" do
let!(:outbox_item) { create(:outbox_item) }
before do
allow(producer).to receive(:call).and_raise("boom")
end
it "returns error" do
expect(result).to be_failure
end
it "changes status to failed" do
result
expect(outbox_item.reload).to be_failed
end
it "calls middleware" do
result
expect(dummy_middleware).to have_received(:call).with(outbox_item)
end
it "tracks error" do
expect(Sbmt::Outbox.error_tracker).to receive(:error)
expect(Sbmt::Outbox.logger).to receive(:log_failure)
.with(/Failed processing outbox item with error: RuntimeError boom/, stacktrace: kind_of(String))
expect(result.failure).to eq :transport_failure
end
it "does not remove outbox item" do
expect { result }.not_to change(OutboxItem, :count)
end
it "tracks Yabeda error counter" do
expect { result }.to increment_yabeda_counter(Yabeda.outbox.error_counter).by(1)
end
context "when error persisting fails" do
let(:redis) { RedisClient.new(url: ENV["REDIS_URL"]) }
before do
allow_any_instance_of(OutboxItem).to receive(:failed!).and_raise("boom")
end
it "returns error" do
expect(result).to be_failure
end
it "logs failure" do
expect(Sbmt::Outbox.error_tracker).to receive(:error)
allow(Sbmt::Outbox.logger).to receive(:log_failure)
expect(result.failure).to eq :transport_failure
expect(Sbmt::Outbox.logger)
.to have_received(:log_failure)
.with(/Could not persist status of failed outbox item due to error: RuntimeError boom/, stacktrace: kind_of(String))
end
it "calls middleware" do
result
expect(dummy_middleware).to have_received(:call).with(outbox_item)
end
it "tracks Yabeda error counter" do
expect { result }.to increment_yabeda_counter(Yabeda.outbox.error_counter).by(1)
end
context "when worker_version is 1" do
let(:worker_version) { 1 }
it "skips item state caching" do
result
data = redis.call("GET", "outbox:outbox_item:#{outbox_item.id}")
expect(data).to be_nil
end
end
context "when worker_version is 2" do
let(:worker_version) { 2 }
context "when there is no cached item state" do
it "caches item state in redis" do
result
data = redis.call("GET", "outbox:outbox_item:#{outbox_item.id}")
deserialized = JSON.parse(data)
expect(deserialized["timestamp"]).to be_an_integer
expect(deserialized).to include(
"error_msg" => "RuntimeError boom",
"errors_count" => 1,
"version" => 1
)
end
it "sets ttl for item state data" do
result
res = redis.call("EXPIRETIME", "outbox:outbox_item:#{outbox_item.id}")
expect(res).to be > 0
end
end
context "when there is cached item state with greater errors_count" do
before do
data = Sbmt::Outbox::V2::RedisItemMeta.new(errors_count: 2, error_msg: "Some previous error")
redis.call("SET", "outbox:outbox_item:#{outbox_item.id}", data.to_s)
end
it "caches item state in redis based on cached errors_count" do
result
data = redis.call("GET", "outbox:outbox_item:#{outbox_item.id}")
deserialized = JSON.parse(data)
expect(deserialized["timestamp"]).to be_an_integer
expect(deserialized).to include(
"error_msg" => "RuntimeError boom",
"errors_count" => 3,
"version" => 1
)
end
it "sets ttl for item state data" do
result
res = redis.call("EXPIRETIME", "outbox:outbox_item:#{outbox_item.id}")
expect(res).to be > 0
end
end
context "when there is cached item state with le/eq errors_count" do
before do
data = Sbmt::Outbox::V2::RedisItemMeta.new(errors_count: 0, error_msg: "Some previous error")
redis.call("SET", "outbox:outbox_item:#{outbox_item.id}", data.to_s)
end
it "caches item state in redis based on db errors_count" do
result
data = redis.call("GET", "outbox:outbox_item:#{outbox_item.id}")
deserialized = JSON.parse(data)
expect(deserialized["timestamp"]).to be_an_integer
expect(deserialized).to include(
"error_msg" => "RuntimeError boom",
"errors_count" => 1,
"version" => 1
)
end
end
end
end
end
context "when item processing returning failure" do
let!(:outbox_item) { create(:outbox_item) }
before do
allow(producer).to receive(:call)
.and_return(Dry::Monads::Result::Failure.new("some error"))
end
it "returns error" do
expect(result).to be_failure
end
it "changes status to failed" do
result
expect(outbox_item.reload).to be_failed
end
it "calls middleware" do
result
expect(dummy_middleware).to have_received(:call).with(outbox_item)
end
it "does not remove outbox item" do
expect { result }.not_to change(OutboxItem, :count)
end
end
context "when outbox item has many transports" do
let!(:outbox_item) { create(:outbox_item) }
before do
allow_any_instance_of(OutboxItem).to receive(:transports).and_return([producer, HttpOrderSender])
end
it "returns success" do
expect(result).to be_success
expect(dummy_middleware).to have_received(:call).with(outbox_item)
expect(outbox_item.reload).to be_delivered
end
end
context "when outbox item has custom payload builder" do
let!(:outbox_item) { create(:outbox_item) }
before do
allow_any_instance_of(OutboxItem).to receive(:payload_builder).and_return(PayloadRenderer)
end
it "returns success" do
expect(producer).to receive(:call).with(outbox_item, "custom-payload").and_return(true)
expect(result).to be_success
expect(dummy_middleware).to have_received(:call).with(outbox_item)
expect(outbox_item.reload).to be_delivered
end
end
context "when checking retry strategies" do
let!(:outbox_item) { create(:outbox_item) }
let(:max_retries) { 1 }
before do
allow(producer).to receive(:call).and_return(false)
end
it "doesn't change status to failed" do
expect { result }.to change { outbox_item.reload.processed_at }
expect(outbox_item).to be_pending
end
it "calls middleware" do
result
expect(dummy_middleware).to have_received(:call).with(outbox_item)
end
it "increments errors count" do
expect { result }.to change { outbox_item.reload.errors_count }.from(0).to(1)
end
context "with the next processing time is greater than the current time" do
let!(:outbox_item) do
create(:outbox_item, processed_at: 1.hour.from_now)
end
it "doesn't increment errors count" do
expect { result }.not_to change { outbox_item.reload.errors_count }
end
it "skips processing" do
expect(result.failure).to eq :skip_processing
end
it "does not call middleware" do
result
expect(dummy_middleware).not_to have_received(:call)
end
end
context "with the next processing time is less than the current time" do
let!(:outbox_item) do
create(:outbox_item, processed_at: 1.hour.ago)
end
it "increments errors count" do
expect { result }.to change { outbox_item.reload.errors_count }.from(0).to(1)
end
it "processes with transport failure" do
expect(result.failure).to eq :transport_failure
end
it "calls middleware" do
result
expect(dummy_middleware).to have_received(:call).with(outbox_item)
end
end
context "when retry strategy discards item" do
let!(:outbox_item) do
create(:outbox_item, processed_at: 1.hour.ago)
end
let!(:outbox_item_2) do
create(:outbox_item, status: :delivered, event_key: outbox_item.event_key)
end
it "discards processing" do
expect(result.failure).to eq :discard_item
expect(outbox_item.reload).to be_discarded
end
it "does not call middleware" do
result
expect(dummy_middleware).not_to have_received(:call)
end
end
context "when retry strategy returns unknown error" do
let!(:outbox_item) do
create(:outbox_item, processed_at: 1.hour.ago)
end
before do
allow_any_instance_of(OutboxItem).to receive(:event_key).and_return(nil)
end
it "fails" do
expect(result.failure).to eq :retry_strategy_failure
expect(outbox_item.reload).to be_pending
end
it "does not call middleware" do
result
expect(dummy_middleware).not_to have_received(:call)
end
end
end
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/spec/interactors/sbmt/outbox/create_outbox_item_spec.rb | spec/interactors/sbmt/outbox/create_outbox_item_spec.rb | # frozen_string_literal: true
describe Sbmt::Outbox::CreateOutboxItem do
subject(:result) { described_class.call(Combined::OutboxItem, attributes: attributes) }
let(:attributes) do
{
payload: "test",
event_key: 10,
event_name: "order_created"
}
end
it "creates a record" do
expect { result }.to change(Combined::OutboxItem, :count).by(1)
expect(result).to be_success
expect(result.value!).to have_attributes(bucket: 1)
end
it "tracks Yabeda metrics" do
expect { result }
.to update_yabeda_gauge(Yabeda.outbox.last_stored_event_id).with_tags(name: "combined-outbox_item", type: :outbox, owner: nil, partition: 1)
.and increment_yabeda_counter(Yabeda.outbox.created_counter).with_tags(name: "combined-outbox_item", type: :outbox, owner: nil, partition: 1)
end
context "when got errors" do
before do
attributes.delete(:event_key)
end
it "does not track Yabeda metrics" do
expect { result }
.to not_update_yabeda_gauge(Yabeda.outbox.last_stored_event_id)
.and not_increment_yabeda_counter(Yabeda.outbox.created_counter)
end
it "returns errors" do
expect { result }.not_to change(Combined::OutboxItem, :count)
expect(result).not_to be_success
end
end
context "when partition by custom key" do
subject(:result) { described_class.call(Combined::OutboxItem, attributes: attributes, partition_by: partition_by) }
let(:partition_by) { 9 }
it "creates a record" do
expect { result }.to change(Combined::OutboxItem, :count).by(1)
expect(result).to be_success
expect(result.value!).to have_attributes(bucket: 3)
end
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/spec/interactors/sbmt/outbox/create_inbox_item_spec.rb | spec/interactors/sbmt/outbox/create_inbox_item_spec.rb | # frozen_string_literal: true
describe Sbmt::Outbox::CreateInboxItem do
subject(:result) { described_class.call(InboxItem, attributes: attributes) }
let(:attributes) do
{
payload: "test",
event_key: 10
}
end
it "creates a record" do
expect { result }.to change(InboxItem, :count).by(1)
expect(result).to be_success
expect(result.value!).to have_attributes(bucket: 2)
end
it "tracks Yabeda metrics" do
expect { result }
.to update_yabeda_gauge(Yabeda.outbox.last_stored_event_id).with_tags(name: "inbox_item", type: :inbox, owner: nil, partition: 0)
.and increment_yabeda_counter(Yabeda.outbox.created_counter).with_tags(name: "inbox_item", type: :inbox, owner: nil, partition: 0)
end
context "when got errors" do
before do
attributes.delete(:event_key)
end
it "does not track Yabeda metrics" do
expect { result }
.to not_update_yabeda_gauge(Yabeda.outbox.last_stored_event_id)
.and not_increment_yabeda_counter(Yabeda.outbox.created_counter)
end
it "returns errors" do
expect { result }.not_to change(InboxItem, :count)
expect(result).not_to be_success
end
end
context "when partition by custom key" do
subject(:result) { described_class.call(InboxItem, attributes: attributes, partition_by: partition_by) }
let(:partition_by) { 9 }
it "creates a record" do
expect { result }.to change(InboxItem, :count).by(1)
expect(result).to be_success
expect(result.value!).to have_attributes(bucket: 1)
end
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/spec/interactors/sbmt/outbox/create_outbox_batch_spec.rb | spec/interactors/sbmt/outbox/create_outbox_batch_spec.rb | # frozen_string_literal: true
describe Sbmt::Outbox::CreateOutboxBatch do
subject(:result) { described_class.call(Combined::OutboxItem, batch_attributes: batch_attributes) }
let(:batch_attributes) do
[
{
payload: "test",
event_key: 10,
event_name: "order_created"
},
{
payload: "test2",
event_key: 5,
event_name: "order_created"
}
]
end
it "creates records" do
expect { result }.to change(Combined::OutboxItem, :count).by(2)
expect(result).to be_success
expect(result.value!).to match_array(Combined::OutboxItem.ids)
end
it "tracks Yabeda metrics" do
expect { result }
.to update_yabeda_gauge(Yabeda.outbox.last_stored_event_id).with_tags(name: "combined-outbox_item", type: :outbox, owner: nil, partition: 1).with(Combined::OutboxItem.ids.first)
.and increment_yabeda_counter(Yabeda.outbox.created_counter).with_tags(name: "combined-outbox_item", type: :outbox, owner: nil, partition: 1).by(Combined::OutboxItem.ids.first)
.and update_yabeda_gauge(Yabeda.outbox.last_stored_event_id).with_tags(name: "combined-outbox_item", type: :outbox, owner: nil, partition: 0).with(Combined::OutboxItem.ids.last)
.and increment_yabeda_counter(Yabeda.outbox.created_counter).with_tags(name: "combined-outbox_item", type: :outbox, owner: nil, partition: 0).by(Combined::OutboxItem.ids.last)
end
context "when got errors" do
let(:batch_attributes) do
[
{
payload: "test",
event_name: "order_created"
},
{
payload: "test2",
event_name: "order_created"
}
]
end
it "does not track Yabeda metrics" do
expect { result }
.to not_update_yabeda_gauge(Yabeda.outbox.last_stored_event_id)
.and not_increment_yabeda_counter(Yabeda.outbox.created_counter)
end
it "returns errors" do
expect { result }.not_to change(Combined::OutboxItem, :count)
expect(result).not_to be_success
end
end
context "when partition by custom key" do
let(:batch_attributes) do
[
{
payload: "test",
event_key: 10,
event_name: "order_created"
},
{
payload: "test2",
event_key: 11,
event_name: "order_created",
partition_by: 6
}
]
end
it "creates a record" do
expect { result }.to change(Combined::OutboxItem, :count).by(2)
expect(result).to be_success
outbox_items = Combined::OutboxItem.pluck(:id, :bucket)
expect(result.value!).to match_array(outbox_items.map(&:first))
expect(outbox_items.map(&:last)).to contain_exactly(0, 1)
end
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/spec/interactors/sbmt/outbox/retry_strategies/compacted_log_spec.rb | spec/interactors/sbmt/outbox/retry_strategies/compacted_log_spec.rb | # frozen_string_literal: true
describe Sbmt::Outbox::RetryStrategies::CompactedLog do
subject(:result) { described_class.call(outbox_item_1) }
let(:event_key) { 10 }
let!(:outbox_item_1) { create(:combined_outbox_item, event_key: 10) }
context "when there are no items ahead" do
it { expect(result).to be_success }
end
context "when there are no items ahead with same key" do
let!(:outbox_item_2) { create(:combined_outbox_item, status: :delivered, event_key: event_key + 1) }
it { expect(result).to be_success }
end
context "when there are no items ahead with same event_name" do
let!(:outbox_item_2) { create(:combined_outbox_item, status: :delivered, event_key: event_key, event_name: "some-name") }
it { expect(result).to be_success }
end
context "when outbox item doesn't have event_key" do
before do
allow(outbox_item_1).to receive(:has_attribute?).with(:event_key).and_return(false)
end
it { expect(result.failure).to eq :missing_event_key }
end
context "when outbox item event_key is blank" do
before do
allow(outbox_item_1).to receive(:event_key).and_return(nil)
end
it { expect(result.failure).to eq :empty_event_key }
end
context "when next exists in any status" do
let!(:outbox_item_2) { create(:combined_outbox_item, event_key: event_key) }
it { expect(result.failure).to eq :discard_item }
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/spec/internal/app/jobs/application_job.rb | spec/internal/app/jobs/application_job.rb | # frozen_string_literal: true
class ApplicationJob < ActiveJob::Base
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/spec/internal/app/models/inbox_item.rb | spec/internal/app/models/inbox_item.rb | # frozen_string_literal: true
class InboxItem < Sbmt::Outbox::InboxItem
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/spec/internal/app/models/application_record.rb | spec/internal/app/models/application_record.rb | # frozen_string_literal: true
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/spec/internal/app/models/outbox_item.rb | spec/internal/app/models/outbox_item.rb | # frozen_string_literal: true
class OutboxItem < Sbmt::Outbox::OutboxItem
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/spec/internal/app/models/combined/outbox_item.rb | spec/internal/app/models/combined/outbox_item.rb | # frozen_string_literal: true
module Combined
class OutboxItem < Sbmt::Outbox::OutboxItem
self.table_name = :combined_outbox_items
validates :event_name, presence: true
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/spec/internal/app/producers/producer.rb | spec/internal/app/producers/producer.rb | # frozen_string_literal: true
class Producer < Sbmt::Outbox::DryInteractor
option :topic
option :kafka, optional: true
def call(item, payload)
publish
end
def publish
true
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/spec/internal/app/interactors/payload_renderer.rb | spec/internal/app/interactors/payload_renderer.rb | # frozen_string_literal: true
class PayloadRenderer < Sbmt::Outbox::DryInteractor
param :outbox_item
def call
Success("custom-payload")
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/spec/internal/app/interactors/http_order_sender.rb | spec/internal/app/interactors/http_order_sender.rb | # frozen_string_literal: true
class HttpOrderSender < Sbmt::Outbox::DryInteractor
param :outbox_item
param :payload
def call
Success()
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/spec/internal/app/interactors/import_order.rb | spec/internal/app/interactors/import_order.rb | # frozen_string_literal: true
class ImportOrder < Sbmt::Outbox::DryInteractor
option :source
def call(outbox_item, payload)
Success()
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/spec/internal/app/interactors/kafka_producer/outbox_transport_factory.rb | spec/internal/app/interactors/kafka_producer/outbox_transport_factory.rb | # frozen_string_literal: true
module KafkaProducer
class OutboxTransportFactory
def self.build(topic:, kafka: {})
::Producer.new(topic: topic, kafka: kafka)
end
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/spec/internal/db/schema.rb | spec/internal/db/schema.rb | # frozen_string_literal: true
ActiveRecord::Schema.define do
create_table :outbox_items do |t|
t.uuid :uuid, null: false
t.bigint :event_key, null: false
t.bigint :bucket, null: false
t.json :options
t.binary :payload, null: false
t.integer :status, null: false, default: 0
t.integer :errors_count, null: false, default: 0
t.text :error_log
t.timestamp :processed_at
t.timestamps
end
add_index :outbox_items, :uuid, unique: true
add_index :outbox_items, [:status, :bucket, :errors_count]
add_index :outbox_items, [:event_key, :id]
add_index :outbox_items, :created_at
create_table :combined_outbox_items do |t|
t.uuid :uuid, null: false
t.string :event_name, null: false
t.bigint :event_key, null: false
t.bigint :bucket, null: false
t.json :options
t.binary :payload, null: false
t.integer :status, null: false, default: 0
t.integer :errors_count, null: false, default: 0
t.text :error_log
t.timestamp :processed_at
t.timestamps
end
add_index :combined_outbox_items, :uuid, unique: true
add_index :combined_outbox_items, [:status, :bucket, :errors_count], name: "index_combined_outbox_items_on_status_and_bucket_and_err"
add_index :combined_outbox_items, [:event_name, :event_key, :id]
add_index :combined_outbox_items, :created_at
create_table :inbox_items do |t|
t.uuid :uuid, null: false
t.bigint :event_key, null: false
t.bigint :bucket, null: false
t.json :options
t.binary :payload, null: false
t.integer :status, null: false, default: 0
t.integer :errors_count, null: false, default: 0
t.text :error_log
t.timestamp :processed_at
t.timestamps
end
add_index :inbox_items, :uuid, unique: true
add_index :inbox_items, [:status, :bucket, :errors_count]
add_index :inbox_items, [:event_key, :id]
add_index :inbox_items, :created_at
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/spec/internal/config/routes.rb | spec/internal/config/routes.rb | # frozen_string_literal: true
Rails.application.routes.draw do
mount Sbmt::Outbox::Engine => "/outbox-ui"
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/spec/internal/config/initializers/outbox.rb | spec/internal/config/initializers/outbox.rb | # frozen_string_literal: true
Rails.application.config.outbox.tap do |config|
config.poller.tap do |pc|
pc.tactic = "noop"
pc.queue_delay = 0
pc.min_queue_size = 1
end
config.processor.tap do |pc|
pc.brpop_delay = 0.1
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/spec/internal/config/initializers/open_telemetry.rb | spec/internal/config/initializers/open_telemetry.rb | # frozen_string_literal: true
return if Rails.env.test?
OpenTelemetry::SDK.configure do |c|
c.add_span_processor(
OpenTelemetry::SDK::Trace::Export::BatchSpanProcessor.new(
OpenTelemetry::SDK::Trace::Export::ConsoleSpanExporter.new
)
)
c.service_name = "rails-app"
c.use_all
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/spec/internal/config/initializers/sentry.rb | spec/internal/config/initializers/sentry.rb | # frozen_string_literal: true
SENTRY_DUMMY_DSN = "http://12345:67890@sentry.localdomain/sentry/42"
Sentry.init do |config|
config.dsn = SENTRY_DUMMY_DSN
config.transport.transport_class = Sentry::DummyTransport
config.enabled_environments = %w[Rails.env]
config.traces_sample_rate = 0.5
config.breadcrumbs_logger = [:active_support_logger, :http_logger]
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/spec/lib/sbmt/outbox_spec.rb | spec/lib/sbmt/outbox_spec.rb | # frozen_string_literal: true
describe Sbmt::Outbox do
describe "batch_process_middlewares" do
it "returns default middlewares" do
expect(described_class.batch_process_middlewares).to eq([described_class::Middleware::Sentry::TracingBatchProcessMiddleware])
end
end
describe "item_process_middlewares" do
it "returns default middlewares" do
expect(described_class.item_process_middlewares)
.to include described_class::Middleware::Sentry::TracingItemProcessMiddleware
if defined?(ActiveSupport::ExecutionContext)
expect(described_class.item_process_middlewares)
.to include described_class::Middleware::ExecutionContext::ContextItemProcessMiddleware
end
end
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/spec/lib/sbmt/outbox/tasks/delete_items_spec.rb | spec/lib/sbmt/outbox/tasks/delete_items_spec.rb | # frozen_string_literal: true
describe "rake outbox:delete_items" do
subject(:task) { Rake::Task["outbox:delete_items"] }
let(:klass) { "OutboxItem" }
let(:status) { 1 }
let(:created_at_a) { 6.hours.ago }
let(:created_at_b) { 8.hours.ago }
let(:created_at_c) { 4.hours.ago }
let!(:outbox_item_a) { create(:outbox_item, status: :failed, errors_count: 1, created_at: created_at_a) }
let!(:outbox_item_b) { create(:outbox_item, status: :failed, errors_count: 1, created_at: created_at_b) }
let!(:outbox_item_c) { create(:outbox_item, status: :delivered, errors_count: 0, created_at: created_at_c) }
before do
task.reenable
allow(Rails.logger).to receive(:info)
end
context "when filtering records by status" do
let(:created_at_a) { Time.zone.now }
let(:created_at_b) { 6.hours.ago }
let(:created_at_c) { Time.zone.now }
it "deletes records matching the given status" do
expect {
task.invoke(klass, status)
}.to change(OutboxItem, :count).by(-1)
expect(Rails.logger).to have_received(:info).with(/Batch items deleted: 1/)
expect(Rails.logger).to have_received(:info).with(/Total items deleted: 1/)
end
end
context "when filtering records by time range" do
let(:start_time) { 7.hours.ago }
let(:end_time) { 5.hours.ago }
it "deletes records within the specified time range" do
expect {
task.invoke(klass, status, start_time, end_time)
}.to change(OutboxItem, :count).by(-1)
expect(Rails.logger).to have_received(:info).with(/Batch items deleted: 1/)
expect(Rails.logger).to have_received(:info).with(/Total items deleted: 1/)
end
end
context "when required parameters are missing" do
it "raises an error" do
expect {
task.invoke(nil, status)
}.to raise_error("Error: Class and status must be specified. Example: rake outbox:delete_items[OutboxItem,1]")
expect(Rails.logger).not_to have_received(:info)
end
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/spec/lib/sbmt/outbox/tasks/delete_failed_outbox_items_spec.rb | spec/lib/sbmt/outbox/tasks/delete_failed_outbox_items_spec.rb | # frozen_string_literal: true
describe "rake outbox:delete_failed_items" do
subject(:task) { Rake::Task["outbox:delete_failed_items"] }
let!(:outbox_item_a) { create(:outbox_item, status: :failed, errors_count: 1) }
let!(:outbox_item_b) { create(:outbox_item, status: :failed, errors_count: 1) }
let!(:outbox_item_c) { create(:outbox_item, status: :delivered, errors_count: 0) }
before do
task.reenable
end
it "deletes all failed items" do
expect { task.invoke("OutboxItem") }
.to change(OutboxItem.all, :count).from(3).to(1)
end
context "when deleting specific item" do
it "deletes that item only" do
expect { task.invoke("OutboxItem", outbox_item_b.id) }
.to change(OutboxItem.all, :count).from(3).to(2)
end
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/spec/lib/sbmt/outbox/tasks/update_status_items_spec.rb | spec/lib/sbmt/outbox/tasks/update_status_items_spec.rb | # frozen_string_literal: true
describe "rake outbox:update_status_items" do
subject(:task) { Rake::Task["outbox:update_status_items"] }
let(:klass) { "OutboxItem" }
let(:status) { 1 }
let(:new_status) { 3 }
let(:created_at_a) { 6.hours.ago }
let(:created_at_b) { 8.hours.ago }
let(:created_at_c) { 4.hours.ago }
let!(:outbox_item_a) { create(:outbox_item, status: :failed, errors_count: 1, created_at: created_at_a) }
let!(:outbox_item_b) { create(:outbox_item, status: :failed, errors_count: 1, created_at: created_at_b) }
let!(:outbox_item_c) { create(:outbox_item, status: :delivered, errors_count: 0, created_at: created_at_c) }
before do
task.reenable
allow(Rails.logger).to receive(:info)
end
context "when filtering records by status" do
let(:created_at_a) { Time.zone.now }
let(:created_at_b) { 6.hours.ago }
let(:created_at_c) { Time.zone.now }
it "updates records matching the given status" do
expect {
task.invoke(klass, status, new_status)
outbox_item_a.reload
outbox_item_b.reload
outbox_item_c.reload
}.to change(outbox_item_b, :status).from("failed").to("discarded")
.and not_change { outbox_item_a.status }
.and not_change { outbox_item_c.status }
expect(Rails.logger).to have_received(:info).with(/Batch items updated: 1/)
expect(Rails.logger).to have_received(:info).with(/Total items updated: 1/)
end
end
context "when filtering records by time range" do
let(:start_time) { 7.hours.ago }
let(:end_time) { 5.hours.ago }
it "updates records within the specified time range" do
expect {
task.invoke(klass, status, new_status, start_time, end_time)
outbox_item_a.reload
outbox_item_b.reload
outbox_item_c.reload
}.to change(outbox_item_a, :status).from("failed").to("discarded")
.and not_change { outbox_item_b.status }
.and not_change { outbox_item_c.status }
expect(Rails.logger).to have_received(:info).with(/Batch items updated: 1/)
expect(Rails.logger).to have_received(:info).with(/Total items updated: 1/)
end
end
context "when required parameters are missing" do
it "raises an error" do
expect {
task.invoke(nil, status, new_status)
}.to raise_error("Error: Class, current status, and new status must be specified. Example: rake outbox:update_status_items[OutboxItem,0,3]")
expect(Rails.logger).not_to have_received(:info)
end
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/spec/lib/sbmt/outbox/tasks/retry_failed_outbox_items_spec.rb | spec/lib/sbmt/outbox/tasks/retry_failed_outbox_items_spec.rb | # frozen_string_literal: true
describe "rake outbox:retry_failed_items" do
subject(:task) { Rake::Task["outbox:retry_failed_items"] }
let!(:outbox_item_a) { create(:outbox_item, status: :failed, errors_count: 1) }
let!(:outbox_item_b) { create(:outbox_item, status: :failed, errors_count: 1) }
let!(:outbox_item_c) { create(:outbox_item, status: :delivered, errors_count: 0) }
before do
task.reenable
end
# rubocop:disable RSpec/PendingWithoutReason
it "sets pending state for all failed items" do
expect { task.invoke("OutboxItem") }
.to change(OutboxItem.pending, :count).from(0).to(2)
end
it "resets errors_count for all failed items" do
expect { task.invoke("OutboxItem") }
.to change(OutboxItem.where(errors_count: 0), :count).from(1).to(3)
end
context "when retring specific item" do
it "sets pending state for that item only" do
expect { task.invoke("OutboxItem", outbox_item_b.id) }
.to change(OutboxItem.pending, :count).from(0).to(1)
end
it "resets errors_count for all failed items" do
expect { task.invoke("OutboxItem", outbox_item_b.id) }
.to change(OutboxItem.where(errors_count: 0), :count).from(1).to(2)
end
end
# rubocop:enable RSpec/PendingWithoutReason
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/spec/lib/sbmt/outbox/middleware/runner_spec.rb | spec/lib/sbmt/outbox/middleware/runner_spec.rb | # frozen_string_literal: true
describe Sbmt::Outbox::Middleware::Runner do
it "works with an empty stack" do
instance = described_class.new([])
expect { instance.call {} }.not_to raise_error
end
it "calls classes in the same order as given" do
a = Class.new do
def call(args)
args[:result] << "A"
yield
args[:result] << "A"
end
end
b = Class.new do
def call(args)
args[:result] << "B"
yield
args[:result] << "B"
end
end
args = {result: []}
instance = described_class.new([a, b])
instance.call(args) { args[:result] << "C" }
expect(args[:result]).to eq %w[A B C B A]
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/spec/lib/sbmt/outbox/middleware/sentry/tracing_batch_process_middleware_spec.rb | spec/lib/sbmt/outbox/middleware/sentry/tracing_batch_process_middleware_spec.rb | # frozen_string_literal: true
require "ostruct"
describe Sbmt::Outbox::Middleware::Sentry::TracingBatchProcessMiddleware do
let(:job) { OpenStruct.new(log_tags: {}) }
let(:scope) { double("scope") } # rubocop:disable RSpec/VerifiedDoubles
it "skips tracing if sentry is not initialized" do
expect(::Sentry).to receive(:initialized?).and_return(false)
expect(::Sentry).not_to receive(:start_transaction)
expect { described_class.new.call(job) {} }.not_to raise_error
end
it "sets up sentry transaction" do
expect(::Sentry).to receive(:initialized?).and_return(true)
expect(::Sentry).to receive(:get_current_scope).and_return(scope)
expect(scope).to receive(:set_tags)
expect(::Sentry).to receive(:start_transaction)
result = described_class.new.call(job) { "block_value" }
expect(result).to eq("block_value")
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/spec/lib/sbmt/outbox/middleware/sentry/tracing_item_process_middleware_spec.rb | spec/lib/sbmt/outbox/middleware/sentry/tracing_item_process_middleware_spec.rb | # frozen_string_literal: true
describe Sbmt::Outbox::Middleware::Sentry::TracingItemProcessMiddleware do
let(:outbox_item) { create(:outbox_item) }
let(:scope) { double("scope") } # rubocop:disable RSpec/VerifiedDoubles
let(:trace_id) { "trace-id" }
it "skips tracing if sentry is not initialized" do
allow(::Sentry).to receive(:initialized?).and_return(false)
expect(::Sentry).not_to receive(:start_transaction)
expect { described_class.new.call(outbox_item) {} }.not_to raise_error
end
it "sets up sentry transaction" do
allow(::Sentry).to receive(:initialized?).and_return(true)
expect(::Sentry).to receive(:get_current_scope).and_return(scope)
expect(scope).to receive(:get_transaction).and_return(nil)
expect(scope).to receive(:set_tags).with hash_including(:trace_id, box_type: :outbox, box_name: "outbox_item")
expect(::Sentry).to receive(:start_transaction)
.with(op: "sbmt.outbox.item_process", name: "Sbmt.Outbox.Outbox_item")
.and_return(nil)
result = described_class.new.call(outbox_item) { "block_value" }
expect(result).to eq("block_value")
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/spec/lib/sbmt/outbox/middleware/open_telemetry/tracing_create_batch_middleware_spec.rb | spec/lib/sbmt/outbox/middleware/open_telemetry/tracing_create_batch_middleware_spec.rb | # frozen_string_literal: true
describe Sbmt::Outbox::Middleware::OpenTelemetry::TracingCreateBatchMiddleware do
let(:tracer) { double("tracer") } # rubocop:disable RSpec/VerifiedDoubles
let(:instrumentation_instance) { double("instrumentation instance") } # rubocop:disable RSpec/VerifiedDoubles
let(:item_class) { OutboxItem }
let(:headers_first) { {header: 1} }
let(:headers_second) { {header: 2} }
let(:batch_attributes) do
[
{options: {headers: headers_first}},
{options: {headers: headers_second}}
]
end
before do
allow(::Sbmt::Outbox::Instrumentation::OpenTelemetryLoader).to receive(:instance).and_return(instrumentation_instance)
allow(instrumentation_instance).to receive(:tracer).and_return(tracer)
end
describe ".call" do
it "injects context into options/headers" do
expect(tracer).to receive(:in_span).with("outbox/outbox_item create batch", kind: :producer, attributes: {
"messaging.destination" => "OutboxItem",
"messaging.destination_kind" => "database",
"messaging.outbox.box_name" => "outbox_item",
"messaging.outbox.box_type" => "outbox",
"messaging.system" => "outbox"
}).and_yield
expect(::OpenTelemetry.propagation).to receive(:inject).with(headers_first)
expect(::OpenTelemetry.propagation).to receive(:inject).with(headers_second)
described_class.new.call(item_class, batch_attributes) {}
end
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/spec/lib/sbmt/outbox/middleware/open_telemetry/tracing_item_process_middleware_spec.rb | spec/lib/sbmt/outbox/middleware/open_telemetry/tracing_item_process_middleware_spec.rb | # frozen_string_literal: true
describe Sbmt::Outbox::Middleware::OpenTelemetry::TracingItemProcessMiddleware do
let(:tracer) { double("tracer") } # rubocop:disable RSpec/VerifiedDoubles
let(:instrumentation_instance) { double("instrumentation instance") } # rubocop:disable RSpec/VerifiedDoubles
let(:headers) { {"SOME_TELEMETRY_HEADER" => "telemetry_value"} }
let(:inbox_item) { create(:inbox_item, options: {headers: headers}) }
before do
allow(::Sbmt::Outbox::Instrumentation::OpenTelemetryLoader).to receive(:instance).and_return(instrumentation_instance)
allow(instrumentation_instance).to receive(:tracer).and_return(tracer)
allow(OpenTelemetry::Trace).to receive(:current_span).and_return(double(context: double(valid?: true, hex_trace_id: "trace-id"))) # rubocop:disable RSpec/VerifiedDoubles
end
describe ".call" do
it "injects context into message headers and logs the trace_id" do
expect(tracer).to receive(:in_span).with("inbox/inbox_item process item", kind: :consumer, attributes: {
"messaging.destination" => "InboxItem",
"messaging.destination_kind" => "database",
"messaging.operation" => "process",
"messaging.outbox.box_name" => "inbox_item",
"messaging.outbox.box_type" => "inbox",
"messaging.outbox.item_id" => inbox_item.id.to_s,
"messaging.system" => "outbox"
}).and_yield
expect(::OpenTelemetry.propagation).to receive(:extract).with(a_hash_including(headers))
expect(Sbmt::Outbox.logger).to receive(:with_tags).with(hash_including(trace_id: "trace-id")).once
described_class.new.call(inbox_item) {}
end
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/spec/lib/sbmt/outbox/middleware/open_telemetry/tracing_create_item_middleware_spec.rb | spec/lib/sbmt/outbox/middleware/open_telemetry/tracing_create_item_middleware_spec.rb | # frozen_string_literal: true
describe Sbmt::Outbox::Middleware::OpenTelemetry::TracingCreateItemMiddleware do
let(:tracer) { double("tracer") } # rubocop:disable RSpec/VerifiedDoubles
let(:instrumentation_instance) { double("instrumentation instance") } # rubocop:disable RSpec/VerifiedDoubles
let(:item_class) { OutboxItem }
let(:headers) { {} }
let(:item_attrs) { {options: {headers: headers}} }
before do
allow(::Sbmt::Outbox::Instrumentation::OpenTelemetryLoader).to receive(:instance).and_return(instrumentation_instance)
allow(instrumentation_instance).to receive(:tracer).and_return(tracer)
end
describe ".call" do
it "injects context into options/headers" do
expect(tracer).to receive(:in_span).with("outbox/outbox_item create item", kind: :producer, attributes: {
"messaging.destination" => "OutboxItem",
"messaging.destination_kind" => "database",
"messaging.outbox.box_name" => "outbox_item",
"messaging.outbox.box_type" => "outbox",
"messaging.system" => "outbox"
}).and_yield
expect(::OpenTelemetry.propagation).to receive(:inject).with(headers)
described_class.new.call(item_class, item_attrs) {}
end
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/spec/lib/sbmt/outbox/middleware/execution_context/context_item_process_middleware_spec.rb | spec/lib/sbmt/outbox/middleware/execution_context/context_item_process_middleware_spec.rb | # frozen_string_literal: true
require "sbmt/outbox/middleware/execution_context/context_item_process_middleware"
describe Sbmt::Outbox::Middleware::ExecutionContext::ContextItemProcessMiddleware do
let(:outbox_item) { create(:outbox_item) }
before do
skip("not supported in the current Rails version") unless defined?(ActiveSupport::ExecutionContext)
end
it "sets execution context" do
described_class.new.call(outbox_item) {}
expect(ActiveSupport::ExecutionContext.to_h[:box_item]).to eq outbox_item
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/spec/lib/sbmt/outbox/v2/poll_throttler_spec.rb | spec/lib/sbmt/outbox/v2/poll_throttler_spec.rb | # frozen_string_literal: true
require "sbmt/outbox/v2/poll_throttler"
describe Sbmt::Outbox::V2::PollThrottler do
let(:redis) { instance_double(RedisClient) }
let(:tactic) { nil }
let(:poller_config) { {} }
let(:build) { described_class.build(tactic, redis, poller_config) }
describe "#build" do
context "with noop throttler" do
let(:tactic) { "noop" }
it "properly builds throttler" do
expect(build).to be_an_instance_of(described_class::Noop)
end
end
context "with default throttler" do
let(:tactic) { "default" }
let(:poller_config) { Sbmt::Outbox.poller_config }
it "properly builds throttler" do
throttler = build
expect(throttler).to be_an_instance_of(described_class::Composite)
expect(throttler.throttlers.count).to eq(3)
expect(throttler.throttlers[0]).to be_an_instance_of(described_class::PausedBox)
expect(throttler.throttlers[1]).to be_an_instance_of(described_class::RedisQueueSize)
expect(throttler.throttlers[2]).to be_an_instance_of(described_class::RateLimited)
end
end
context "with low-priority throttler" do
let(:tactic) { "low-priority" }
let(:poller_config) { Sbmt::Outbox.poller_config }
it "properly builds throttler" do
throttler = build
expect(throttler).to be_an_instance_of(described_class::Composite)
expect(throttler.throttlers.count).to eq(4)
expect(throttler.throttlers[0]).to be_an_instance_of(described_class::PausedBox)
expect(throttler.throttlers[1]).to be_an_instance_of(described_class::RedisQueueSize)
expect(throttler.throttlers[2]).to be_an_instance_of(described_class::RedisQueueTimeLag)
expect(throttler.throttlers[3]).to be_an_instance_of(described_class::RateLimited)
end
end
context "with aggressive throttler" do
let(:tactic) { "aggressive" }
let(:poller_config) { Sbmt::Outbox.poller_config }
it "properly builds throttler" do
throttler = build
expect(throttler).to be_an_instance_of(described_class::Composite)
expect(throttler.throttlers.count).to eq(2)
expect(throttler.throttlers[0]).to be_an_instance_of(described_class::PausedBox)
expect(throttler.throttlers[1]).to be_an_instance_of(described_class::RedisQueueSize)
end
end
context "with unknown throttler" do
let(:tactic) { "awesome-tactic" }
it "properly builds throttler" do
expect { build }.to raise_error(/invalid poller poll tactic/)
end
end
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/spec/lib/sbmt/outbox/v2/box_processor_spec.rb | spec/lib/sbmt/outbox/v2/box_processor_spec.rb | # frozen_string_literal: true
require "sbmt/outbox/v2/box_processor"
describe Sbmt::Outbox::V2::BoxProcessor do
let(:boxes) { [OutboxItem, InboxItem] }
let(:threads_count) { 1 }
let(:processor_klass) do
Class.new(described_class) do
def process_task(worker_number, task)
# noop
end
end
end
let(:processor) do
processor_klass.new(
boxes: boxes,
threads_count: threads_count
)
end
context "when initialized" do
it "properly partitions items and builds task queue" do
task_queue = processor.send(:queue)
tasks = []
while task_queue.size > 0
tasks << task_queue.pop.to_h
end
expect(tasks.size).to eq(boxes.count)
expect(tasks).to contain_exactly(
hash_including(item_class: OutboxItem, worker_name: "abstract_worker", worker_version: 2),
hash_including(item_class: InboxItem, worker_name: "abstract_worker", worker_version: 2)
)
end
end
context "with processed task" do
let(:task) do
Sbmt::Outbox::V2::Tasks::Base.new(item_class: InboxItem, worker_name: "abstract_worker")
end
before { allow(processor.send(:thread_pool)).to receive(:start).and_yield(0, task) }
it "logs task tags" do
expect(Sbmt::Outbox.logger).to receive(:with_tags).with(**task.log_tags)
expect { processor.start }
.to increment_yabeda_counter(Yabeda.box_worker.job_counter).with_tags(name: "inbox_item", state: "processed", type: :inbox, owner: nil, worker_name: "abstract_worker", worker_version: 2).by(1)
.and measure_yabeda_histogram(Yabeda.box_worker.job_execution_runtime).with_tags(name: "inbox_item", type: :inbox, worker_name: "abstract_worker", worker_version: 2)
end
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/spec/lib/sbmt/outbox/v2/processor_spec.rb | spec/lib/sbmt/outbox/v2/processor_spec.rb | # frozen_string_literal: true
require "sbmt/outbox/v2/processor"
# rubocop:disable RSpec/IndexedLet
describe Sbmt::Outbox::V2::Processor do
let(:boxes) { [OutboxItem, InboxItem] }
let(:processor) do
described_class.new(
boxes,
lock_timeout: lock_timeout,
cutoff_timeout: cutoff_timeout,
threads_count: threads_count,
redis: redis
)
end
let(:lock_timeout) { 1 }
let(:cutoff_timeout) { nil }
let(:threads_count) { 1 }
let(:redis) { instance_double(RedisClient) }
context "when initialized" do
it "properly builds task queue" do
task_queue = processor.send(:queue)
tasks = []
while task_queue.size > 0
tasks << task_queue.pop.to_h
end
expect(tasks.size).to eq(boxes.count)
expect(tasks).to contain_exactly(
hash_including(item_class: OutboxItem, worker_name: "processor", worker_version: 2),
hash_including(item_class: InboxItem, worker_name: "processor", worker_version: 2)
)
end
end
describe "#process_task" do
let(:task) do
Sbmt::Outbox::V2::Tasks::Base.new(item_class: InboxItem, worker_name: "processor")
end
before do
allow(processor.send(:thread_pool)).to receive(:start).and_yield(0, task)
allow(redis).to receive(:read_timeout).and_return(1)
end
context "when redis job queue has pending job" do
let!(:item1) { create(:inbox_item, bucket: 0) }
let!(:item2) { create(:inbox_item, bucket: 0) }
before do
allow(redis).to receive(:call).with("GET", "inbox:inbox_item:#{item1.id}").and_return(nil)
allow(redis).to receive(:call).with("GET", "inbox:inbox_item:#{item2.id}").and_return(nil)
allow(redis).to receive(:blocking_call).with(1.1, "BRPOP", "inbox_item:job_queue", 0.1).and_return(%W[inbox_item:job_queue 0:#{Time.current.to_i}:#{item1.id},#{item2.id}])
end
it "fetches job from redis, acquires lock and processes it" do
expect(processor.send(:lock_manager)).to receive(:lock)
.with("sbmt:outbox:processor:inbox_item:0:lock", 1000)
.and_yield(task)
expect { processor.start }.to change(InboxItem.delivered, :count).from(0).to(2)
.and measure_yabeda_histogram(Yabeda.box_worker.item_execution_runtime).with_tags(name: "inbox_item", type: :inbox, worker_name: "processor", worker_version: 2)
.and increment_yabeda_counter(Yabeda.box_worker.job_items_counter).with_tags(name: "inbox_item", type: :inbox, worker_name: "processor", worker_version: 2).by(2)
.and not_increment_yabeda_counter(Yabeda.box_worker.job_timeout_counter)
.and increment_yabeda_counter(Yabeda.outbox.sent_counter).with_tags(name: "inbox_item", type: :inbox, owner: nil, partition: 0, worker_version: 2).by(2)
.and update_yabeda_gauge(Yabeda.outbox.last_sent_event_id).with_tags(name: "inbox_item", type: :inbox, owner: nil, partition: 0, worker_version: 2)
.and measure_yabeda_histogram(Yabeda.outbox.process_latency).with_tags(name: "inbox_item", type: :inbox, owner: nil, partition: 0, worker_version: 2)
.and increment_yabeda_counter(Yabeda.outbox.error_counter).with_tags(name: "inbox_item", type: :inbox, owner: nil, partition: 0, worker_version: 2).by(0)
.and increment_yabeda_counter(Yabeda.outbox.retry_counter).with_tags(name: "inbox_item", type: :inbox, owner: nil, partition: 0, worker_version: 2).by(0)
.and increment_yabeda_counter(Yabeda.outbox.discarded_counter).with_tags(name: "inbox_item", type: :inbox, owner: nil, partition: 0, worker_version: 2).by(0)
.and increment_yabeda_counter(Yabeda.outbox.fetch_error_counter).with_tags(name: "inbox_item", type: :inbox, owner: nil, partition: 0, worker_version: 2).by(0)
end
it "skips job if lock is already being held by other thread" do
expect(processor.send(:lock_manager)).to receive(:lock)
.with("sbmt:outbox:processor:inbox_item:0:lock", 1000)
.and_yield(nil)
expect(processor.start).to be(Sbmt::Outbox::V2::ThreadPool::SKIPPED)
end
context "when cutoff times out after first processed item in batch" do
let(:lock_timeout) { 10 }
let(:cutoff_timeout) { 1 }
let(:cutoff_exception) { Cutoff::CutoffExceededError.new(Cutoff.new(cutoff_timeout)) }
before do
allow_any_instance_of(Cutoff).to receive(:checkpoint!).and_raise(cutoff_exception)
allow(Sbmt::Outbox.logger).to receive(:log_info)
end
it "processes only first item" do
expect(processor.send(:lock_manager)).to receive(:lock)
.with("sbmt:outbox:processor:inbox_item:0:lock", 10000)
.and_yield(task)
expect(Sbmt::Outbox.logger).to receive(:log_info).with(/Lock timeout while processing/)
expect { processor.start }
.to change(InboxItem.delivered, :count).from(0).to(1)
.and increment_yabeda_counter(Yabeda.box_worker.job_items_counter).with_tags(name: "inbox_item", type: :inbox, worker_name: "processor", worker_version: 2).by(1)
.and increment_yabeda_counter(Yabeda.box_worker.job_timeout_counter).with_tags(name: "inbox_item", type: :inbox, worker_name: "processor", worker_version: 2).by(1)
end
end
context "when use option strict_order" do
context "when strict_order is true" do
before do
allow(task.item_class).to receive(:config).and_return(OpenStruct.new(strict_order: true))
end
it "stops processing on failure" do
expect(processor.send(:lock_manager)).to receive(:lock)
.with("sbmt:outbox:processor:inbox_item:0:lock", 1000)
.and_yield(task)
allow(Sbmt::Outbox::ProcessItem).to receive(:call).with(any_args).and_return(OpenStruct.new(failure?: true))
expect { processor.start }.to not_change(InboxItem.delivered, :count)
.and measure_yabeda_histogram(Yabeda.box_worker.item_execution_runtime).with_tags(name: "inbox_item", type: :inbox, worker_name: "processor", worker_version: 2)
.and increment_yabeda_counter(Yabeda.box_worker.job_items_counter).with_tags(name: "inbox_item", type: :inbox, worker_name: "processor", worker_version: 2).by(1)
.and not_increment_yabeda_counter(Yabeda.box_worker.job_timeout_counter)
.and not_increment_yabeda_counter(Yabeda.outbox.sent_counter)
.and not_update_yabeda_gauge(Yabeda.outbox.last_sent_event_id)
.and not_measure_yabeda_histogram(Yabeda.outbox.process_latency)
.and not_increment_yabeda_counter(Yabeda.outbox.error_counter)
.and not_increment_yabeda_counter(Yabeda.outbox.retry_counter)
.and not_increment_yabeda_counter(Yabeda.outbox.discarded_counter)
.and not_increment_yabeda_counter(Yabeda.outbox.fetch_error_counter)
end
end
context "when strict_order is false" do
it "continues processing on failure" do
expect(processor.send(:lock_manager)).to receive(:lock)
.with("sbmt:outbox:processor:inbox_item:0:lock", 1000)
.and_yield(task)
allow(Sbmt::Outbox::ProcessItem).to receive(:call).with(any_args).and_return(OpenStruct.new(failure?: true))
expect { processor.start }.to not_change(InboxItem.delivered, :count)
.and measure_yabeda_histogram(Yabeda.box_worker.item_execution_runtime).with_tags(name: "inbox_item", type: :inbox, worker_name: "processor", worker_version: 2)
.and increment_yabeda_counter(Yabeda.box_worker.job_items_counter).with_tags(name: "inbox_item", type: :inbox, worker_name: "processor", worker_version: 2).by(2)
.and not_increment_yabeda_counter(Yabeda.box_worker.job_timeout_counter)
.and not_increment_yabeda_counter(Yabeda.outbox.sent_counter)
.and not_update_yabeda_gauge(Yabeda.outbox.last_sent_event_id)
.and not_measure_yabeda_histogram(Yabeda.outbox.process_latency)
.and not_increment_yabeda_counter(Yabeda.outbox.error_counter)
.and not_increment_yabeda_counter(Yabeda.outbox.retry_counter)
.and not_increment_yabeda_counter(Yabeda.outbox.discarded_counter)
.and not_increment_yabeda_counter(Yabeda.outbox.fetch_error_counter)
end
end
end
end
context "when redis job queue is empty" do
it "waits for 1 sec and skips task" do
expect(redis).to receive(:blocking_call).with(1.1, "BRPOP", "inbox_item:job_queue", 0.1).and_return(nil)
expect(processor.send(:lock_manager)).not_to receive(:lock)
expect(processor.start).to be(Sbmt::Outbox::V2::ThreadPool::SKIPPED)
end
end
end
end
# rubocop:enable RSpec/IndexedLet
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/spec/lib/sbmt/outbox/v2/worker_spec.rb | spec/lib/sbmt/outbox/v2/worker_spec.rb | # frozen_string_literal: true
require "sbmt/outbox/v2/worker"
describe Sbmt::Outbox::V2::Worker do
let(:boxes) { [OutboxItem] }
let(:poll_tactic) { "aggressive" }
let(:processor_concurrency) { 1 }
let(:poller_partitions_count) { 1 }
let(:poller_threads_count) { 1 }
let!(:worker) do
described_class.new(
boxes: boxes,
poll_tactic: poll_tactic,
processor_concurrency: processor_concurrency,
poller_partitions_count: poller_partitions_count,
poller_threads_count: poller_threads_count
)
end
let(:failing_transport) do
lambda { |_item, _payload| raise StandardError }
end
let(:transport) do
lambda { |_item, _payload| true }
end
around do |spec|
spec.run
worker.stop
end
context "when initialized" do
it "passes readiness check" do
worker.start_async
expect(worker).to be_ready
end
end
context "when processing error occurred" do
let!(:first_failing) { create(:outbox_item, bucket: 0) }
let!(:second_failing) { create(:outbox_item, bucket: 1) }
let!(:first_successful) { create(:inbox_item, bucket: 0) }
let!(:second_successful) { create(:inbox_item, bucket: 1) }
let(:processor_concurrency) { 2 }
let(:poller_partitions_count) { 1 }
let(:poller_threads_count) { 2 }
let(:boxes) { [OutboxItem, InboxItem] }
before do
allow_any_instance_of(Sbmt::Outbox::OutboxItemConfig).to receive_messages(
max_retries: 1,
retry_strategies: [Sbmt::Outbox::RetryStrategies::NoDelay],
transports: {_all_: [failing_transport]}
)
allow_any_instance_of(Sbmt::Outbox::InboxItemConfig).to receive_messages(
transports: {_all_: [transport]}
)
end
it "concurrently retries processing" do
expect do
worker.start_async
sleep(2)
end.to change(OutboxItem.failed, :count).from(0).to(2)
.and change(InboxItem.delivered, :count).from(0).to(2)
expect(first_failing.reload.errors_count).to eq(2)
expect(second_failing.reload.errors_count).to eq(2)
expect(first_successful.reload.errors_count).to eq(0)
expect(second_successful.reload.errors_count).to eq(0)
end
end
context "with poller concurrency" do
let!(:first) { create(:inbox_item, bucket: 0) }
let!(:second) { create(:inbox_item, bucket: 0) }
let!(:third) { create(:inbox_item, bucket: 1) }
let!(:forth) { create(:inbox_item, bucket: 1) }
let(:processor_concurrency) { 2 }
let(:poller_partitions_count) { 2 }
let(:poller_threads_count) { 2 }
let(:boxes) { [InboxItem] }
before do
allow_any_instance_of(Sbmt::Outbox::InboxItemConfig).to receive_messages(
transports: {_all_: [transport]}
)
end
it "successfully processes items" do
expect do
worker.start_async
sleep(2)
end.to change(InboxItem.delivered, :count).from(0).to(4)
end
end
context "with default poll tactic" do
let!(:item) { create(:outbox_item, bucket: 0) }
let(:poll_tactic) { "default" }
before do
allow_any_instance_of(Sbmt::Outbox::OutboxItemConfig).to receive_messages(
transports: {_all_: [transport]}
)
end
it "successfully processes item" do
expect do
worker.start_async
sleep(2)
end.to change(OutboxItem.delivered, :count).from(0).to(1)
end
end
context "with low-priority poll tactic" do
let!(:item) { create(:outbox_item, bucket: 0) }
let(:poll_tactic) { "low-priority" }
before do
allow_any_instance_of(Sbmt::Outbox::OutboxItemConfig).to receive_messages(
transports: {_all_: [transport]}
)
end
it "successfully processes item" do
expect do
worker.start_async
sleep(2)
end.to change(OutboxItem.delivered, :count).from(0).to(1)
end
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/spec/lib/sbmt/outbox/v2/poller_spec.rb | spec/lib/sbmt/outbox/v2/poller_spec.rb | # frozen_string_literal: true
require "sbmt/outbox/v2/poller"
# rubocop:disable RSpec/IndexedLet
describe Sbmt::Outbox::V2::Poller do
let(:boxes) { [OutboxItem, InboxItem] }
let(:regular_batch_size) { 2 }
let(:retry_batch_size) { 1 }
let(:throttler_tactic) { "noop" }
let(:dummy_middleware_class) { instance_double(Class, new: dummy_middleware) }
let(:dummy_middleware) { ->(*_args, &b) { b.call } }
let(:poller) do
described_class.new(
boxes,
partitions_count: 2,
lock_timeout: 1,
threads_count: 1,
regular_items_batch_size: regular_batch_size,
retryable_items_batch_size: retry_batch_size,
redis: redis,
throttler_tactic: throttler_tactic
)
end
let(:redis) { instance_double(RedisClient) }
before do
allow(redis).to receive(:pipelined).and_yield(redis)
allow(Sbmt::Outbox).to receive(:polling_item_middlewares).and_return([dummy_middleware_class])
allow(dummy_middleware).to receive(:call).and_call_original
end
context "when initialized" do
it "properly partitions items and builds task queue" do
task_queue = poller.send(:queue)
tasks = []
while task_queue.size > 0
tasks << task_queue.pop.to_h
end
expect(tasks.size).to eq(boxes.count * 2)
expect(tasks).to contain_exactly(
hash_including(item_class: OutboxItem, partition: 0, buckets: [0, 2], resource_key: "outbox_item:0", resource_path: "sbmt:outbox:poller:outbox_item:0", redis_queue: "outbox_item:job_queue", worker_name: "poller", worker_version: 2),
hash_including(item_class: OutboxItem, partition: 1, buckets: [1, 3], resource_key: "outbox_item:1", resource_path: "sbmt:outbox:poller:outbox_item:1", redis_queue: "outbox_item:job_queue", worker_name: "poller", worker_version: 2),
hash_including(item_class: InboxItem, partition: 0, buckets: [0, 2], resource_key: "inbox_item:0", resource_path: "sbmt:outbox:poller:inbox_item:0", redis_queue: "inbox_item:job_queue", worker_name: "poller", worker_version: 2),
hash_including(item_class: InboxItem, partition: 1, buckets: [1, 3], resource_key: "inbox_item:1", resource_path: "sbmt:outbox:poller:inbox_item:1", redis_queue: "inbox_item:job_queue", worker_name: "poller", worker_version: 2)
)
end
end
describe "#process_task" do
let(:task) do
Sbmt::Outbox::V2::Tasks::Poll.new(
item_class: InboxItem, worker_name: "poller", partition: 0, buckets: [0, 2]
)
end
before { allow(poller.send(:thread_pool)).to receive(:start).and_yield(0, task) }
it "properly acquires lock per task" do
expect(poller.send(:lock_manager)).to receive(:lock)
.with("sbmt:outbox:poller:inbox_item:0:lock", 1000)
expect(poller.start).to be(Sbmt::Outbox::V2::ThreadPool::PROCESSED)
expect(dummy_middleware).not_to have_received(:call)
end
it "returns SKIPPED if lock is not acquired" do
expect(poller.send(:lock_manager)).to receive(:lock).and_yield(nil)
expect(poller.start).to be(Sbmt::Outbox::V2::ThreadPool::SKIPPED)
expect(dummy_middleware).not_to have_received(:call)
end
context "when default poll tactic is used" do
let(:throttler_tactic) { "default" }
it "skips poll-cycle if redis queue is oversized" do
expect(redis).to receive(:call).with("LLEN", "inbox_item:job_queue").and_return(200)
expect(poller.send(:lock_manager)).not_to receive(:lock)
expect(poller.start).to be(Sbmt::Outbox::V2::ThreadPool::SKIPPED)
expect(dummy_middleware).not_to have_received(:call)
end
it "does not throttle processing if redis queue is not oversized" do
expect(redis).to receive(:call).with("LLEN", "inbox_item:job_queue").and_return(0)
expect(poller.send(:lock_manager)).to receive(:lock).with("sbmt:outbox:poller:inbox_item:0:lock", 1000)
expect(poller.start).to be(Sbmt::Outbox::V2::ThreadPool::PROCESSED)
expect(dummy_middleware).not_to have_received(:call)
end
end
context "when pushing to redis job queue" do
let(:freeze_time) { Time.current }
around { |ex| travel_to(freeze_time, &ex) }
context "when no pending items in buckets" do
let(:regular_batch_size) { 1 }
let!(:item1) { create(:inbox_item, bucket: 1) }
let!(:item2) { create(:inbox_item, bucket: 3) }
it "returns no data" do
expect(redis).not_to receive(:call)
expect { poller.process_task(0, task) }
.to measure_yabeda_histogram(Yabeda.box_worker.item_execution_runtime).with_tags(name: "inbox_item", partition: 0, type: :inbox, worker_name: "poller", worker_version: 2)
.and not_increment_yabeda_counter(Yabeda.box_worker.job_items_counter)
.and increment_yabeda_counter(Yabeda.box_worker.batches_per_poll_counter).with_tags(name: "inbox_item", partition: 0, type: :inbox, worker_name: "poller", worker_version: 2).by(1)
.and not_increment_yabeda_counter(Yabeda.box_worker.job_timeout_counter)
expect(dummy_middleware).to have_received(:call)
end
end
context "when items are only regular" do
let(:regular_batch_size) { 3 }
let(:retry_batch_size) { 1 }
# i.e. max_batch_size = 3, max_buffer_size = 4
# so it makes 1 batch (sql) poll request to fill regular_batch_size
let!(:item1_1) { create(:inbox_item, bucket: 0) }
let!(:item1_2) { create(:inbox_item, bucket: 0) }
let!(:item2) { create(:inbox_item, bucket: 1) }
let!(:item3) { create(:inbox_item, bucket: 2) }
it "polls only regular items" do
expect(redis).to receive(:call).with("LPUSH", "inbox_item:job_queue", "0:#{freeze_time.to_i}:#{item1_1.id},#{item1_2.id}")
expect(redis).to receive(:call).with("LPUSH", "inbox_item:job_queue", "2:#{freeze_time.to_i}:#{item3.id}")
expect { poller.process_task(0, task) }
.to measure_yabeda_histogram(Yabeda.box_worker.item_execution_runtime).with_tags(name: "inbox_item", partition: 0, type: :inbox, worker_name: "poller", worker_version: 2)
.and increment_yabeda_counter(Yabeda.box_worker.job_items_counter).with_tags(name: "inbox_item", partition: 0, type: :inbox, worker_name: "poller", worker_version: 2).by(3)
.and increment_yabeda_counter(Yabeda.box_worker.batches_per_poll_counter).with_tags(name: "inbox_item", partition: 0, type: :inbox, worker_name: "poller", worker_version: 2).by(1)
.and not_increment_yabeda_counter(Yabeda.box_worker.job_timeout_counter)
expect(dummy_middleware).to have_received(:call)
end
end
context "when items are mostly retryable" do
let(:regular_batch_size) { 1 }
let(:retry_batch_size) { 1 }
# i.e. max_batch_size = 1, max_buffer_size = 2
# so it makes 2 batch (sql) poll requests
# 1: fills buffer with 1 retryable item and skips 2nd retryable item, because retry_batch_size = 1 is already hit
# 2: fills buffer with 1 regular item
let!(:item1_1) { create(:inbox_item, bucket: 0, errors_count: 1) }
let!(:item1_2) { create(:inbox_item, bucket: 0, errors_count: 1) }
let!(:item2) { create(:inbox_item, bucket: 1, errors_count: 1) }
let!(:item3) { create(:inbox_item, bucket: 2) }
it "polls more batches to fill regular items buffer limit" do
expect(redis).to receive(:call).with("LPUSH", "inbox_item:job_queue", "0:#{freeze_time.to_i}:#{item1_1.id}")
expect(redis).to receive(:call).with("LPUSH", "inbox_item:job_queue", "2:#{freeze_time.to_i}:#{item3.id}")
expect { poller.process_task(0, task) }
.to measure_yabeda_histogram(Yabeda.box_worker.item_execution_runtime).with_tags(name: "inbox_item", partition: 0, type: :inbox, worker_name: "poller", worker_version: 2)
.and increment_yabeda_counter(Yabeda.box_worker.job_items_counter).with_tags(name: "inbox_item", partition: 0, type: :inbox, worker_name: "poller", worker_version: 2).by(2)
.and increment_yabeda_counter(Yabeda.box_worker.batches_per_poll_counter).with_tags(name: "inbox_item", partition: 0, type: :inbox, worker_name: "poller", worker_version: 2).by(2)
.and not_increment_yabeda_counter(Yabeda.box_worker.job_timeout_counter)
expect(dummy_middleware).to have_received(:call)
end
end
context "when items are mixed" do
let(:retry_batch_size) { 1 }
let(:regular_batch_size) { 1 }
# i.e. max_batch_size = 1, max_buffer_size = 2
# so it makes 1 batch (sql) poll request to fill regular_batch_size and stops
# because regular items have priority over retryable ones
# and the rest retryable items will be polled later in the next poll
let!(:item1) { create(:inbox_item, bucket: 0) }
let!(:item2) { create(:inbox_item, bucket: 1, errors_count: 1) }
let!(:item3) { create(:inbox_item, bucket: 2, errors_count: 1) }
it "stops if regular buffer limit is full" do
expect(redis).to receive(:call).with("LPUSH", "inbox_item:job_queue", "0:#{freeze_time.to_i}:#{item1.id}")
expect { poller.process_task(0, task) }
.to measure_yabeda_histogram(Yabeda.box_worker.item_execution_runtime).with_tags(name: "inbox_item", partition: 0, type: :inbox, worker_name: "poller", worker_version: 2)
.and increment_yabeda_counter(Yabeda.box_worker.job_items_counter).with_tags(name: "inbox_item", partition: 0, type: :inbox, worker_name: "poller", worker_version: 2).by(1)
.and increment_yabeda_counter(Yabeda.box_worker.batches_per_poll_counter).with_tags(name: "inbox_item", partition: 0, type: :inbox, worker_name: "poller", worker_version: 2).by(1)
.and not_increment_yabeda_counter(Yabeda.box_worker.job_timeout_counter)
expect(dummy_middleware).to have_received(:call)
end
end
end
end
end
# rubocop:enable RSpec/IndexedLet
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/spec/lib/sbmt/outbox/v2/tasks/poll_spec.rb | spec/lib/sbmt/outbox/v2/tasks/poll_spec.rb | # frozen_string_literal: true
require "sbmt/outbox/v2/tasks/poll"
describe Sbmt::Outbox::V2::Tasks::Poll do
let(:worker_name) { "worker" }
let(:partition) { 0 }
let(:buckets) { [0, 1] }
it "properly formats log tags" do
expect(described_class.new(item_class: InboxItem, worker_name: worker_name, partition: partition, buckets: buckets).log_tags).to eq(box_name: "inbox_item", box_type: :inbox, box_partition: 0, worker_name: "worker", worker_version: 2)
expect(described_class.new(item_class: OutboxItem, worker_name: worker_name, partition: partition, buckets: buckets).log_tags).to eq(box_name: "outbox_item", box_type: :outbox, box_partition: 0, worker_name: "worker", worker_version: 2)
expect(described_class.new(item_class: Combined::OutboxItem, worker_name: worker_name, partition: partition, buckets: buckets).log_tags).to eq(box_name: "combined/outbox_item", box_type: :outbox, box_partition: 0, worker_name: "worker", worker_version: 2)
end
it "properly formats yabeda labels" do
expect(described_class.new(item_class: InboxItem, worker_name: worker_name, partition: partition, buckets: buckets).yabeda_labels).to eq(name: "inbox_item", owner: nil, type: :inbox, worker_name: "worker", worker_version: 2, partition: 0)
expect(described_class.new(item_class: OutboxItem, worker_name: worker_name, partition: partition, buckets: buckets).yabeda_labels).to eq(name: "outbox_item", owner: nil, type: :outbox, worker_name: "worker", worker_version: 2, partition: 0)
expect(described_class.new(item_class: Combined::OutboxItem, worker_name: worker_name, partition: partition, buckets: buckets).yabeda_labels).to eq(name: "combined-outbox_item", owner: nil, type: :outbox, worker_name: "worker", worker_version: 2, partition: 0)
end
it "properly converts to hash" do
expect(described_class.new(item_class: InboxItem, worker_name: worker_name, partition: partition, buckets: buckets).to_h)
.to eq(
item_class: InboxItem, worker_name: "worker", worker_version: 2, partition: 0, buckets: [0, 1],
resource_key: "inbox_item:0", resource_path: "sbmt:outbox:worker:inbox_item:0", redis_queue: "inbox_item:job_queue",
log_tags: {box_name: "inbox_item", box_partition: 0, box_type: :inbox, worker_name: "worker", worker_version: 2},
yabeda_labels: {name: "inbox_item", owner: nil, type: :inbox, partition: 0, worker_name: "worker", worker_version: 2}
)
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/spec/lib/sbmt/outbox/v2/tasks/base_spec.rb | spec/lib/sbmt/outbox/v2/tasks/base_spec.rb | # frozen_string_literal: true
require "sbmt/outbox/v2/tasks/base"
describe Sbmt::Outbox::V2::Tasks::Base do
let(:worker_name) { "worker" }
it "properly formats log tags" do
expect(described_class.new(item_class: InboxItem, worker_name: worker_name).log_tags).to eq(box_name: "inbox_item", box_type: :inbox, worker_name: "worker", worker_version: 2)
expect(described_class.new(item_class: OutboxItem, worker_name: worker_name).log_tags).to eq(box_name: "outbox_item", box_type: :outbox, worker_name: "worker", worker_version: 2)
expect(described_class.new(item_class: Combined::OutboxItem, worker_name: worker_name).log_tags).to eq(box_name: "combined/outbox_item", box_type: :outbox, worker_name: "worker", worker_version: 2)
end
it "properly formats yabeda labels" do
expect(described_class.new(item_class: InboxItem, worker_name: worker_name).yabeda_labels).to eq(name: "inbox_item", owner: nil, type: :inbox, worker_name: "worker", worker_version: 2)
expect(described_class.new(item_class: OutboxItem, worker_name: worker_name).yabeda_labels).to eq(name: "outbox_item", owner: nil, type: :outbox, worker_name: "worker", worker_version: 2)
expect(described_class.new(item_class: Combined::OutboxItem, worker_name: worker_name).yabeda_labels).to eq(name: "combined-outbox_item", owner: nil, type: :outbox, worker_name: "worker", worker_version: 2)
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/spec/lib/sbmt/outbox/v2/tasks/process_spec.rb | spec/lib/sbmt/outbox/v2/tasks/process_spec.rb | # frozen_string_literal: true
require "sbmt/outbox/v2/tasks/process"
describe Sbmt::Outbox::V2::Tasks::Process do
let(:worker_name) { "worker" }
let(:bucket) { 0 }
let(:ids) { [0, 1] }
it "properly formats log tags" do
expect(described_class.new(item_class: InboxItem, worker_name: worker_name, bucket: bucket, ids: ids).log_tags).to eq(box_name: "inbox_item", box_type: :inbox, bucket: 0, worker_name: "worker", worker_version: 2)
expect(described_class.new(item_class: OutboxItem, worker_name: worker_name, bucket: bucket, ids: ids).log_tags).to eq(box_name: "outbox_item", box_type: :outbox, bucket: 0, worker_name: "worker", worker_version: 2)
expect(described_class.new(item_class: Combined::OutboxItem, worker_name: worker_name, bucket: bucket, ids: ids).log_tags).to eq(box_name: "combined/outbox_item", box_type: :outbox, bucket: 0, worker_name: "worker", worker_version: 2)
end
it "properly formats yabeda labels" do
expect(described_class.new(item_class: InboxItem, worker_name: worker_name, bucket: bucket, ids: ids).yabeda_labels).to eq(name: "inbox_item", owner: nil, type: :inbox, worker_name: "worker", worker_version: 2)
expect(described_class.new(item_class: OutboxItem, worker_name: worker_name, bucket: bucket, ids: ids).yabeda_labels).to eq(name: "outbox_item", owner: nil, type: :outbox, worker_name: "worker", worker_version: 2)
expect(described_class.new(item_class: Combined::OutboxItem, worker_name: worker_name, bucket: bucket, ids: ids).yabeda_labels).to eq(name: "combined-outbox_item", owner: nil, type: :outbox, worker_name: "worker", worker_version: 2)
end
it "properly converts to hash" do
expect(described_class.new(item_class: InboxItem, worker_name: worker_name, bucket: bucket, ids: ids).to_h)
.to eq(
item_class: InboxItem, worker_name: "worker", worker_version: 2, bucket: 0, ids: [0, 1],
resource_key: "inbox_item:0", resource_path: "sbmt:outbox:worker:inbox_item:0",
log_tags: {box_name: "inbox_item", bucket: 0, box_type: :inbox, worker_name: "worker", worker_version: 2},
yabeda_labels: {name: "inbox_item", owner: nil, type: :inbox, worker_name: "worker", worker_version: 2}
)
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/spec/lib/sbmt/outbox/v2/poll_throttler/rate_limited_spec.rb | spec/lib/sbmt/outbox/v2/poll_throttler/rate_limited_spec.rb | # frozen_string_literal: true
require "sbmt/outbox/v2/poller"
require "sbmt/outbox/v2/poll_throttler/rate_limited"
describe Sbmt::Outbox::V2::PollThrottler::RateLimited do
let(:limit) { 60 }
let(:interval) { 60 }
let(:throttler) { described_class.new(limit: limit, interval: interval) }
let(:task_inbox) do
Sbmt::Outbox::V2::Tasks::Poll.new(
item_class: InboxItem, worker_name: "poller", partition: 0, buckets: [0, 2]
)
end
let(:task_outbox) do
Sbmt::Outbox::V2::Tasks::Poll.new(
item_class: OutboxItem, worker_name: "poller", partition: 0, buckets: [0, 2]
)
end
it "uses different queues for item classes" do
expect do
throttler.call(0, task_inbox, Sbmt::Outbox::V2::ThreadPool::PROCESSED)
throttler.call(0, task_outbox, Sbmt::Outbox::V2::ThreadPool::PROCESSED)
throttler.call(0, task_inbox, Sbmt::Outbox::V2::ThreadPool::PROCESSED)
throttler.call(0, task_outbox, Sbmt::Outbox::V2::ThreadPool::PROCESSED)
end.to increment_yabeda_counter(Yabeda.box_worker.poll_throttling_counter).with_tags(status: "throttle", throttler: "Sbmt::Outbox::V2::PollThrottler::RateLimited", name: "inbox_item", type: :inbox, worker_name: "poller", worker_version: 2).by(2)
.and increment_yabeda_counter(Yabeda.box_worker.poll_throttling_counter).with_tags(status: "throttle", throttler: "Sbmt::Outbox::V2::PollThrottler::RateLimited", name: "outbox_item", type: :outbox, worker_name: "poller", worker_version: 2).by(2)
.and measure_yabeda_histogram(Yabeda.box_worker.poll_throttling_runtime).with_tags(throttler: "Sbmt::Outbox::V2::PollThrottler::RateLimited", name: "inbox_item", type: :inbox, worker_name: "poller", worker_version: 2)
.and measure_yabeda_histogram(Yabeda.box_worker.poll_throttling_runtime).with_tags(throttler: "Sbmt::Outbox::V2::PollThrottler::RateLimited", name: "outbox_item", type: :outbox, worker_name: "poller", worker_version: 2)
expect(throttler.queues.count).to eq(2)
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Kuper-Tech/sbmt-outbox | https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/spec/lib/sbmt/outbox/v2/poll_throttler/fixed_delay_spec.rb | spec/lib/sbmt/outbox/v2/poll_throttler/fixed_delay_spec.rb | # frozen_string_literal: true
require "sbmt/outbox/v2/poller"
require "sbmt/outbox/v2/poll_throttler/fixed_delay"
describe Sbmt::Outbox::V2::PollThrottler::FixedDelay do
let(:delay) { 0.1 }
let(:throttler) { described_class.new(delay: delay) }
let(:task) do
Sbmt::Outbox::V2::Tasks::Poll.new(
item_class: InboxItem, worker_name: "poller", partition: 0, buckets: [0, 2]
)
end
it "waits if task is PROCESSED" do
expect(throttler).to receive(:sleep).with(delay)
expect { throttler.call(0, task, Sbmt::Outbox::V2::ThreadPool::PROCESSED) }
.to increment_yabeda_counter(Yabeda.box_worker.poll_throttling_counter).with_tags(status: "throttle", throttler: "Sbmt::Outbox::V2::PollThrottler::FixedDelay", name: "inbox_item", type: :inbox, worker_name: "poller", worker_version: 2).by(1)
.and measure_yabeda_histogram(Yabeda.box_worker.poll_throttling_runtime).with_tags(throttler: "Sbmt::Outbox::V2::PollThrottler::FixedDelay", name: "inbox_item", type: :inbox, worker_name: "poller", worker_version: 2)
end
it "does not wait if task is not PROCESSED" do
expect(throttler).not_to receive(:sleep)
expect { throttler.call(0, task, Sbmt::Outbox::V2::ThreadPool::SKIPPED) }
.to increment_yabeda_counter(Yabeda.box_worker.poll_throttling_counter).with_tags(status: "noop", throttler: "Sbmt::Outbox::V2::PollThrottler::FixedDelay", name: "inbox_item", type: :inbox, worker_name: "poller", worker_version: 2).by(1)
.and measure_yabeda_histogram(Yabeda.box_worker.poll_throttling_runtime).with_tags(throttler: "Sbmt::Outbox::V2::PollThrottler::FixedDelay", name: "inbox_item", type: :inbox, worker_name: "poller", worker_version: 2)
end
end
| ruby | MIT | 6da9ae3ea0333ae3ad58983c035bc95bd739aaf4 | 2026-01-04T17:51:44.997823Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.