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
Kuper-Tech/sbmt-outbox
https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/spec/lib/sbmt/outbox/v2/poll_throttler/redis_queue_size_spec.rb
spec/lib/sbmt/outbox/v2/poll_throttler/redis_queue_size_spec.rb
# frozen_string_literal: true require "sbmt/outbox/v2/poller" require "sbmt/outbox/v2/poll_throttler/redis_queue_size" describe Sbmt::Outbox::V2::PollThrottler::RedisQueueSize do let(:delay) { 0.1 } let(:min_size) { -1 } let(:max_size) { 10 } let(:task) do Sbmt::Outbox::V2::Tasks::Poll.new( item_class: InboxItem, worker_name: "poller", partition: 0, buckets: [0, 2] ) end let(:redis) { instance_double(RedisClient) } let(:throttler) { described_class.new(redis: redis, min_size: min_size, max_size: max_size, delay: delay) } context "when min_size is defined" do let(:min_size) { 5 } it "waits if queue size is less than min_size" do allow(redis).to receive(:call).with("LLEN", task.redis_queue).and_return("2") expect(throttler).to receive(:sleep).with(delay) expect { throttler.call(0, task, nil) } .to increment_yabeda_counter(Yabeda.box_worker.poll_throttling_counter).with_tags(status: "throttle", throttler: "Sbmt::Outbox::V2::PollThrottler::RedisQueueSize", name: "inbox_item", type: :inbox, worker_name: "poller", worker_version: 2).by(1) .and update_yabeda_gauge(Yabeda.box_worker.redis_job_queue_size).with_tags(throttler: "Sbmt::Outbox::V2::PollThrottler::RedisQueueSize", name: "inbox_item", type: :inbox, worker_name: "poller", worker_version: 2).with(2) .and measure_yabeda_histogram(Yabeda.box_worker.poll_throttling_runtime).with_tags(throttler: "Sbmt::Outbox::V2::PollThrottler::RedisQueueSize", name: "inbox_item", type: :inbox, worker_name: "poller", worker_version: 2) end it "does not wait if queue size is above min_size" do allow(redis).to receive(:call).with("LLEN", task.redis_queue).and_return("6") expect(throttler).not_to receive(:sleep) expect { throttler.call(0, task, nil) } .to increment_yabeda_counter(Yabeda.box_worker.poll_throttling_counter).with_tags(status: "noop", throttler: "Sbmt::Outbox::V2::PollThrottler::RedisQueueSize", name: "inbox_item", type: :inbox, worker_name: "poller", worker_version: 2).by(1) .and update_yabeda_gauge(Yabeda.box_worker.redis_job_queue_size).with_tags(throttler: "Sbmt::Outbox::V2::PollThrottler::RedisQueueSize", name: "inbox_item", type: :inbox, worker_name: "poller", worker_version: 2).with(6) .and measure_yabeda_histogram(Yabeda.box_worker.poll_throttling_runtime).with_tags(throttler: "Sbmt::Outbox::V2::PollThrottler::RedisQueueSize", name: "inbox_item", type: :inbox, worker_name: "poller", worker_version: 2) end end context "when max_size is defined" do it "does not wait if queue size is less than max_size" do allow(redis).to receive(:call).with("LLEN", task.redis_queue).and_return("2") expect(throttler).not_to receive(:sleep) expect { throttler.call(0, task, nil) } .to increment_yabeda_counter(Yabeda.box_worker.poll_throttling_counter).with_tags(status: "noop", throttler: "Sbmt::Outbox::V2::PollThrottler::RedisQueueSize", name: "inbox_item", type: :inbox, worker_name: "poller", worker_version: 2).by(1) .and update_yabeda_gauge(Yabeda.box_worker.redis_job_queue_size).with_tags(throttler: "Sbmt::Outbox::V2::PollThrottler::RedisQueueSize", name: "inbox_item", type: :inbox, worker_name: "poller", worker_version: 2).with(2) .and measure_yabeda_histogram(Yabeda.box_worker.poll_throttling_runtime).with_tags(throttler: "Sbmt::Outbox::V2::PollThrottler::RedisQueueSize", name: "inbox_item", type: :inbox, worker_name: "poller", worker_version: 2) end it "waits if queue size is above max_size" do allow(redis).to receive(:call).with("LLEN", task.redis_queue).and_return("12") expect(throttler).to receive(:sleep).with(delay) expect { throttler.call(0, task, nil) } .to increment_yabeda_counter(Yabeda.box_worker.poll_throttling_counter).with_tags(status: "skip", throttler: "Sbmt::Outbox::V2::PollThrottler::RedisQueueSize", name: "inbox_item", type: :inbox, worker_name: "poller", worker_version: 2).by(1) .and update_yabeda_gauge(Yabeda.box_worker.redis_job_queue_size).with_tags(throttler: "Sbmt::Outbox::V2::PollThrottler::RedisQueueSize", name: "inbox_item", type: :inbox, worker_name: "poller", worker_version: 2).with(12) .and measure_yabeda_histogram(Yabeda.box_worker.poll_throttling_runtime).with_tags(throttler: "Sbmt::Outbox::V2::PollThrottler::RedisQueueSize", name: "inbox_item", type: :inbox, worker_name: "poller", worker_version: 2) end end context "when redis command returns nil" do it "skips wait logic" do allow(redis).to receive(:call).with("LLEN", task.redis_queue).and_return(nil) expect(throttler).not_to receive(:sleep) expect { throttler.call(0, task, nil) } .to increment_yabeda_counter(Yabeda.box_worker.poll_throttling_counter).with_tags(status: "noop", throttler: "Sbmt::Outbox::V2::PollThrottler::RedisQueueSize", name: "inbox_item", type: :inbox, worker_name: "poller", worker_version: 2).by(1) .and update_yabeda_gauge(Yabeda.box_worker.redis_job_queue_size).with_tags(throttler: "Sbmt::Outbox::V2::PollThrottler::RedisQueueSize", name: "inbox_item", type: :inbox, worker_name: "poller", worker_version: 2).with(0) .and measure_yabeda_histogram(Yabeda.box_worker.poll_throttling_runtime).with_tags(throttler: "Sbmt::Outbox::V2::PollThrottler::RedisQueueSize", name: "inbox_item", type: :inbox, worker_name: "poller", worker_version: 2) end end context "when redis command raises exception" do it "skips wait logic" do allow(redis).to receive(:call).with("LLEN", task.redis_queue).and_raise("connection error") expect(throttler).not_to receive(:sleep) expect { throttler.call(0, task, nil) } .to increment_yabeda_counter(Yabeda.box_worker.poll_throttling_counter).with_tags(status: "connection error", throttler: "Sbmt::Outbox::V2::PollThrottler::RedisQueueSize", name: "inbox_item", type: :inbox, worker_name: "poller", worker_version: 2).by(1) .and not_update_yabeda_gauge(Yabeda.box_worker.redis_job_queue_size) .and measure_yabeda_histogram(Yabeda.box_worker.poll_throttling_runtime).with_tags(throttler: "Sbmt::Outbox::V2::PollThrottler::RedisQueueSize", name: "inbox_item", type: :inbox, worker_name: "poller", 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/poll_throttler/redis_queue_time_lag_spec.rb
spec/lib/sbmt/outbox/v2/poll_throttler/redis_queue_time_lag_spec.rb
# frozen_string_literal: true require "sbmt/outbox/v2/poller" require "sbmt/outbox/v2/poll_throttler/redis_queue_time_lag" describe Sbmt::Outbox::V2::PollThrottler::RedisQueueTimeLag do let(:delay) { 0.1 } let(:min_lag) { 5 } let(:task) do Sbmt::Outbox::V2::Tasks::Poll.new( item_class: InboxItem, worker_name: "poller", partition: 0, buckets: [0, 2] ) end let(:redis) { instance_double(RedisClient) } let(:throttler) { described_class.new(redis: redis, min_lag: min_lag, delay: delay) } it "does not wait if lag is above min_lag" do allow(redis).to receive(:call).with("LINDEX", task.redis_queue, -1).and_return("0:#{Time.current.to_i - 10}:1,2,3") expect(throttler).not_to receive(:sleep) expect { throttler.call(0, task, nil) } .to increment_yabeda_counter(Yabeda.box_worker.poll_throttling_counter).with_tags(status: "noop", throttler: "Sbmt::Outbox::V2::PollThrottler::RedisQueueTimeLag", name: "inbox_item", type: :inbox, worker_name: "poller", worker_version: 2).by(1) .and update_yabeda_gauge(Yabeda.box_worker.redis_job_queue_time_lag).with_tags(throttler: "Sbmt::Outbox::V2::PollThrottler::RedisQueueTimeLag", name: "inbox_item", type: :inbox, worker_name: "poller", worker_version: 2).with(10) .and measure_yabeda_histogram(Yabeda.box_worker.poll_throttling_runtime).with_tags(throttler: "Sbmt::Outbox::V2::PollThrottler::RedisQueueTimeLag", name: "inbox_item", type: :inbox, worker_name: "poller", worker_version: 2) end it "waits if lag is less than min_lag" do allow(redis).to receive(:call).with("LINDEX", task.redis_queue, -1).and_return("0:#{Time.current.to_i - 2}:1,2,3") expect(throttler).to receive(:sleep).with(delay) expect { throttler.call(0, task, nil) } .to increment_yabeda_counter(Yabeda.box_worker.poll_throttling_counter).with_tags(status: "skip", throttler: "Sbmt::Outbox::V2::PollThrottler::RedisQueueTimeLag", name: "inbox_item", type: :inbox, worker_name: "poller", worker_version: 2).by(1) .and update_yabeda_gauge(Yabeda.box_worker.redis_job_queue_time_lag).with_tags(throttler: "Sbmt::Outbox::V2::PollThrottler::RedisQueueTimeLag", name: "inbox_item", type: :inbox, worker_name: "poller", worker_version: 2).with(2) .and measure_yabeda_histogram(Yabeda.box_worker.poll_throttling_runtime).with_tags(throttler: "Sbmt::Outbox::V2::PollThrottler::RedisQueueTimeLag", name: "inbox_item", type: :inbox, worker_name: "poller", worker_version: 2) end it "skips wait logic if redis command returns nil" do allow(redis).to receive(:call).with("LINDEX", task.redis_queue, -1).and_return(nil) expect(throttler).not_to receive(:sleep) expect { throttler.call(0, task, nil) } .to increment_yabeda_counter(Yabeda.box_worker.poll_throttling_counter).with_tags(status: "noop", throttler: "Sbmt::Outbox::V2::PollThrottler::RedisQueueTimeLag", name: "inbox_item", type: :inbox, worker_name: "poller", worker_version: 2).by(1) .and not_update_yabeda_gauge(Yabeda.box_worker.redis_job_queue_time_lag).with_tags(throttler: "Sbmt::Outbox::V2::PollThrottler::RedisQueueTimeLag", 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::RedisQueueTimeLag", name: "inbox_item", type: :inbox, worker_name: "poller", 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/composite_spec.rb
spec/lib/sbmt/outbox/v2/poll_throttler/composite_spec.rb
# frozen_string_literal: true require "sbmt/outbox/v2/poller" require "sbmt/outbox/v2/poll_throttler/composite" require "sbmt/outbox/v2/poll_throttler/rate_limited" require "sbmt/outbox/v2/poll_throttler/redis_queue_size" describe Sbmt::Outbox::V2::PollThrottler::Composite do let(:delay) { 0.1 } let(:redis) { instance_double(RedisClient) } let(:redis_throttler) { Sbmt::Outbox::V2::PollThrottler::RedisQueueSize.new(redis: redis, max_size: 10, delay: delay) } let(:throttler) do described_class.new(throttlers: [redis_throttler]) end let(:task) do Sbmt::Outbox::V2::Tasks::Poll.new( item_class: InboxItem, worker_name: "poller", partition: 0, buckets: [0, 2] ) end it "sequentially calls throttlers" do expect(redis_throttler).to receive(:sleep).with(delay) allow(redis).to receive(:call).with("LLEN", task.redis_queue).and_return("15") expect(redis_throttler).to receive(:wait).and_call_original expect { throttler.call(0, task, Sbmt::Outbox::V2::ThreadPool::PROCESSED) } .to increment_yabeda_counter(Yabeda.box_worker.poll_throttling_counter).with_tags(status: "skip", throttler: "Sbmt::Outbox::V2::PollThrottler::RedisQueueSize", 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::RedisQueueSize", name: "inbox_item", type: :inbox, worker_name: "poller", worker_version: 2) end context "with return status" do let(:failure_throttler) { instance_double(Sbmt::Outbox::V2::PollThrottler::Base) } let(:skip_throttler) { instance_double(Sbmt::Outbox::V2::PollThrottler::Base) } let(:noop_throttler) { instance_double(Sbmt::Outbox::V2::PollThrottler::Base) } let(:throttle_throttler) { instance_double(Sbmt::Outbox::V2::PollThrottler::Base) } before do allow(failure_throttler).to receive(:call).and_return(Dry::Monads::Result::Failure.new("some err")) allow(skip_throttler).to receive(:call).and_return(Dry::Monads::Result::Success.new(Sbmt::Outbox::V2::Throttler::SKIP_STATUS)) allow(noop_throttler).to receive(:call).and_return(Dry::Monads::Result::Success.new(Sbmt::Outbox::V2::Throttler::NOOP_STATUS)) allow(throttle_throttler).to receive(:call).and_return(Dry::Monads::Result::Success.new(Sbmt::Outbox::V2::Throttler::THROTTLE_STATUS)) end it "returns skip if present" do expect(described_class.new(throttlers: [ throttle_throttler, noop_throttler, skip_throttler, failure_throttler ]).call(0, task, nil).value!).to eq(Sbmt::Outbox::V2::Throttler::SKIP_STATUS) end it "returns failure if present" do expect(described_class.new(throttlers: [ throttle_throttler, noop_throttler, failure_throttler ]).call(0, task, nil).failure).to eq("some err") end it "returns throttle if present" do expect(described_class.new(throttlers: [ throttle_throttler, noop_throttler ]).call(0, task, nil).value!).to eq(Sbmt::Outbox::V2::Throttler::THROTTLE_STATUS) 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/poll_throttler/paused_box_spec.rb
spec/lib/sbmt/outbox/v2/poll_throttler/paused_box_spec.rb
# frozen_string_literal: true require "sbmt/outbox/v2/poller" require "sbmt/outbox/v2/poll_throttler/paused_box" describe Sbmt::Outbox::V2::PollThrottler::PausedBox do let(:throttler) { described_class.new } let(:task) do Sbmt::Outbox::V2::Tasks::Poll.new( item_class: InboxItem, worker_name: "poller", partition: 0, buckets: [0, 2] ) end it "noops if box is not paused" do allow(InboxItem.config).to receive(:polling_enabled?).and_return(true) result = nil expect { result = throttler.call(0, task, Sbmt::Outbox::V2::ThreadPool::PROCESSED) } .to increment_yabeda_counter(Yabeda.box_worker.poll_throttling_counter).with_tags(status: "noop", throttler: "Sbmt::Outbox::V2::PollThrottler::PausedBox", 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::PausedBox", name: "inbox_item", type: :inbox, worker_name: "poller", worker_version: 2) expect(result.value!).to eq(Sbmt::Outbox::V2::Throttler::NOOP_STATUS) end it "skips if box is paused" do allow(InboxItem.config).to receive(:polling_enabled?).and_return(false) result = nil expect { result = throttler.call(0, task, Sbmt::Outbox::V2::ThreadPool::PROCESSED) } .to increment_yabeda_counter(Yabeda.box_worker.poll_throttling_counter).with_tags(status: "skip", throttler: "Sbmt::Outbox::V2::PollThrottler::PausedBox", 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::PausedBox", name: "inbox_item", type: :inbox, worker_name: "poller", worker_version: 2) expect(result.value!).to eq(Sbmt::Outbox::V2::Throttler::SKIP_STATUS) 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/config/schked_spec.rb
spec/config/schked_spec.rb
# frozen_string_literal: true require "rails_helper" describe Schked do let(:worker) { described_class.worker.tap(&:pause) } let(:time_zone) { "UTC" } around do |ex| Time.use_zone(time_zone) do travel_to(start_time, &ex) end end describe "Sbmt::Outbox::DeleteStaleOutboxItemsJob" do let(:job) { worker.job("Sbmt::Outbox::DeleteStaleOutboxItemsJob") } let(:start_time) { Time.zone.local(2008, 9, 1, 2, 30, 10) } let(:next_ten_mins) { Time.zone.local(2008, 9, 1, 2, 40, 10) } it "executes every 10 minutes" do expect(job.next_time.to_local_time).to eq(next_ten_mins) end it "enqueues job" do expect { job.call(false) }.to have_enqueued_job(Sbmt::Outbox::DeleteStaleOutboxItemsJob).exactly(:twice) end end describe "Sbmt::Outbox::DeleteStaleInboxItemsJob" do let(:job) { worker.job("Sbmt::Outbox::DeleteStaleInboxItemsJob") } let(:start_time) { Time.zone.local(2008, 9, 1, 2, 30, 10) } let(:next_ten_mins) { Time.zone.local(2008, 9, 1, 2, 40, 10) } it "executes every 10 minutes" do expect(job.next_time.to_local_time).to eq(next_ten_mins) end it "enqueues job" do expect { job.call(false) }.to have_enqueued_job(Sbmt::Outbox::DeleteStaleInboxItemsJob) 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/lib/sbmt-outbox.rb
lib/sbmt-outbox.rb
# frozen_string_literal: true require_relative "sbmt/outbox"
ruby
MIT
6da9ae3ea0333ae3ad58983c035bc95bd739aaf4
2026-01-04T17:51:44.997823Z
false
Kuper-Tech/sbmt-outbox
https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/lib/generators/outbox.rb
lib/generators/outbox.rb
# frozen_string_literal: true require "rails/generators" require_relative "helpers" module Outbox module Generators class Base < Rails::Generators::Base include Helpers::Config include Helpers::Initializer include Helpers::Paas end class NamedBase < Rails::Generators::NamedBase include Helpers::Config include Helpers::Initializer include Helpers::Items include Helpers::Migration include Helpers::Paas include Helpers::Values 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/lib/generators/helpers.rb
lib/generators/helpers.rb
# frozen_string_literal: true require_relative "helpers/config" require_relative "helpers/initializer" require_relative "helpers/items" require_relative "helpers/migration" require_relative "helpers/paas" require_relative "helpers/values"
ruby
MIT
6da9ae3ea0333ae3ad58983c035bc95bd739aaf4
2026-01-04T17:51:44.997823Z
false
Kuper-Tech/sbmt-outbox
https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/lib/generators/outbox/item/item_generator.rb
lib/generators/outbox/item/item_generator.rb
# frozen_string_literal: true require "generators/outbox" module Outbox module Generators class ItemGenerator < NamedBase source_root File.expand_path("templates", __dir__) class_option :kind, type: :string, desc: "Either inbox or outbox", banner: "inbox/outbox", required: true class_option :skip_migration, type: :boolean, default: false, desc: "Skip creating migration" class_option :skip_model, type: :boolean, default: false, desc: "Skip creating model class" class_option :skip_config, type: :boolean, default: false, desc: "Skip modifying config/outbox.yml" class_option :skip_values, type: :boolean, default: false, desc: "Skip modifying configs/values.yaml" def check_kind! return if options[:kind].in?(%w[inbox outbox]) raise Rails::Generators::Error, "Unknown item kind. " \ "Please specify `--kind inbox` or `--kind outbox`" end def check! check_config! end def validate_item_name return if file_name.underscore.match?(%r{#{options[:kind]}_item$}) continue = yes?( "Warning: your item's name doesn't match the conventional" \ " name format (i.e. Some#{options[:kind].camelize}Item). Continue?" ) return if continue raise Rails::Generators::Error, "Aborting" end def create_migration return if options[:skip_migration] create_migration_file(migration_class_name, migration_table_name) end def create_model return if options[:skip_model] template "#{options[:kind]}_item.rb", File.join("app/models", "#{item_path}.rb") end def patch_config return if options[:skip_config] item_template_data = if options[:kind] == "inbox" <<~RUBY #{item_path}: partition_size: 1 partition_strategy: hash retention: P1W max_retries: 7 retry_strategies: - exponential_backoff # # see README to learn more about transport configuration # transports: {} RUBY else <<~RUBY #{item_path}: partition_size: 1 partition_strategy: number retention: P3D max_retries: 7 retry_strategies: - exponential_backoff # # see README to learn more about transport configuration # transports: {} RUBY end add_item_to_config("#{options[:kind]}_items", item_template_data) end def patch_values return if options[:skip_values] return unless paas_app? # e.g. order/inbox_item => inbox-order-inbox-items deployment_name = "#{options[:kind]}-" + dasherize_item(item_path) add_item_to_values(deployment_name.pluralize, item_path) 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/lib/generators/outbox/transport/transport_generator.rb
lib/generators/outbox/transport/transport_generator.rb
# frozen_string_literal: true require "generators/outbox" module Outbox module Generators class TransportGenerator < NamedBase source_root File.expand_path("templates", __dir__) argument :transport, required: true, type: :string, banner: "sbmt/kafka_producer" class_option :kind, type: :string, desc: "Either inbox or outbox", banner: "inbox/outbox", required: true class_option :topic, type: :string, banner: "my-topic-name" class_option :source, type: :string, banner: "kafka" class_option :target, type: :string, banner: "order" class_option :event_name, type: :string, default: "", banner: "order_created" def check_name! return if options[:kind].in?(%w[inbox outbox]) raise Rails::Generators::Error, "Unknown transport type. Should be inbox or outbox" end def check! check_config! end def check_item_exists! return if item_exists? raise Rails::Generators::Error, "Item `#{item_name}` does not exist in the `#{options[:kind]}_items` " \ "section of #{CONFIG_PATH}. You may insert this item by running " \ "`bin/rails g outbox:item #{item_name} --kind #{options[:kind]}`" end def insert_transport data = optimize_indentation(template, 6) insert_into_file CONFIG_PATH, data, after: "#{item_name.underscore}:\n", force: true end private def item_name name end def item_exists? File.binread(CONFIG_PATH).match?(%r{#{options[:kind]}_items:.*#{item_name.underscore}:}m) end def template_path File.join(TransportGenerator.source_root, "#{options[:kind]}_transport.yml.erb") end def template ERB.new(File.read(template_path), trim_mode: "%-").result(binding) 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/lib/generators/outbox/install/install_generator.rb
lib/generators/outbox/install/install_generator.rb
# frozen_string_literal: true require "generators/outbox" module Outbox module Generators class InstallGenerator < Base source_root File.expand_path("templates", __dir__) class_option :skip_outboxfile, type: :boolean, default: false, desc: "Skip creating Outboxfile" class_option :skip_initializer, type: :boolean, default: false, desc: "Skip creating config/initializers/outbox.rb" class_option :skip_config, type: :boolean, default: false, desc: "Skip creating config/outbox.yml" def create_outboxfile return if options[:skip_outboxfile] copy_file "Outboxfile", "Outboxfile" end def create_initializer return if options[:skip_initializer] copy_file "outbox.rb", OUTBOX_INITIALIZER_PATH end def create_config return if options[:skip_config] copy_file "outbox.yml", CONFIG_PATH 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/lib/generators/outbox/install/templates/outbox.rb
lib/generators/outbox/install/templates/outbox.rb
# frozen_string_literal: true Rails.application.config.outbox.tap do |config| config.redis = {url: ENV.fetch("REDIS_URL", "redis://127.0.0.1:6379")} end
ruby
MIT
6da9ae3ea0333ae3ad58983c035bc95bd739aaf4
2026-01-04T17:51:44.997823Z
false
Kuper-Tech/sbmt-outbox
https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/lib/generators/helpers/items.rb
lib/generators/helpers/items.rb
# frozen_string_literal: true module Outbox module Generators module Helpers module Items def namespaced_item_class_name file_path.camelize end def item_path file_path 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/lib/generators/helpers/initializer.rb
lib/generators/helpers/initializer.rb
# frozen_string_literal: true module Outbox module Generators module Helpers module Initializer OUTBOX_INITIALIZER_PATH = "config/initializers/outbox.rb" private def add_item_to_initializer(attr_name) template_data_with_push = <<~RUBY "#{namespaced_item_class_name}", RUBY template_data_with_append = <<~RUBY #{attr_name} << "#{namespaced_item_class_name}" RUBY initial_template_data = <<~RUBY #{attr_name}.push( "#{namespaced_item_class_name}" ) RUBY content = File.binread(OUTBOX_INITIALIZER_PATH) data, after = if content.match?(/^\s*#{attr_name}\.push/) [optimize_indentation(template_data_with_push, 4), /^\s*#{attr_name}\.push\(\n/] elsif content.match?(/^\s*#{attr_name}\s+<</) [optimize_indentation(template_data_with_append, 2), /^\s*#{attr_name}\s+<< ".+?\n/] else # there is no config for items, so set it up initially [optimize_indentation(initial_template_data, 2), /^Rails.application.config.outbox.tap do.+?\n/] end inject_into_file OUTBOX_INITIALIZER_PATH, data, after: after 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/lib/generators/helpers/paas.rb
lib/generators/helpers/paas.rb
# frozen_string_literal: true module Outbox module Generators module Helpers module Paas APP_MANIFEST_PATH = "configs/app.toml" private def paas_app? File.exist?(APP_MANIFEST_PATH) 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/lib/generators/helpers/values.rb
lib/generators/helpers/values.rb
# frozen_string_literal: true module Outbox module Generators module Helpers module Values VALUES_PATH = "configs/values.yaml" private def add_item_to_values(deployment_name, item_path) template_data = <<~RUBY #{deployment_name}: replicas: _default: 1 prod: 2 command: - /bin/sh - -c - exec bundle exec outbox start --box #{item_path} --concurrency 4 readinessProbe: httpGet: path: /readiness/outbox port: SET-UP-YOUR-HEALTHCHECK-PORT-HERE livenessProbe: httpGet: path: /liveness/outbox port: SET-UP-YOUR-HEALTHCHECK-PORT-HERE resources: prod: requests: cpu: "500m" memory: "512Mi" limits: cpu: "1" memory: "1Gi" RUBY inject_into_file VALUES_PATH, optimize_indentation(template_data, 2), after: /^deployments:\s*\n/ end def dasherize_item(item_path) item_path.tr("/", "-").dasherize 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/lib/generators/helpers/config.rb
lib/generators/helpers/config.rb
# frozen_string_literal: true module Outbox module Generators module Helpers module Config CONFIG_PATH = "config/outbox.yml" private def config_exists? File.exist?(CONFIG_PATH) end def check_config! return if config_exists? if yes?("Seems like `config/outbox.yml` doesn't exist. Would you like to generate it?") generate "outbox:install" else raise Rails::Generators::Error, "Something went wrong: `config/outbox.yml` is missing. " \ "Please generate one by running `bin/rails g outbox:install` " \ "or add it manually." end end def add_item_to_config(config_block_name, item_template_data) template_data_with_parent = <<~RUBY #{config_block_name}: #{optimize_indentation(item_template_data, 2)} RUBY data, after = if File.binread(CONFIG_PATH).match?(/^\s*#{config_block_name}:/) # if config already contains non-empty/non-commented-out inbox_items/outbox_items block [optimize_indentation(item_template_data, 4), /^\s*#{config_block_name}:\s*\n/] else # there is no config for our items # so we just set it up initially [optimize_indentation(template_data_with_parent, 2), /^default:.+?\n/] end inject_into_file CONFIG_PATH, data, after: after 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/lib/generators/helpers/migration.rb
lib/generators/helpers/migration.rb
# frozen_string_literal: true module Outbox module Generators module Helpers module Migration private def create_migration_file(migration_class_name, migration_table_name) return false if find_existing_migration(migration_class_name.tableize) result = generate "rails:migration", migration_class_name, "--no-timestamps" return unless result migration_filepath = find_existing_migration(migration_class_name.tableize) return unless migration_filepath patch_migration_with_template_data(migration_filepath, migration_table_name) end def find_existing_migration(name) base_path = "db/migrate" found_files = Dir.glob("*_#{name}.rb", base: base_path) return if found_files.size != 1 "#{base_path}/#{found_files[0]}" end def patch_migration_with_template_data(migration_filepath, table_name) data_to_replace = /^\s*create_table :#{table_name}.+?end\n/m template_data = <<~RUBY create_table :#{table_name} do |t| t.uuid :uuid, null: false t.string :event_key, null: false t.integer :bucket, null: false t.integer :status, null: false, default: 0 t.jsonb :options t.binary :payload, null: false # when using mysql the column type should be mediumblob t.integer :errors_count, null: false, default: 0 t.text :error_log t.timestamp :processed_at t.timestamps null: false end add_index :#{table_name}, :uuid, unique: true add_index :#{table_name}, [:status, :id, :bucket], algorithm: :concurrently, include: [:errors_count] add_index :#{table_name}, [:event_key, :id] add_index :#{table_name}, :created_at RUBY gsub_file(migration_filepath, data_to_replace, optimize_indentation(template_data, 4)) end def create_inbox_model_file(path) template "inbox_item.rb", File.join("app/models", "#{path}.rb") end def create_outbox_model_file(path) template "outbox_item.rb", File.join("app/models", "#{path}.rb") end def migration_class_name "Create" + namespaced_item_class_name.gsub("::", "").pluralize end def migration_table_name namespaced_item_class_name.tableize.tr("/", "_") 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/lib/sbmt/outbox.rb
lib/sbmt/outbox.rb
# frozen_string_literal: true require "rails" require "active_job" require "active_record" require "dry-initializer" require "dry-monads" require "dry/monads/do" require "yabeda" require "exponential_backoff" require "cutoff" require "http_health_check" require "redis-client" require "connection_pool" require "ostruct" begin require "sentry-rails" require_relative "outbox/middleware/sentry/tracing_batch_process_middleware" require_relative "outbox/middleware/sentry/tracing_item_process_middleware" rescue LoadError # optional dependency end begin require_relative "outbox/instrumentation/open_telemetry_loader" rescue LoadError # optional dependency end require_relative "outbox/version" require_relative "outbox/errors" require_relative "outbox/error_tracker" require_relative "outbox/logger" require_relative "outbox/database_switcher" require_relative "outbox/engine" require_relative "outbox/middleware/builder" require_relative "outbox/middleware/runner" require_relative "outbox/probes/probe" require_relative "outbox/probes/metrics" require_relative "outbox/redis_client_factory" module Sbmt module Outbox class << self attr_accessor :current_worker end module_function def config @config ||= Rails.application.config.outbox end def logger @logger ||= Sbmt::Outbox::Logger.new end def poller_config @poller_config ||= config.poller end def processor_config @processor_config ||= config.processor end def active_record_base_class @active_record_base_class ||= config.active_record_base_class.safe_constantize || ::ActiveRecord::Base end def active_job_base_class @active_job_base_class ||= config.active_job_base_class.safe_constantize || ::ActiveJob::Base end def action_controller_api_base_class @action_controller_api_base_class ||= config.action_controller_api_base_class.safe_constantize || ::ActionController::API end def action_controller_base_class @action_controller_base_class ||= config.action_controller_base_class.safe_constantize || ::ActionController::Base end def error_tracker @error_tracker ||= config.error_tracker.constantize end def database_switcher @database_switcher ||= config.database_switcher.constantize end def redis @redis ||= ConnectionPool::Wrapper.new(size: ENV.fetch("RAILS_MAX_THREADS", 5).to_i) do RedisClientFactory.build(config.redis) end end def memory_store @memory_store ||= ActiveSupport::Cache::MemoryStore.new end def outbox_item_classes @outbox_item_classes ||= if config.outbox_item_classes.empty? (yaml_config[:outbox_items] || {}).keys.map { |name| name.camelize.constantize } else config.outbox_item_classes.map(&:constantize) end end def inbox_item_classes @inbox_item_classes ||= if config.inbox_item_classes.empty? (yaml_config[:inbox_items] || {}).keys.map { |name| name.camelize.constantize } else config.inbox_item_classes.map(&:constantize) end end def item_classes @item_classes ||= outbox_item_classes + inbox_item_classes end def item_classes_by_name @item_classes_by_name ||= item_classes.index_by(&:box_name) end def yaml_config return @yaml_config if defined?(@yaml_config) paths = if config.paths.empty? [Rails.root.join("config/outbox.yml").to_s] else config.paths end @yaml_config = paths.each_with_object({}.with_indifferent_access) do |path, memo| memo.deep_merge!( load_yaml(path) ) end end def load_yaml(path) data = if Gem::Version.new(Psych::VERSION) >= Gem::Version.new("4.0.0") YAML.safe_load(ERB.new(File.read(path)).result, aliases: true) else YAML.safe_load(ERB.new(File.read(path)).result, [], [], true) end data .with_indifferent_access .fetch(Rails.env, {}) end def batch_process_middlewares @batch_process_middlewares ||= config.batch_process_middlewares.map(&:constantize) end def item_process_middlewares @item_process_middlewares ||= config.item_process_middlewares.map(&:constantize) end def create_item_middlewares @create_item_middlewares ||= config.create_item_middlewares.map(&:constantize) end def create_batch_middlewares @create_batch_middlewares ||= config.create_batch_middlewares.map(&:constantize) end def polling_item_middlewares @polling_item_middlewares ||= config.polling_item_middlewares.map(&:constantize) 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/lib/sbmt/outbox/version.rb
lib/sbmt/outbox/version.rb
# frozen_string_literal: true module Sbmt module Outbox VERSION = "7.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/lib/sbmt/outbox/logger.rb
lib/sbmt/outbox/logger.rb
# frozen_string_literal: true module Sbmt module Outbox class Logger delegate :logger, to: :Rails def log_debug(message, **params) with_tags(**params) do logger.debug(message) end end def log_info(message, **params) with_tags(**params) do logger.info(message) end end def log_error(message, **params) with_tags(**params) do logger.error(message) end end def log_success(message, **params) log_info(message, status: "success", **params) end def log_failure(message, **params) log_error(message, status: "failure", **params) end def with_tags(**params) logger.tagged(**params) 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/lib/sbmt/outbox/errors.rb
lib/sbmt/outbox/errors.rb
# frozen_string_literal: true module Sbmt module Outbox class Error < StandardError end class ConfigError < Error end class DatabaseError < Error 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/lib/sbmt/outbox/error_tracker.rb
lib/sbmt/outbox/error_tracker.rb
# frozen_string_literal: true module Sbmt module Outbox class ErrorTracker class << self def error(message, params = {}) unless defined?(Sentry) Outbox.logger.log_error(message, **params) return end Sentry.with_scope do |scope| scope.set_contexts(contexts: params) if message.is_a?(Exception) Sentry.capture_exception(message, level: :error) else Sentry.capture_message(message, level: :error) end 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/lib/sbmt/outbox/redis_client_factory.rb
lib/sbmt/outbox/redis_client_factory.rb
# frozen_string_literal: true module Sbmt module Outbox module RedisClientFactory def self.build(options) options = options.deep_symbolize_keys unless options.key?(:reconnect_attempts) options[:reconnect_attempts] = 3 end if options.key?(:sentinels) if (url = options.delete(:url)) uri = URI.parse(url) if !options.key?(:name) && uri.host options[:name] = uri.host end if !options.key?(:password) && uri.password && !uri.password.empty? options[:password] = uri.password end if !options.key?(:username) && uri.user && !uri.user.empty? options[:username] = uri.user end end RedisClient.sentinel(**options).new_client else RedisClient.config(**options).new_client 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/lib/sbmt/outbox/enum_refinement.rb
lib/sbmt/outbox/enum_refinement.rb
# frozen_string_literal: true module Sbmt module Outbox module EnumRefinement refine ActiveRecord::Base.singleton_class do def enum(name, values = nil) if Rails::VERSION::MAJOR >= 7 super else super(name => values) 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/lib/sbmt/outbox/ascii_art.rb
lib/sbmt/outbox/ascii_art.rb
# frozen_string_literal: true module Sbmt module Outbox module AsciiArt module_function def logo <<~'TEXT' @@@@@@@ @* @.@@ @ - @ @@@@@@@ .@@@@ ##.#=. #### @@ .-@ @ *#.#-. -## * # #* @@=.#* @@@ *#.#-. ##- +# ### @+ @@-@@ *#.#-. . ## .# ## %@# # ## #-. # -##. ##### # .# . ..## . .## # # #### ## :==# #+ ### ### *# # # # -# #### :#=. @@ @@@ @ @@@ @@ .:#- ## ## # ####### ### .##: @@ @ @ @@ .##+ ### .###### ##.. ###. @ @@@@@ @@@@@ @@@@@ @ .*## . :##. # +### * @@@@@@@@ @@@ @@@ @@@ @@@@@@@@ ## .###= *# # :## @@@@%%%%@@@@@@@ @ @ @ @@@@@@@%%%%@@@@ ##. +# # @@@@%%%%%%%%%%%@@@@@@@= =@@@@@@@%%%%%%%%%%%@@@@ +# # -@@@@@@@%%%%%%%%%%%%@@@@@@ @@@@@@%%%%%%%%%%%%@@@@@@@- +# #. :@@@@@@@%%%%%%@@@- @ @ @@@@%%%%%%@@@@@@@# .+ ################### @@- *@@@@@@@@@ @@@ @# @@@@@@@@@@ :@ ###################+ #. ... @@@@@@@@ @@@ + @@ @@@ : @@@ :-* @@@ .. .. .+ # -##* -###: @ @ @@@ -@@.@@ @ @#@ :*- @ #@@@.: +@ -###: .### +# # .#...:*# @ @@@@@@@ .@@# @@+@ @*@%+ @@=@+ @@%# @ ## :.# # +# # -##.-: ## @ @@@@@@ @@@@@= @@%@ @#*@@ *@@@. ##@@ @ # +.-.#. + ### ##- @ @@ @% : @@@@@@ @* @@#- :@@@= =## @ ##+ ###+ # @@@ @@@@ @@ @@@ @ @ @* @%@@ .@@ :@@@@@@ .- +*@*- %@@ =% @%@.=@ @ @@ @#+ *@@@@ @@@% @@@ @ @@@ @@@@@@:@ @ @@ @@@@@@ .@..# @ @ @..@ +. @ ######################### @@@@ @@@@ ##########################=%@ #.@= @ @@@@@ # # @@@@@@ # # @@@@@@ # # @@@@@ @@ @#% @ ###################### @@@ ###################### @@ @*@ @@ @@ @#@--@ @@@@@ @@ @#@ @@ @@@@@@ ####################### @@@ ######################## @@@@@ @@@@@ @@@@@ @@@@@@@ @@@@@@@ @@@@@ @@ @@@@@ @@@@@@@@@@ @@@ @@ @@@@@ @@@ @@@ @@@ @@@ @@@@@@@ @@ @@@@@ @@@@@@@ @@@ @@@ @@@@@ @@@@@@@ @@@ @@@ @@@ @@@ @@@ @@ @@@ @@@ @@ @@@ @@@@@@@ @@@@@ @@@ @@@ @@@ @@@@ @@@ @@@ @@@ @@@ @@ @@@ @@@@@ @@@@@@@@@@ @@@@ @@@ @@@@@ @@ @@@@@ @@@@@@ @@@ @@@ @@@@@ @@@@@ @@@@@@@ @@@@@@@ @@@@@ @@@@@ TEXT end def shutdown <<~'TEXT' _ | | | |===( ) ////// |_| ||| | o o| ||| ( c ) ____ ||| \= / || \_ |||||| || | |||||| ...||__/|-" |||||| __|________|__ ||| |______________| ||| || || || || ||| || || || || -------------------|||-------------||-||------||-||------- |__> || || || || TEXT 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/lib/sbmt/outbox/cli.rb
lib/sbmt/outbox/cli.rb
# frozen_string_literal: true require "thor" require "sbmt/outbox/ascii_art" module Sbmt module Outbox class CLI < Thor def self.exit_on_failure? true end default_command :start desc "start", "Start outbox worker" option :box, aliases: "-b", repeatable: true, desc: "Outbox/Inbox processors to start in format foo_name:1,2,n bar_name:1,2,n" option :concurrency, aliases: "-c", type: :numeric, desc: "Number of threads (processor)" option :poll_concurrency, aliases: "-p", type: :numeric, desc: "Number of poller partitions" option :poll_threads, aliases: "-n", type: :numeric, desc: "Number of threads (poller)" option :poll_tactic, aliases: "-t", type: :string, desc: "Poll tactic: [default, low-priority, aggressive]" def start load_environment boxes = format_boxes(options[:box]) check_deprecations!(boxes) worker = Sbmt::Outbox::V2::Worker.new( boxes: boxes, poll_tactic: options[:poll_tactic], poller_threads_count: options[:poll_threads], poller_partitions_count: options[:poll_concurrency], processor_concurrency: options[:concurrency] || 4 ) Sbmt::Outbox.current_worker = worker watch_signals(worker) $stdout.puts AsciiArt.logo $stdout.puts "Outbox/Inbox worker has been started" $stdout.puts "Version: #{VERSION}" Sbmt::Outbox::Probes::Probe.run_probes Sbmt::Outbox::Probes::Metrics.run_metrics worker.start end private def check_deprecations!(boxes) boxes.each do |item_class| next if item_class.config.partition_size_raw.blank? raise "partition_size option is invalid and cannot be used with worker v2, please remove it from config/outbox.yml for #{item_class.name.underscore}" end end def load_environment load(lookup_outboxfile) require "sbmt/outbox" require "sbmt/outbox/v2/worker" end def lookup_outboxfile file_path = ENV["OUTBOXFILE"] || "#{Dir.pwd}/Outboxfile" raise "Cannot locate Outboxfile at #{file_path}" unless File.exist?(file_path) file_path end def format_boxes(val) if val.nil? fetch_all_boxes else extract_boxes(val) end end def fetch_all_boxes Outbox.outbox_item_classes + Outbox.inbox_item_classes end def extract_boxes(boxes) boxes.map do |name, acc| item_class = Sbmt::Outbox.item_classes_by_name[name] raise "Cannot locate box #{name}" unless item_class item_class end end def watch_signals(worker) # ctrl+c Signal.trap("INT") do $stdout.puts AsciiArt.shutdown $stdout.puts "Going to shut down..." worker.stop end # normal kill with number 15 Signal.trap("TERM") do $stdout.puts AsciiArt.shutdown $stdout.puts "Going to shut down..." worker.stop end # normal kill with number 3 Signal.trap("SIGQUIT") do $stdout.puts AsciiArt.shutdown $stdout.puts "Going to shut down..." worker.stop 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/lib/sbmt/outbox/database_switcher.rb
lib/sbmt/outbox/database_switcher.rb
# frozen_string_literal: true module Sbmt module Outbox class DatabaseSwitcher def self.use_slave yield end def self.use_master yield 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/lib/sbmt/outbox/engine.rb
lib/sbmt/outbox/engine.rb
# frozen_string_literal: true require "rails/engine" module Sbmt module Outbox class Engine < Rails::Engine isolate_namespace Sbmt::Outbox config.outbox = ActiveSupport::OrderedOptions.new.tap do |c| c.active_record_base_class = "ApplicationRecord" c.active_job_base_class = "ApplicationJob" c.action_controller_api_base_class = "ActionController::API" # We cannot use ApplicationController because often it could be inherited from ActionController::API c.action_controller_base_class = "ActionController::Base" c.error_tracker = "Sbmt::Outbox::ErrorTracker" c.outbox_item_classes = [] c.inbox_item_classes = [] c.paths = [] c.disposable_transports = false c.redis = {url: ENV.fetch("REDIS_URL", "redis://127.0.0.1:6379")} c.ui = ActiveSupport::OrderedOptions.new.tap do |c| c.serve_local = false c.local_endpoint = "http://localhost:5173" c.cdn_url = "https://cdn.jsdelivr.net/npm/sbmt-outbox-ui@0.0.8/dist/assets/index.js" end c.process_items = ActiveSupport::OrderedOptions.new.tap do |c| c.general_timeout = 180 c.cutoff_timeout = 90 c.batch_size = 200 end # worker v2 c.poller = ActiveSupport::OrderedOptions.new.tap do |pc| pc.concurrency = 6 pc.threads_count = 2 pc.general_timeout = 60 pc.regular_items_batch_size = 200 pc.retryable_items_batch_size = 100 pc.tactic = "default" pc.rate_limit = 60 pc.rate_interval = 60 pc.min_queue_size = 10 pc.max_queue_size = 100 pc.min_queue_timelag = 5 pc.queue_delay = 0.1 end c.processor = ActiveSupport::OrderedOptions.new.tap do |pc| pc.threads_count = 4 pc.general_timeout = 180 pc.cutoff_timeout = 90 pc.brpop_delay = 1 end c.database_switcher = "Sbmt::Outbox::DatabaseSwitcher" c.batch_process_middlewares = [] c.item_process_middlewares = [] c.create_item_middlewares = [] c.create_batch_middlewares = [] c.polling_item_middlewares = [] if defined?(::Sentry) c.batch_process_middlewares.push("Sbmt::Outbox::Middleware::Sentry::TracingBatchProcessMiddleware") c.item_process_middlewares.push("Sbmt::Outbox::Middleware::Sentry::TracingItemProcessMiddleware") end if defined?(ActiveSupport::ExecutionContext) require_relative "middleware/execution_context/context_item_process_middleware" c.item_process_middlewares.push("Sbmt::Outbox::Middleware::ExecutionContext::ContextItemProcessMiddleware") end end rake_tasks do load "sbmt/outbox/tasks/retry_failed_items.rake" load "sbmt/outbox/tasks/delete_failed_items.rake" load "sbmt/outbox/tasks/delete_items.rake" load "sbmt/outbox/tasks/update_status_items.rake" 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/lib/sbmt/outbox/middleware/runner.rb
lib/sbmt/outbox/middleware/runner.rb
# frozen_string_literal: true module Sbmt module Outbox module Middleware class Runner attr_reader :stack def initialize(stack) @stack = stack end def call(*args) return yield if stack.empty? chain = stack.map { |i| i.new } traverse_chain = proc do if chain.empty? yield else chain.shift.call(*args, &traverse_chain) end end traverse_chain.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/lib/sbmt/outbox/middleware/builder.rb
lib/sbmt/outbox/middleware/builder.rb
# frozen_string_literal: true module Sbmt module Outbox module Middleware class Builder def initialize(middlewares) middlewares.each { |middleware| stack << middleware } end def call(...) Runner.new(stack.dup).call(...) end private def stack @stack ||= [] 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/lib/sbmt/outbox/middleware/sentry/transaction.rb
lib/sbmt/outbox/middleware/sentry/transaction.rb
# frozen_string_literal: true module Sbmt module Outbox module Middleware module Sentry module Transaction def start_sentry_transaction(scope, op, name, tags = {}) trace_id = SecureRandom.base58 scope&.set_tags(tags.merge(trace_id: trace_id)) transaction = ::Sentry.start_transaction(op: op, name: name) scope&.set_span(transaction) if transaction transaction end def finish_sentry_transaction(scope, transaction, status) return unless transaction transaction.set_http_status(status) transaction.finish scope.clear 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/lib/sbmt/outbox/middleware/sentry/tracing_batch_process_middleware.rb
lib/sbmt/outbox/middleware/sentry/tracing_batch_process_middleware.rb
# frozen_string_literal: true require "sbmt/outbox/middleware/sentry/transaction" module Sbmt module Outbox module Middleware module Sentry class TracingBatchProcessMiddleware include Transaction def call(job) return yield unless ::Sentry.initialized? scope = ::Sentry.get_current_scope # transaction will be nil if sentry tracing is not enabled transaction = start_transaction(scope, job) begin result = yield rescue finish_sentry_transaction(scope, transaction, 500) raise end finish_sentry_transaction(scope, transaction, 200) result end private def start_transaction(scope, job) start_sentry_transaction(scope, op(job), transaction_name(job), job.log_tags) end def op(job) "sbmt.#{job.log_tags[:box_type]&.downcase}.batch_process" end def transaction_name(job) "Sbmt.#{job.log_tags[:box_type]&.capitalize}.#{job.log_tags[:box_name]&.capitalize}" 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/lib/sbmt/outbox/middleware/sentry/tracing_item_process_middleware.rb
lib/sbmt/outbox/middleware/sentry/tracing_item_process_middleware.rb
# frozen_string_literal: true require "sbmt/outbox/middleware/sentry/transaction" module Sbmt module Outbox module Middleware module Sentry class TracingItemProcessMiddleware include Transaction attr_reader :new_transaction def call(item) return yield unless ::Sentry.initialized? scope = ::Sentry.get_current_scope # transaction will be nil if sentry tracing is not enabled transaction = scope&.get_transaction || start_transaction(scope, item.class) span = transaction&.start_child(op: op(item.class), description: "Starting item processing") span&.set_data(:item_id, item.id) begin result = yield rescue finish_span(span, 500) finish_sentry_transaction(scope, transaction, 500) if new_transaction raise end finish_span(span, 200) finish_sentry_transaction(scope, transaction, 200) if new_transaction result end private def finish_span(span, status) return unless span span.set_data(:status, status) span.finish end def start_transaction(scope, item_class) @new_transaction = true start_sentry_transaction(scope, op(item_class), transaction_name(item_class), tags(item_class)) end def transaction_name(item_class) "Sbmt.#{item_class.box_type.capitalize}.#{item_class.box_name.capitalize}" end def tags(item_class) {box_type: item_class.box_type, box_name: item_class.box_name} end def op(item_class) "sbmt.#{item_class.box_type.downcase}.item_process" 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/lib/sbmt/outbox/middleware/open_telemetry/tracing_create_batch_middleware.rb
lib/sbmt/outbox/middleware/open_telemetry/tracing_create_batch_middleware.rb
# frozen_string_literal: true module Sbmt module Outbox module Middleware module OpenTelemetry class TracingCreateBatchMiddleware def call(item_class, batch_attributes) return yield unless defined?(::OpenTelemetry) span_attributes = { "messaging.system" => "outbox", "messaging.outbox.box_type" => item_class.box_type.to_s, "messaging.outbox.box_name" => item_class.box_name, "messaging.outbox.owner" => item_class.owner, "messaging.destination" => item_class.name, "messaging.destination_kind" => "database" } tracer.in_span(span_name(item_class), attributes: span_attributes.compact, kind: :producer) do batch_attributes.each do |item_attributes| options = item_attributes[:options] ||= {} headers = options[:headers] || options["headers"] || {} ::OpenTelemetry.propagation.inject(headers) end yield end end private def tracer ::Sbmt::Outbox::Instrumentation::OpenTelemetryLoader.instance.tracer end def span_name(item_class) "#{item_class.box_type}/#{item_class.box_name} create batch" 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/lib/sbmt/outbox/middleware/open_telemetry/tracing_create_item_middleware.rb
lib/sbmt/outbox/middleware/open_telemetry/tracing_create_item_middleware.rb
# frozen_string_literal: true module Sbmt module Outbox module Middleware module OpenTelemetry class TracingCreateItemMiddleware def call(item_class, item_attributes) return yield unless defined?(::OpenTelemetry) span_attributes = { "messaging.system" => "outbox", "messaging.outbox.box_type" => item_class.box_type.to_s, "messaging.outbox.box_name" => item_class.box_name, "messaging.outbox.owner" => item_class.owner, "messaging.destination" => item_class.name, "messaging.destination_kind" => "database" } options = item_attributes[:options] ||= {} headers = options[:headers] || options["headers"] headers ||= options[:headers] ||= {} tracer.in_span(span_name(item_class), attributes: span_attributes.compact, kind: :producer) do ::OpenTelemetry.propagation.inject(headers) yield end end private def tracer ::Sbmt::Outbox::Instrumentation::OpenTelemetryLoader.instance.tracer end def span_name(item_class) "#{item_class.box_type}/#{item_class.box_name} create item" 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/lib/sbmt/outbox/middleware/open_telemetry/tracing_item_process_middleware.rb
lib/sbmt/outbox/middleware/open_telemetry/tracing_item_process_middleware.rb
# frozen_string_literal: true module Sbmt module Outbox module Middleware module OpenTelemetry class TracingItemProcessMiddleware def call(item) return yield unless defined?(::OpenTelemetry) item_class = item.class item_options = item.options || {} item_options_headers = item_options[:headers] || item_options["headers"] return yield unless item_class && item_options_headers span_attributes = { "messaging.system" => "outbox", "messaging.outbox.item_id" => item.id.to_s, "messaging.outbox.box_type" => item_class.box_type.to_s, "messaging.outbox.box_name" => item_class.box_name, "messaging.outbox.owner" => item_class.owner, "messaging.destination" => item_class.name, "messaging.destination_kind" => "database", "messaging.operation" => "process" } extracted_context = ::OpenTelemetry.propagation.extract(item_options_headers) ::OpenTelemetry::Context.with_current(extracted_context) do tracer.in_span(span_name(item_class), attributes: span_attributes.compact, kind: :consumer) do Sbmt::Outbox.logger.with_tags(trace_id: trace_id) do yield end end end end private def tracer ::Sbmt::Outbox::Instrumentation::OpenTelemetryLoader.instance.tracer end def span_name(item_class) "#{item_class.box_type}/#{item_class.box_name} process item" end def trace_id context = ::OpenTelemetry::Trace.current_span.context context.valid? ? context.hex_trace_id : nil 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/lib/sbmt/outbox/middleware/execution_context/context_item_process_middleware.rb
lib/sbmt/outbox/middleware/execution_context/context_item_process_middleware.rb
# frozen_string_literal: true require "sbmt/outbox/middleware/execution_context/context_item_process_middleware" module Sbmt module Outbox module Middleware module ExecutionContext class ContextItemProcessMiddleware def call(item) ActiveSupport::ExecutionContext[:box_item] = item yield 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/lib/sbmt/outbox/probes/probe.rb
lib/sbmt/outbox/probes/probe.rb
# frozen_string_literal: true module Sbmt module Outbox module Probes class Probe DEFAULT_PROBE_PORT = 5555 class << self def run_probes return unless autostart_probe? $stdout.puts "Starting probes..." ::HttpHealthCheck.run_server_async( port: probe_port, rack_app: HttpHealthCheck::RackApp.configure do |c| c.logger Rails.logger c.probe "/readiness/outbox" do |_env| code = Sbmt::Outbox.current_worker.ready? ? 200 : 500 [code, {}, ["Outbox version: #{Sbmt::Outbox::VERSION}"]] end c.probe "/liveness/outbox" do |_env| code = Sbmt::Outbox.current_worker.alive? ? 200 : 500 [code, {}, ["Outbox version: #{Sbmt::Outbox::VERSION}"]] end end ) end private def probe_port return DEFAULT_PROBE_PORT if Outbox.yaml_config["probes"].nil? Sbmt::Outbox.yaml_config.fetch(:probes).fetch(:port) end def autostart_probe? value = Sbmt::Outbox.yaml_config.dig(:probes, :enabled) value = true if value.nil? value 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/lib/sbmt/outbox/probes/metrics.rb
lib/sbmt/outbox/probes/metrics.rb
# frozen_string_literal: true require "rackup/handler/webrick" if Gem::Version.new(::Rack.release) >= Gem::Version.new("3") module Sbmt module Outbox module Probes class Metrics DEFAULT_YABEDA_PORT = 9090 DEFAULT_YABEDA_PATH = "/metrics" class << self def run_metrics return unless autostart_yabeda_server? if defined?(Yabeda) $stdout.puts "Starting metrics http-server..." start_webrick( Yabeda::Prometheus::Mmap::Exporter::NOT_FOUND_HANDLER, middlewares: {::Yabeda::Prometheus::Exporter => {path: DEFAULT_YABEDA_PATH}}, port: yabeda_port ) end end private def yabeda_port Sbmt::Outbox.yaml_config.dig(:metrics, :port) || DEFAULT_YABEDA_PORT end def start_webrick(app, middlewares:, port:) Thread.new do webrick.run( ::Rack::Builder.new do middlewares.each do |middleware, options| use middleware, **options end run app end, Host: "0.0.0.0", Port: port ) end end def webrick return ::Rack::Handler::WEBrick if Gem::Version.new(::Rack.release) < Gem::Version.new("3") ::Rackup::Handler::WEBrick end def autostart_yabeda_server? Sbmt::Outbox.yaml_config.dig(:metrics, :enabled) || false 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/lib/sbmt/outbox/metrics/utils.rb
lib/sbmt/outbox/metrics/utils.rb
# frozen_string_literal: true module Sbmt module Outbox module Metrics module Utils extend self def metric_safe(str) str.tr("/", "-") 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/lib/sbmt/outbox/v2/redis_item_meta.rb
lib/sbmt/outbox/v2/redis_item_meta.rb
# frozen_string_literal: true module Sbmt module Outbox module V2 class RedisItemMeta attr_reader :version, :timestamp, :errors_count, :error_msg CURRENT_VERSION = 1 MAX_ERROR_LEN = 200 def initialize(errors_count:, error_msg:, timestamp: Time.current.to_i, version: CURRENT_VERSION) @errors_count = errors_count @error_msg = error_msg @timestamp = timestamp @version = version end def to_s serialize end def serialize JSON.generate({ version: version, timestamp: timestamp, errors_count: errors_count, error_msg: error_msg.slice(0, MAX_ERROR_LEN) }) end def self.deserialize!(value) raise "invalid data type: string is required" unless value.is_a?(String) data = JSON.parse!(value, max_nesting: 1) new( version: data["version"], timestamp: data["timestamp"].to_i, errors_count: data["errors_count"].to_i, error_msg: data["error_msg"] ) 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/lib/sbmt/outbox/v2/poller.rb
lib/sbmt/outbox/v2/poller.rb
# frozen_string_literal: true require "redlock" require "sbmt/outbox/v2/box_processor" require "sbmt/outbox/v2/redis_job" require "sbmt/outbox/v2/poll_throttler" require "sbmt/outbox/v2/tasks/poll" module Sbmt module Outbox module V2 class Poller < BoxProcessor delegate :poller_config, :polling_item_middlewares, :logger, to: "Sbmt::Outbox" delegate :box_worker, to: "Yabeda" attr_reader :partitions_count, :lock_timeout, :regular_items_batch_size, :retryable_items_batch_size, :max_buffer_size, :max_batch_size, :throttler, :middleware_builder def initialize( boxes, partitions_count: nil, threads_count: nil, lock_timeout: nil, regular_items_batch_size: nil, retryable_items_batch_size: nil, throttler_tactic: nil, redis: nil ) @partitions_count = partitions_count || poller_config.concurrency @lock_timeout = lock_timeout || poller_config.general_timeout @regular_items_batch_size = regular_items_batch_size || poller_config.regular_items_batch_size @retryable_items_batch_size = retryable_items_batch_size || poller_config.retryable_items_batch_size @max_buffer_size = @regular_items_batch_size + @retryable_items_batch_size @max_batch_size = @regular_items_batch_size super(boxes: boxes, threads_count: threads_count || poller_config.threads_count, name: "poller", redis: redis) @throttler = PollThrottler.build(throttler_tactic || poller_config.tactic || "default", self.redis, poller_config) @middleware_builder = Middleware::Builder.new(polling_item_middlewares) end def throttle(worker_number, poll_task, result) throttler.call(worker_number, poll_task, result) end def process_task(_worker_number, task) middleware_builder.call(task) { poll(task) } end private def build_task_queue(boxes) scheduled_tasks = boxes.map do |item_class| schedule_concurrency = (0...partitions_count).to_a schedule_concurrency.map do |partition| buckets = item_class.calc_bucket_partitions(partitions_count).fetch(partition) Tasks::Poll.new( item_class: item_class, worker_name: worker_name, partition: partition, buckets: buckets ) end end.flatten scheduled_tasks.shuffle! Queue.new.tap { |queue| scheduled_tasks.each { |task| queue << task } } end def lock_task(poll_task) lock_manager.lock("#{poll_task.resource_path}:lock", lock_timeout * 1000) do |locked| lock_status = locked ? "locked" : "skipped" logger.log_debug("poller: lock for #{poll_task}: #{lock_status}") yield(locked ? poll_task : nil) end end def poll(task) lock_timer = Cutoff.new(lock_timeout) last_id = 0 box_worker.item_execution_runtime.measure(task.yabeda_labels) do Outbox.database_switcher.use_slave do result = fetch_items(task) do |item| box_worker.job_items_counter.increment(task.yabeda_labels) last_id = item.id lock_timer.checkpoint! end logger.log_debug("poll task #{task}: fetched buckets:#{result.keys.count}, items:#{result.values.sum(0) { |ids| ids.count }}") push_to_redis(task, result) if result.present? end end rescue Cutoff::CutoffExceededError box_worker.job_timeout_counter.increment(task.yabeda_labels) logger.log_info("Lock timeout while processing #{task.resource_key} at id #{last_id}") end def fetch_items(task) regular_count = 0 retryable_count = 0 # single buffer to preserve item's positions poll_buffer = {} fetch_items_with_retries(task, max_batch_size).each do |item| if item.errors_count > 0 # skip if retryable buffer capacity limit reached next if retryable_count >= retryable_items_batch_size poll_buffer[item.bucket] ||= [] poll_buffer[item.bucket] << item.id retryable_count += 1 else poll_buffer[item.bucket] ||= [] poll_buffer[item.bucket] << item.id regular_count += 1 end yield(item) end box_worker.batches_per_poll_counter.increment(task.yabeda_labels) return {} if poll_buffer.blank? # regular items have priority over retryable ones return poll_buffer if regular_count >= regular_items_batch_size # additionally poll regular items only when retryable buffer capacity limit reached # and no regular items were found if retryable_count >= retryable_items_batch_size && regular_count == 0 fetch_regular_items(task, regular_items_batch_size).each do |item| poll_buffer[item.bucket] ||= [] poll_buffer[item.bucket] << item.id yield(item) end box_worker.batches_per_poll_counter.increment(task.yabeda_labels) end poll_buffer end def fetch_items_with_retries(task, limit) task.item_class .for_processing .where(bucket: task.buckets) .order(id: :asc) .limit(limit) .select(:id, :bucket, :errors_count) end def fetch_regular_items(task, limit) task.item_class .for_processing .where(bucket: task.buckets, errors_count: 0) .order(id: :asc) .limit(limit) .select(:id, :bucket) end def push_to_redis(poll_task, ids_per_bucket) redis.pipelined do |conn| ids_per_bucket.each do |bucket, ids| redis_job = RedisJob.new(bucket, ids) logger.log_debug("pushing job to redis, items count: #{ids.count}: #{redis_job}") conn.call("LPUSH", poll_task.redis_queue, redis_job.serialize) end 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/lib/sbmt/outbox/v2/processor.rb
lib/sbmt/outbox/v2/processor.rb
# frozen_string_literal: true require "redlock" require "sbmt/outbox/v2/box_processor" require "sbmt/outbox/v2/redis_job" require "sbmt/outbox/v2/tasks/process" module Sbmt module Outbox module V2 class Processor < BoxProcessor delegate :processor_config, :batch_process_middlewares, :logger, to: "Sbmt::Outbox" attr_reader :lock_timeout, :cache_ttl, :cutoff_timeout, :brpop_delay REDIS_BRPOP_MIN_DELAY = 0.1 def initialize( boxes, threads_count: nil, lock_timeout: nil, cache_ttl: nil, cutoff_timeout: nil, brpop_delay: nil, redis: nil ) @lock_timeout = lock_timeout || processor_config.general_timeout @cache_ttl = cache_ttl || @lock_timeout * 10 @cutoff_timeout = cutoff_timeout || processor_config.cutoff_timeout @brpop_delay = brpop_delay || redis_brpop_delay(boxes.count, processor_config.brpop_delay) @redis = redis super(boxes: boxes, threads_count: threads_count || processor_config.threads_count, name: "processor", redis: redis) end def process_task(_worker_number, task) middlewares = Middleware::Builder.new(batch_process_middlewares) middlewares.call(task) { process(task) } end private def build_task_queue(boxes) # queue size is: boxes_count * threads_count # to simplify scheduling per box tasks = boxes.map do |item_class| (0...threads_count) .to_a .map { Tasks::Base.new(item_class: item_class, worker_name: worker_name) } end.flatten tasks.shuffle! Queue.new.tap { |queue| tasks.each { |task| queue << task } } end def lock_task(scheduled_task) redis_job = fetch_redis_job(scheduled_task) return yield(nil) if redis_job.blank? processor_task = Tasks::Process.new( item_class: scheduled_task.item_class, worker_name: worker_name, bucket: redis_job.bucket, ids: redis_job.ids ) lock_manager.lock("#{processor_task.resource_path}:lock", lock_timeout * 1000) do |locked| lock_status = locked ? "locked" : "skipped" logger.log_debug("processor: lock for #{processor_task}: #{lock_status}") yield(locked ? processor_task : nil) end end def process(task) lock_timer = Cutoff.new(cutoff_timeout) last_id = 0 strict_order = task.item_class.config.strict_order box_worker.item_execution_runtime.measure(task.yabeda_labels) do Outbox.database_switcher.use_master do task.ids.each do |id| result = ProcessItem.call( task.item_class, id, worker_version: task.yabeda_labels[:worker_version], cache_ttl_sec: cache_ttl, redis: @redis ) box_worker.job_items_counter.increment(task.yabeda_labels) last_id = id lock_timer.checkpoint! break if strict_order == true && result.failure? end end end rescue Cutoff::CutoffExceededError box_worker.job_timeout_counter.increment(task.yabeda_labels) logger.log_info("Lock timeout while processing #{task.resource_key} at id #{last_id}") end def fetch_redis_job(scheduled_task) _queue, result = redis.blocking_call(redis_block_timeout, "BRPOP", "#{scheduled_task.item_class.box_name}:job_queue", brpop_delay) return if result.blank? RedisJob.deserialize!(result) rescue => ex logger.log_error("error while fetching redis job: #{ex.message}") end def redis_block_timeout redis.read_timeout + brpop_delay end def redis_brpop_delay(boxes_count, default_delay) return default_delay if boxes_count == 1 REDIS_BRPOP_MIN_DELAY 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/lib/sbmt/outbox/v2/throttler.rb
lib/sbmt/outbox/v2/throttler.rb
# frozen_string_literal: true module Sbmt module Outbox module V2 module Throttler THROTTLE_STATUS = "throttle" SKIP_STATUS = "skip" NOOP_STATUS = "noop" 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/lib/sbmt/outbox/v2/thread_pool.rb
lib/sbmt/outbox/v2/thread_pool.rb
# frozen_string_literal: true module Sbmt module Outbox module V2 class ThreadPool delegate :logger, to: "Sbmt::Outbox" BREAK = Object.new.freeze SKIPPED = Object.new.freeze PROCESSED = Object.new.freeze def initialize(concurrency:, name: "thread_pool", random_startup_delay: true, start_async: true, &block) self.concurrency = concurrency self.name = name self.random_startup_delay = random_startup_delay self.start_async = start_async self.task_source = block self.task_mutex = Mutex.new self.stopped = true self.threads = Concurrent::Array.new end def next_task task_mutex.synchronize do return if stopped task = task_source.call if task == BREAK self.stopped = true return end task end end def start self.stopped = false mode = start_async ? "async" : "sync" logger.log_info("#{name}: starting #{concurrency} threads in #{mode} mode") result = run_threads do |task| logger.with_tags(worker: worker_number) do yield worker_number, task end end logger.log_info("#{name}: threads started") raise result if result.is_a?(Exception) end def stop self.stopped = true threads.map(&:join) if start_async ensure stop_threads end def running? return false if stopped true end def alive?(timeout) return false if stopped deadline = Time.current - timeout threads.all? do |thread| last_active_at = last_active_at(thread) return false unless last_active_at deadline < last_active_at end end private attr_accessor :concurrency, :name, :random_startup_delay, :task_source, :task_mutex, :stopped, :start_async, :threads def touch_worker! self.last_active_at = Time.current end def worker_number(thread = Thread.current) thread.thread_variable_get("#{name}_worker_number:#{object_id}") end def last_active_at(thread = Thread.current) thread.thread_variable_get("#{name}_last_active_at:#{object_id}") end def run_threads exception = nil in_threads do |worker_num| self.worker_number = worker_num # We don't want to start all threads at the same time sleep(rand * (worker_num + 1)) if random_startup_delay touch_worker! until exception task = next_task break unless task touch_worker! begin yield task rescue Exception => e # rubocop:disable Lint/RescueException exception = e end end end exception end def in_threads Thread.handle_interrupt(Exception => :never) do Thread.handle_interrupt(Exception => :immediate) do concurrency.times do |i| threads << Thread.new { yield(i) } end threads.map(&:value) unless start_async end ensure stop_threads unless start_async end end def stop_threads threads.each(&:kill) threads.clear end def worker_number=(num) Thread.current.thread_variable_set("#{name}_worker_number:#{object_id}", num) end def last_active_at=(at) Thread.current.thread_variable_set("#{name}_last_active_at:#{object_id}", at) 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/lib/sbmt/outbox/v2/worker.rb
lib/sbmt/outbox/v2/worker.rb
# frozen_string_literal: true require "redlock" require "sbmt/outbox/v2/poller" require "sbmt/outbox/v2/processor" module Sbmt module Outbox module V2 class Worker def initialize(boxes:, poll_tactic: nil, processor_concurrency: nil, poller_partitions_count: nil, poller_threads_count: nil) @poller = Poller.new(boxes, throttler_tactic: poll_tactic, threads_count: poller_threads_count, partitions_count: poller_partitions_count) @processor = Processor.new(boxes, threads_count: processor_concurrency) end def start start_async loop do sleep 0.1 break unless @poller.started && @processor.started end end def start_async @poller.start @processor.start loop do sleep(0.1) break if ready? end end def stop @poller.stop @processor.stop end def ready? @poller.ready? && @processor.ready? end def alive? return false unless ready? @poller.alive?(@poller.lock_timeout) && @processor.alive?(@processor.lock_timeout) 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/lib/sbmt/outbox/v2/poll_throttler.rb
lib/sbmt/outbox/v2/poll_throttler.rb
# frozen_string_literal: true require "sbmt/outbox/v2/poll_throttler/base" require "sbmt/outbox/v2/poll_throttler/composite" require "sbmt/outbox/v2/poll_throttler/rate_limited" require "sbmt/outbox/v2/poll_throttler/fixed_delay" require "sbmt/outbox/v2/poll_throttler/noop" require "sbmt/outbox/v2/poll_throttler/redis_queue_size" require "sbmt/outbox/v2/poll_throttler/redis_queue_time_lag" require "sbmt/outbox/v2/poll_throttler/paused_box" module Sbmt module Outbox module V2 module PollThrottler POLL_TACTICS = %w[noop default low-priority aggressive] def self.build(tactic, redis, poller_config) raise "WARN: invalid poller poll tactic provided: #{tactic}, available options: #{POLL_TACTICS}" unless POLL_TACTICS.include?(tactic) # no-op, for testing purposes return Noop.new if tactic == "noop" if tactic == "default" # composite of RateLimited & RedisQueueSize (upper bound only) # optimal polling performance for most cases Composite.new(throttlers: [ PausedBox.new, RedisQueueSize.new(redis: redis, max_size: poller_config.max_queue_size, delay: poller_config.queue_delay), RateLimited.new(limit: poller_config.rate_limit, interval: poller_config.rate_interval) ]) elsif tactic == "low-priority" # composite of RateLimited & RedisQueueSize (with lower & upper bounds) & RedisQueueTimeLag, # delays polling depending on min job queue size threshold # and also by min redis queue oldest item lag # optimal polling performance for low-intensity data flow Composite.new(throttlers: [ PausedBox.new, RedisQueueSize.new(redis: redis, min_size: poller_config.min_queue_size, max_size: poller_config.max_queue_size, delay: poller_config.queue_delay), RedisQueueTimeLag.new(redis: redis, min_lag: poller_config.min_queue_timelag, delay: poller_config.queue_delay), RateLimited.new(limit: poller_config.rate_limit, interval: poller_config.rate_interval) ]) elsif tactic == "aggressive" # throttles only by max job queue size, max polling performance # optimal polling performance for high-intensity data flow Composite.new(throttlers: [ PausedBox.new, RedisQueueSize.new(redis: redis, max_size: poller_config.max_queue_size, delay: poller_config.queue_delay) ]) 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/lib/sbmt/outbox/v2/redis_job.rb
lib/sbmt/outbox/v2/redis_job.rb
# frozen_string_literal: true module Sbmt module Outbox module V2 class RedisJob attr_reader :bucket, :timestamp, :ids GENERIC_SEPARATOR = ":" IDS_SEPARATOR = "," def initialize(bucket, ids, timestamp = Time.current.to_i) @bucket = bucket @ids = ids @timestamp = timestamp end def to_s serialize end def serialize [bucket, timestamp, ids.join(IDS_SEPARATOR)].join(GENERIC_SEPARATOR) end def self.deserialize!(value) raise "invalid data type: string is required" unless value.is_a?(String) bucket, ts_utc, ids_str, _ = value.split(GENERIC_SEPARATOR) raise "invalid data format: bucket or ids are not valid" if bucket.blank? || ts_utc.blank? || ids_str.blank? ts = ts_utc.to_i ids = ids_str.split(IDS_SEPARATOR).map(&:to_i) raise "invalid data format: IDs are empty" if ids.blank? new(bucket, ids, ts) 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/lib/sbmt/outbox/v2/box_processor.rb
lib/sbmt/outbox/v2/box_processor.rb
# frozen_string_literal: true require "sbmt/outbox/v2/throttler" require "sbmt/outbox/v2/thread_pool" require "sbmt/outbox/v2/tasks/default" module Sbmt module Outbox module V2 class BoxProcessor delegate :config, :logger, to: "Sbmt::Outbox" delegate :box_worker, to: "Yabeda" attr_reader :started, :threads_count, :worker_name def initialize(boxes:, threads_count:, name: "abstract_worker", redis: nil) @threads_count = threads_count @worker_name = name @queue = build_task_queue(boxes) @thread_pool = ThreadPool.new( concurrency: threads_count, name: "#{name}_thread_pool" ) do queue.pop end @started = false init_redis(redis) end def start raise "#{worker_name} is already started" if started @started = true thread_pool.start do |worker_number, scheduled_task| result = ThreadPool::PROCESSED last_result = Thread.current[:last_polling_result] throttling_res = throttle(worker_number, scheduled_task, last_result) next ThreadPool::SKIPPED if throttling_res&.value_or(nil) == Sbmt::Outbox::V2::Throttler::SKIP_STATUS lock_task(scheduled_task) do |locked_task| base_labels = scheduled_task.yabeda_labels.merge(worker_name: worker_name) if locked_task labels = base_labels.merge(locked_task.yabeda_labels) box_worker.job_execution_runtime.measure(labels) do ::Rails.application.executor.wrap do logger.with_tags(**locked_task.log_tags) do result = safe_process_task(worker_number, locked_task) end end end else result = ThreadPool::SKIPPED end box_worker.job_counter.increment(base_labels.merge(state: locked_task ? "processed" : "skipped"), by: 1) end Thread.current[:last_polling_result] = result || ThreadPool::PROCESSED ensure queue << scheduled_task end rescue => e Outbox.error_tracker.error(e) raise end def stop @started = false @thread_pool.stop end def ready? started && @thread_pool.running? end def alive?(timeout) return false unless ready? @thread_pool.alive?(timeout) end def safe_process_task(worker_number, task) process_task(worker_number, task) rescue => e log_fatal(e, task) track_fatal(e, task) end def throttle(_worker_number, _scheduled_task, _result) # noop by default # IMPORTANT: method is called from thread-pool, i.e. code must be thread-safe end def process_task(_worker_number, _task) raise NotImplementedError, "Implement #process_task for Sbmt::Outbox::V2::BoxProcessor" end private attr_accessor :queue, :thread_pool, :redis, :lock_manager def init_redis(redis) self.redis = redis || ConnectionPool::Wrapper.new(size: threads_count) { RedisClientFactory.build(config.redis) } client = if Gem::Version.new(Redlock::VERSION) >= Gem::Version.new("2.0.0") self.redis else ConnectionPool::Wrapper.new(size: threads_count) { Redis.new(config.redis) } end self.lock_manager = Redlock::Client.new([client], retry_count: 0) end def lock_task(scheduled_task) # by default there's no locking yield scheduled_task end def build_task_queue(boxes) scheduled_tasks = boxes.map do |item_class| Tasks::Default.new(item_class: item_class, worker_name: worker_name) end scheduled_tasks.shuffle! Queue.new.tap { |queue| scheduled_tasks.each { |task| queue << task } } end def log_fatal(e, task) backtrace = e.backtrace.join("\n") if e.respond_to?(:backtrace) logger.log_error( "Failed processing #{task} with error: #{e.class} #{e.message}", stacktrace: backtrace ) end def track_fatal(e, task) box_worker.job_counter.increment(task.yabeda_labels.merge(state: "failed")) Outbox.error_tracker.error(e, **task.log_tags) 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/lib/sbmt/outbox/v2/tasks/default.rb
lib/sbmt/outbox/v2/tasks/default.rb
# frozen_string_literal: true require "sbmt/outbox/v2/tasks/base" module Sbmt module Outbox module V2 module Tasks class Default < Base def to_s "#{item_class.box_type}/#{item_class.box_name}" 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/lib/sbmt/outbox/v2/tasks/poll.rb
lib/sbmt/outbox/v2/tasks/poll.rb
# frozen_string_literal: true require "sbmt/outbox/v2/tasks/base" module Sbmt module Outbox module V2 module Tasks class Poll < Base attr_reader :partition, :buckets, :resource_key, :resource_path, :redis_queue def initialize(item_class:, worker_name:, partition:, buckets:) super(item_class: item_class, worker_name: worker_name) @partition = partition @buckets = buckets @resource_key = "#{item_class.box_name}:#{partition}" @resource_path = "sbmt:outbox:#{worker_name}:#{resource_key}" @redis_queue = "#{item_class.box_name}:job_queue" @log_tags = log_tags.merge(box_partition: partition) @yabeda_labels = yabeda_labels.merge(partition: partition) end def to_s resource_path 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/lib/sbmt/outbox/v2/tasks/base.rb
lib/sbmt/outbox/v2/tasks/base.rb
# frozen_string_literal: true require "sbmt/outbox/metrics/utils" module Sbmt module Outbox module V2 module Tasks class Base attr_reader :item_class, :worker_name, :worker_version, :log_tags, :yabeda_labels delegate :owner, to: :item_class def initialize(item_class:, worker_name:, worker_version: 2) @item_class = item_class @worker_name = worker_name @worker_version = worker_version @log_tags = { box_type: item_class.box_type, box_name: item_class.box_name, worker_name: worker_name, worker_version: worker_version } @yabeda_labels = { type: item_class.box_type, name: Sbmt::Outbox::Metrics::Utils.metric_safe(item_class.box_name), owner: owner, worker_version: 2, worker_name: worker_name } end def to_h result = {} instance_variables.each do |iv| iv = iv.to_s[1..] result[iv.to_sym] = instance_variable_get(:"@#{iv}") end result 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/lib/sbmt/outbox/v2/tasks/process.rb
lib/sbmt/outbox/v2/tasks/process.rb
# frozen_string_literal: true require "sbmt/outbox/v2/tasks/base" module Sbmt module Outbox module V2 module Tasks class Process < Base attr_reader :partition, :bucket, :ids, :resource_key, :resource_path def initialize(item_class:, worker_name:, bucket:, ids:) super(item_class: item_class, worker_name: worker_name) @bucket = bucket @ids = ids @resource_key = "#{item_class.box_name}:#{bucket}" @resource_path = "sbmt:outbox:#{worker_name}:#{resource_key}" @log_tags = log_tags.merge(bucket: bucket) end def to_s resource_path 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/lib/sbmt/outbox/v2/poll_throttler/composite.rb
lib/sbmt/outbox/v2/poll_throttler/composite.rb
# frozen_string_literal: true require "sbmt/outbox/v2/poll_throttler/base" module Sbmt module Outbox module V2 module PollThrottler class Composite < Base attr_reader :throttlers def initialize(throttlers:) super() @throttlers = throttlers end def call(worker_num, poll_task, task_result) # each throttler delays polling thread by it's own rules # i.e. resulting delay is a sum of each throttler's ones results = @throttlers.map do |t| res = t.call(worker_num, poll_task, task_result) return res if res.success? && res.value! == Sbmt::Outbox::V2::Throttler::SKIP_STATUS return res if res.failure? res end throttled(results) || Success(Sbmt::Outbox::V2::Throttler::NOOP_STATUS) end private def throttled(results) results.find { |res| res.success? && res.value! == Sbmt::Outbox::V2::Throttler::THROTTLE_STATUS } 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/lib/sbmt/outbox/v2/poll_throttler/redis_queue_time_lag.rb
lib/sbmt/outbox/v2/poll_throttler/redis_queue_time_lag.rb
# frozen_string_literal: true require "sbmt/outbox/v2/poll_throttler/base" require "sbmt/outbox/v2/redis_job" module Sbmt module Outbox module V2 module PollThrottler class RedisQueueTimeLag < Base delegate :redis_job_queue_time_lag, to: "Yabeda.box_worker" def initialize(redis:, min_lag: 5, delay: 0) super() @redis = redis @min_lag = min_lag @delay = delay end def wait(worker_num, poll_task, _task_result) # LINDEX is O(1) for first/last element oldest_job = @redis.call("LINDEX", poll_task.redis_queue, -1) return Success(Sbmt::Outbox::V2::Throttler::NOOP_STATUS) if oldest_job.nil? job = RedisJob.deserialize!(oldest_job) time_lag = Time.current.to_i - job.timestamp redis_job_queue_time_lag.set(metric_tags(poll_task), time_lag) if time_lag <= @min_lag sleep(@delay) return Success(Sbmt::Outbox::V2::Throttler::SKIP_STATUS) end Success(Sbmt::Outbox::V2::Throttler::NOOP_STATUS) rescue => ex # noop, just skip any redis / serialization errors Failure(ex.message) 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/lib/sbmt/outbox/v2/poll_throttler/fixed_delay.rb
lib/sbmt/outbox/v2/poll_throttler/fixed_delay.rb
# frozen_string_literal: true require "sbmt/outbox/v2/poll_throttler/base" require "sbmt/outbox/v2/thread_pool" module Sbmt module Outbox module V2 module PollThrottler class FixedDelay < Base def initialize(delay:) super() @delay = delay end def wait(worker_num, poll_task, task_result) return Success(Sbmt::Outbox::V2::Throttler::NOOP_STATUS) unless task_result == Sbmt::Outbox::V2::ThreadPool::PROCESSED sleep(@delay) Success(Sbmt::Outbox::V2::Throttler::THROTTLE_STATUS) 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/lib/sbmt/outbox/v2/poll_throttler/noop.rb
lib/sbmt/outbox/v2/poll_throttler/noop.rb
# frozen_string_literal: true require "sbmt/outbox/v2/poll_throttler/base" module Sbmt module Outbox module V2 module PollThrottler class Noop < Base def wait(worker_num, poll_task, _task_result) Success(Sbmt::Outbox::V2::Throttler::NOOP_STATUS) 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/lib/sbmt/outbox/v2/poll_throttler/paused_box.rb
lib/sbmt/outbox/v2/poll_throttler/paused_box.rb
# frozen_string_literal: true require "sbmt/outbox/v2/poll_throttler/base" require "sbmt/outbox/v2/thread_pool" module Sbmt module Outbox module V2 module PollThrottler class PausedBox < Base def initialize(delay: 0.1) super() @delay = delay end def wait(worker_num, poll_task, task_result) return Success(Sbmt::Outbox::V2::Throttler::NOOP_STATUS) if poll_task.item_class.config.polling_enabled? sleep(@delay) Success(Sbmt::Outbox::V2::Throttler::SKIP_STATUS) 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/lib/sbmt/outbox/v2/poll_throttler/redis_queue_size.rb
lib/sbmt/outbox/v2/poll_throttler/redis_queue_size.rb
# frozen_string_literal: true require "sbmt/outbox/v2/poll_throttler/base" module Sbmt module Outbox module V2 module PollThrottler class RedisQueueSize < Base delegate :redis_job_queue_size, to: "Yabeda.box_worker" def initialize(redis:, min_size: -1, max_size: 100, delay: 0) super() @redis = redis @min_size = min_size @max_size = max_size @delay = delay end def wait(worker_num, poll_task, _task_result) # LLEN is O(1) queue_size = @redis.call("LLEN", poll_task.redis_queue).to_i redis_job_queue_size.set(metric_tags(poll_task), queue_size) if queue_size < @min_size # just throttle (not skip) to wait for job queue size becomes acceptable sleep(@delay) return Success(Sbmt::Outbox::V2::Throttler::THROTTLE_STATUS) end if queue_size > @max_size # completely skip poll-cycle if job queue is oversized sleep(@delay) return Success(Sbmt::Outbox::V2::Throttler::SKIP_STATUS) end Success(Sbmt::Outbox::V2::Throttler::NOOP_STATUS) rescue => ex Failure(ex.message) 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/lib/sbmt/outbox/v2/poll_throttler/base.rb
lib/sbmt/outbox/v2/poll_throttler/base.rb
# frozen_string_literal: true require "sbmt/outbox/v2/throttler" module Sbmt module Outbox module V2 module PollThrottler class Base < Outbox::DryInteractor delegate :poll_throttling_counter, :poll_throttling_runtime, to: "Yabeda.box_worker" def call(worker_num, poll_task, task_result) with_metrics(poll_task) do wait(worker_num, poll_task, task_result) end end def wait(_worker_num, _poll_task, _task_result) raise NotImplementedError, "Implement #wait for Sbmt::Outbox::PollThrottler::Base" end private def with_metrics(poll_task, &block) tags = metric_tags(poll_task) result = nil poll_throttling_runtime.measure(tags) do result = yield poll_throttling_counter.increment(tags.merge(status: result.value_or(result.failure)), by: 1) end result end def metric_tags(poll_task) poll_task.yabeda_labels.merge(throttler: self.class.name) 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/lib/sbmt/outbox/v2/poll_throttler/rate_limited.rb
lib/sbmt/outbox/v2/poll_throttler/rate_limited.rb
# frozen_string_literal: true require "sbmt/outbox/v2/poll_throttler/base" require "ruby-limiter" module Sbmt module Outbox module V2 module PollThrottler class RateLimited < Base attr_reader :queues def initialize(limit: nil, interval: nil, balanced: true) @limit = limit @interval = interval @balanced = balanced @queues = {} @mutex = Mutex.new end def wait(_worker_num, poll_task, _task_result) queue_for(poll_task).shift Success(Sbmt::Outbox::V2::Throttler::THROTTLE_STATUS) end private def queue_for(task) key = task.item_class.box_name return @queues[key] if @queues.key?(key) @mutex.synchronize do return @queues[key] if @queues.key?(key) @queues[key] = Limiter::RateQueue.new( @limit, interval: @interval, balanced: @balanced ) end 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/lib/sbmt/outbox/instrumentation/open_telemetry_loader.rb
lib/sbmt/outbox/instrumentation/open_telemetry_loader.rb
# frozen_string_literal: true require "opentelemetry" require "opentelemetry-common" require "opentelemetry-instrumentation-base" require_relative "../middleware/open_telemetry/tracing_create_item_middleware" require_relative "../middleware/open_telemetry/tracing_create_batch_middleware" require_relative "../middleware/open_telemetry/tracing_item_process_middleware" module Sbmt module Outbox module Instrumentation class OpenTelemetryLoader < ::OpenTelemetry::Instrumentation::Base install do |_config| require_dependencies ::Sbmt::Outbox.config.create_item_middlewares.push("Sbmt::Outbox::Middleware::OpenTelemetry::TracingCreateItemMiddleware") ::Sbmt::Outbox.config.create_batch_middlewares.push("Sbmt::Outbox::Middleware::OpenTelemetry::TracingCreateBatchMiddleware") ::Sbmt::Outbox.config.item_process_middlewares.push("Sbmt::Outbox::Middleware::OpenTelemetry::TracingItemProcessMiddleware") end present do true end private def require_dependencies require_relative "../middleware/open_telemetry/tracing_create_item_middleware" require_relative "../middleware/open_telemetry/tracing_create_batch_middleware" require_relative "../middleware/open_telemetry/tracing_item_process_middleware" 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/config/routes.rb
config/routes.rb
# frozen_string_literal: true Sbmt::Outbox::Engine.routes.draw do root to: "root#index" namespace :api, defaults: {format: :json} do resources :outbox_classes, only: [:index, :show, :update, :destroy] resources :inbox_classes, only: [:index, :show, :update, :destroy] 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/config/schedule.rb
config/schedule.rb
# frozen_string_literal: true every "10m", as: "Sbmt::Outbox::DeleteStaleOutboxItemsJob", overlap: false, timeout: "60s" do Sbmt::Outbox::DeleteStaleOutboxItemsJob.enqueue end every "10m", as: "Sbmt::Outbox::DeleteStaleInboxItemsJob", overlap: false, timeout: "60s" do Sbmt::Outbox::DeleteStaleInboxItemsJob.enqueue end
ruby
MIT
6da9ae3ea0333ae3ad58983c035bc95bd739aaf4
2026-01-04T17:51:44.997823Z
false
Kuper-Tech/sbmt-outbox
https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/config/initializers/active_record.rb
config/initializers/active_record.rb
# frozen_string_literal: true if ActiveRecord.version >= Gem::Version.new("7.0.0") Rails.application.config.active_record.tap do |config| config.query_log_tags << { box_name: ->(context) { context[:box_item]&.class&.box_name }, box_item_id: ->(context) { context[:box_item]&.uuid } } 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/config/initializers/schked.rb
config/initializers/schked.rb
# frozen_string_literal: true begin require "schked" Schked.config.paths << Sbmt::Outbox::Engine.root.join("config", "schedule.rb") rescue LoadError # optional dependency end
ruby
MIT
6da9ae3ea0333ae3ad58983c035bc95bd739aaf4
2026-01-04T17:51:44.997823Z
false
Kuper-Tech/sbmt-outbox
https://github.com/Kuper-Tech/sbmt-outbox/blob/6da9ae3ea0333ae3ad58983c035bc95bd739aaf4/config/initializers/yabeda.rb
config/initializers/yabeda.rb
# frozen_string_literal: true Yabeda.configure do # error_counter retry_counter sent_counter fetch_error_counter discarded_counter group :outbox do default_tag(:worker_version, 1) counter :created_counter, tags: %i[type name partition owner], comment: "The total number of created messages" counter :sent_counter, tags: %i[type name partition owner], comment: "The total number of processed messages" counter :error_counter, tags: %i[type name partition owner], comment: "Errors (excepting retries) that occurred while processing messages" counter :retry_counter, tags: %i[type name partition owner], comment: "Retries that occurred while processing messages" counter :discarded_counter, tags: %i[type name partition owner], comment: "The total number of discarded messages" counter :fetch_error_counter, tags: %i[type name partition owner], comment: "Errors that occurred while fetching messages" gauge :last_stored_event_id, tags: %i[type name partition owner], comment: "The ID of the last stored event" gauge :last_sent_event_id, tags: %i[type name partition owner], comment: "The ID of the last sent event. " \ "If the message order is not preserved, the value may be inaccurate" histogram :process_latency, tags: %i[type name partition owner], unit: :seconds, buckets: [0.5, 1, 2.5, 5, 10, 15, 20, 30, 45, 60, 300].freeze, comment: "A histogram outbox process latency" histogram :delete_latency, tags: %i[box_type box_name], unit: :seconds, buckets: [0.005, 0.01, 0.05, 0.1, 0.25, 0.5, 1, 2, 5, 10, 20, 30].freeze, comment: "A histogram for outbox/inbox deletion latency" histogram :retry_latency, tags: %i[type name partition owner], unit: :seconds, buckets: [1, 10, 20, 50, 120, 300, 900, 1800, 3600].freeze, comment: "A histogram outbox retry latency" counter :deleted_counter, tags: %i[box_type box_name], comment: "A counter for the number of deleted outbox/inbox items" end group :box_worker do default_tag(:worker_version, 1) default_tag(:worker_name, "worker") counter :job_counter, tags: %i[type name partition state owner], comment: "The total number of processed jobs" counter :job_timeout_counter, tags: %i[type name partition_key], comment: "Requeue of a job that occurred while processing the batch" counter :job_items_counter, tags: %i[type name partition], comment: "The total number of processed items in jobs" histogram :job_execution_runtime, comment: "A histogram of the job execution time", unit: :seconds, tags: %i[type name partition], buckets: [0.5, 1, 2.5, 5, 10, 15, 20, 30, 45, 60, 300] histogram :item_execution_runtime, comment: "A histogram of the item execution time", unit: :seconds, tags: %i[type name partition], buckets: [0.5, 1, 2.5, 5, 10, 15, 20, 30, 45, 60, 300] counter :batches_per_poll_counter, tags: %i[type name partition], comment: "The total number of poll batches per poll" gauge :redis_job_queue_size, tags: %i[type name partition], comment: "The total size of redis job queue" gauge :redis_job_queue_time_lag, tags: %i[type name partition], comment: "The total time lag of redis job queue" counter :poll_throttling_counter, tags: %i[type name partition throttler status], comment: "The total number of poll throttlings" histogram :poll_throttling_runtime, comment: "A histogram of the poll throttling time", unit: :seconds, tags: %i[type name partition throttler], buckets: [0.5, 1, 2.5, 5, 10, 15, 20, 30, 45, 60, 300] end end
ruby
MIT
6da9ae3ea0333ae3ad58983c035bc95bd739aaf4
2026-01-04T17:51:44.997823Z
false
heycarsten/email-veracity
https://github.com/heycarsten/email-veracity/blob/1a7db8ca81a72d8102f31d65a1ca7814e806a506/test/test_domain.rb
test/test_domain.rb
require 'helper' class TestDomain < Test::Unit::TestCase def test_blacklisted_domain assert EmailVeracity::Domain.blacklisted?('dodgeit.com'), 'Should match a blacklisted domain.' assert EmailVeracity::Domain.blacklisted?('DoDgEiT.cOm'), 'Should match a blacklisted domain regardless of case.' assert EmailVeracity::Domain.blacklisted?(" dodgeit.com \r\n "), 'Should match a blacklisted domain regardless of whitespace.' assert !EmailVeracity::Domain.blacklisted?('iamnotblacklisted.com'), 'Should not match a non-blacklisted domain.' end def test_whitelisted_domain assert EmailVeracity::Domain.whitelisted?('gmail.com'), 'Should match a whitelisted domain.' assert EmailVeracity::Domain.whitelisted?('GmAiL.cOm'), 'Should match a whitelisted domain regardless of case.' assert EmailVeracity::Domain.whitelisted?(" gmail.com \r\n "), 'Should match a whitelisted domain regardless of whitespace.' assert !EmailVeracity::Domain.whitelisted?('iamnotwhitelisted.com'), 'Should not match a non-whitelisted domain.' end def test_initializing_a_new_domain_with_whitespace domain = new_domain(' heycarsten.com ') assert_equal 'heycarsten.com', domain.name, 'Should strip whitespace.' assert_respond_to domain, :to_s, 'Should have a to_s method.' end def test_a_valid_domain_for_address_servers domain_name = 'gmail.com' domain = new_domain(domain_name) EmailVeracity::Resolver.expects(:get_servers_for). with(domain_name, :a).returns(["mail.#{domain_name}"]) assert_not_empty domain.address_servers, 'Should contain address servers.' end def test_a_valid_domain_for_exchange_servers domain_name = 'gmail.com' domain = new_domain(domain_name) EmailVeracity::Resolver.expects(:get_servers_for). with(domain_name, :mx).returns(["mail.#{domain_name}"]) assert_not_empty domain.exchange_servers, 'Should contain mail servers.' end def test_an_invalid_domain_for_address_servers domain = new_domain('i-surely-do-not.exist') domain.expects(:servers_in).with(:a).returns([]) assert_empty domain.address_servers, 'Should not contain address servers.' end def test_an_invalid_domain_for_exchange_servers domain = new_domain('i-surely-do-not.exist') domain.expects(:servers_in).with(:mx).returns([]) assert_empty domain.exchange_servers, 'Should not contain exchange servers.' end def test_a_blank_domain_for_servers domain = new_domain('') assert_empty domain.exchange_servers, 'Should not contain exchange servers.' assert_empty domain.address_servers, 'Should not contain address servers.' end def test_for_errors_on_a_valid_domain domain = new_domain('yahoo.com') assert_empty domain.errors, 'Should not have errors.' end context 'A domain with no address records or exchange records' do setup do @domain = new_domain('nothingtoseehere.org') @domain.stubs(:address_servers).returns([]) @domain.stubs(:exchange_servers).returns([]) end should 'not pass validation' do assert !@domain.valid? end should 'indicate the appropriate error' do assert @domain.errors.include?(:no_records) end end context 'A domain validation when Config[:skip_lookup] is set' do setup do EmailVeracity::Config[:skip_lookup] = true @domain = new_domain('heycarsten.com') @domain.stubs(:address_servers).returns([:something]) end should 'not perform any lookups for validations' do assert @domain.errors.empty? end should 'still allow explicit lookups' do assert @domain.address_servers.any? end teardown do EmailVeracity::Config.revert! end end private def new_domain(name = 'heycarsten.com') EmailVeracity::Domain.new(name) end end
ruby
MIT
1a7db8ca81a72d8102f31d65a1ca7814e806a506
2026-01-04T17:52:16.554329Z
false
heycarsten/email-veracity
https://github.com/heycarsten/email-veracity/blob/1a7db8ca81a72d8102f31d65a1ca7814e806a506/test/test_validatability.rb
test/test_validatability.rb
require 'helper' class TestValidatability < Test::Unit::TestCase def test_includes_proper_methods %w[ valid? validate! clear_errors! add_error errors ].each do |method_name| assert_respond_to ClassWithValidationMock.new, method_name end end def test_add_error mock = ClassWithValidationMock.new mock.give_error = true assert_equal 1, mock.errors.size, 'Should set one error.' mock.give_errors = true assert_equal [:one, :two, :three], mock.errors, 'Should push tow new errors for a total of three.' mock.give_array_of_errors = true assert_equal [:one, :two, :three, :four, :five], mock.errors, 'Should concat the array leaving two new errors for a total of five.' end def test_valid? mock = ClassWithValidationMock.new assert mock.valid?, 'Should be valid by default.' mock.give_error = true assert !mock.valid?, 'Should not be valid if errors are set.' end def test_errors assert ClassWithValidationMock.new.errors.empty?, 'Should be empty by default.' end end
ruby
MIT
1a7db8ca81a72d8102f31d65a1ca7814e806a506
2026-01-04T17:52:16.554329Z
false
heycarsten/email-veracity
https://github.com/heycarsten/email-veracity/blob/1a7db8ca81a72d8102f31d65a1ca7814e806a506/test/test_resolver.rb
test/test_resolver.rb
require 'helper' class TestResolver < Test::Unit::TestCase DOMAIN_NAMES = %w[ viarails.net heycarsten.com yahoo.com gmail.com savvica.com okayfail.com github.com google.com rogers.com amd.com adobe.com unspace.ca xerox.com webkit.org cooltown.net aiderss.com delicious.com ] def test_consecutive_queries DOMAIN_NAMES.each do |domain_name| EmailVeracity::Resolver.stubs(:get_resources_for). with(domain_name, kind_of(Symbol)).returns(["mail.#{domain_name}"]) end assert_nothing_raised do DOMAIN_NAMES.each do |domain| assert_instance_of Array, EmailVeracity::Resolver.get_servers_for(domain), 'Should return an array of servers' end end end def test_timing_out_while_resolving_a_domain domain = 'okayfail.com' timeout_exception = Timeout::Error.new('The connection has timed out') EmailVeracity::Resolver.stubs(:get_resources_for). with(domain, kind_of(Symbol)).raises(timeout_exception) assert_raise EmailVeracity::DomainResourcesTimeoutError, 'Should time out' do EmailVeracity::Resolver.get_servers_for(domain) end end end
ruby
MIT
1a7db8ca81a72d8102f31d65a1ca7814e806a506
2026-01-04T17:52:16.554329Z
false
heycarsten/email-veracity
https://github.com/heycarsten/email-veracity/blob/1a7db8ca81a72d8102f31d65a1ca7814e806a506/test/test_server.rb
test/test_server.rb
require 'helper' class TestServer < Test::Unit::TestCase def test_creating_a_new_blank_server_object new_server = EmailVeracity::Server.new assert_equal '', new_server.to_s, 'Should yield a blank string on call to to_s.' assert_equal '', new_server.name, 'Should yield a blank string on call to name.' end def test_creating_a_new_server_object_with_a_name_and_type name = 'cooltown.ca' new_server = EmailVeracity::Server.new(name) assert_equal name, new_server.name, 'Should yield the provided name on call to name.' assert_equal name, new_server.to_s, 'Should yield the provided name on call to to_s.' end def test_creating_a_new_blank_server_object_and_setting_its_name_after_initialization new_server = EmailVeracity::Server.new('igvita.com') assert_raise NoMethodError, 'Should fail miserably.' do new_server.name = name end end end
ruby
MIT
1a7db8ca81a72d8102f31d65a1ca7814e806a506
2026-01-04T17:52:16.554329Z
false
heycarsten/email-veracity
https://github.com/heycarsten/email-veracity/blob/1a7db8ca81a72d8102f31d65a1ca7814e806a506/test/test_config.rb
test/test_config.rb
# coding: utf-8 require 'helper' class TestConfig < Test::Unit::TestCase VALID_EMAIL_ADDRESS_EXAMPLES = %w[ goto@rubyfringe.ca went.to@futureruby.com heyd00d+stuff@gmail.com carsten_nielsen@gmail.com carsten-nielsen@gmail.com goodoldemail@address.ca old-skool@mail.mysite.on.ca heycarsten@del.icio.us nex3@haml.town 1234@aplace.com carsten2@happyland.net sweetCandy4@me-and-you.ca technically.accurate@10.0.0.1 simple@example.com -@iamdash.net _@underscoreface.com neat@b.eat &^%$#$%@yojimbo.nil i@shouldwork.com this+should+not+work+but+it+does+because+the+internet+told+me+to%20@dot.com +_-@justaccepteverything.ca $oRight@example.com !!!!!@gmail.com this!is.actually.ok@comtown.com 1@shouldworktoo.com ] INVALID_EMAIL_ADDRESS_EXAMPLES = %w[ two@email.com\ addresses@example.com @failure.net craptastic@ oh-noez@f4iL/\/\@il.net fail..horribly@org.net someone@somewhere charles\ babbage@gmail.com ,@crap.com "greetings\ friend"@comtastic.dk this,fails@ice-t.com ungültige@adresse.de iamat@@at.net .@fail.net ] context 'Default email pattern' do should 'match valid addresses' do VALID_EMAIL_ADDRESS_EXAMPLES.each do |example| assert_match EmailVeracity::Config[:valid_pattern], example end end should 'not match invalid addresses' do INVALID_EMAIL_ADDRESS_EXAMPLES.each do |example| assert_no_match EmailVeracity::Config[:valid_pattern], example end end end def test_default_whitelist_domains assert_instance_of Array, EmailVeracity::Config[:whitelist] assert_not_empty EmailVeracity::Config[:whitelist], 'Should have more than one item.' end def test_default_blacklist_domains assert_instance_of Array, EmailVeracity::Config[:blacklist] assert_not_empty EmailVeracity::Config[:blacklist], 'Should have more than one item.' end def test_must_include_default_setting assert_instance_of Array, EmailVeracity::Config[:must_include] end def test_enforced_record_with_symbols assert !EmailVeracity::Config.enforced_record?(:a), 'Should not check for A records by default' assert !EmailVeracity::Config.enforced_record?(:mx), 'Should not check for MX records be default' end def test_enforce_lookup_with_strings assert !EmailVeracity::Config.enforced_record?('a'), 'Should not check for A records by default' assert !EmailVeracity::Config.enforced_record?('mx'), 'Should not check for MX records be default' end def test_changing_and_reverting_configuration EmailVeracity::Config.update(:lookup => false, :timeout => 3) assert_equal false, EmailVeracity::Config[:lookup], 'Should change configuration.' assert_equal 3, EmailVeracity::Config[:timeout] 'Should change configuration.' EmailVeracity::Config.revert! assert_equal EmailVeracity::Config::DEFAULT_OPTIONS, EmailVeracity::Config.options, 'Should revert configuration' end end
ruby
MIT
1a7db8ca81a72d8102f31d65a1ca7814e806a506
2026-01-04T17:52:16.554329Z
false
heycarsten/email-veracity
https://github.com/heycarsten/email-veracity/blob/1a7db8ca81a72d8102f31d65a1ca7814e806a506/test/test_address.rb
test/test_address.rb
require 'helper' class TestAddress < Test::Unit::TestCase def test_initialize assert_instance_of EmailVeracity::Address, EmailVeracity::Address.new('heycarsten@gmail.com'), 'Should create a new Address object.' assert_instance_of Array, EmailVeracity::Address.new('heycarsten@gmail.com').errors, '#errors should be an array.' end end class DefaultConfigurationAddressValidationsTest < Test::Unit::TestCase def test_a_nil_address_argument address = new_address(nil) assert !address.valid?, 'Should be invalid.' end def test_a_well_formed_address_with_a_whitelisted_domain address = new_address('heycarsten@gmail.com') assert address.valid?, "Should be valid. @errors: #{address.errors.inspect}" end def test_a_well_formed_address_with_a_blacklisted_domain address = new_address('heycarsten@dodgeit.com') address.stubs(:domain).returns(stub(:errors => [:blacklisted])) assert !address.valid?, "Should not be valid. @errors: #{address.errors.inspect}" end def test_a_well_formed_address_that_does_not_exist address = new_address('heycarsten@i-surely-do-not-exist.nil') address.stubs(:domain).returns(stub(:errors => [:no_records])) assert !address.valid?, 'Should not be valid.' end def test_a_well_formed_address_that_exists address = new_address('itsme@heycarsten.com') address.stubs(:domain).returns(stub(:errors => [])) assert address.valid?, "Should be valid. @errors: #{address.errors.inspect}" end private def new_address(address = '') EmailVeracity::Address.new(address) end end
ruby
MIT
1a7db8ca81a72d8102f31d65a1ca7814e806a506
2026-01-04T17:52:16.554329Z
false
heycarsten/email-veracity
https://github.com/heycarsten/email-veracity/blob/1a7db8ca81a72d8102f31d65a1ca7814e806a506/test/test_utils.rb
test/test_utils.rb
require 'helper' class TestUtils < Test::Unit::TestCase def test_blank assert EmailVeracity::Utils.blank?([]), '[] should be blank.' assert EmailVeracity::Utils.blank?(''), '"" should be blank.' assert EmailVeracity::Utils.blank?(Hash.new), '{} should be blank.' assert EmailVeracity::Utils.blank?(nil), 'nil should be blank.' end end
ruby
MIT
1a7db8ca81a72d8102f31d65a1ca7814e806a506
2026-01-04T17:52:16.554329Z
false
heycarsten/email-veracity
https://github.com/heycarsten/email-veracity/blob/1a7db8ca81a72d8102f31d65a1ca7814e806a506/test/helper.rb
test/helper.rb
require 'rubygems' require 'test/unit' require 'shoulda' require 'mocha' $:.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) $:.unshift(File.dirname(__FILE__)) require 'email_veracity' class ClassWithValidationMock include EmailVeracity::Validatability attr_accessor :give_error attr_accessor :give_errors attr_accessor :give_array_of_errors def validate! add_error(:one) if give_error add_errors(:two, :three) if give_errors add_errors([:four, :five]) if give_array_of_errors add_errors [] end end class Test::Unit::TestCase def assert_empty(array, message = nil) unless array.is_a?(Array) raise ArgumentError, 'First argument must be an Array' end message = [message, "Expected #{array.inspect} to be empty."]. flatten.join("\n") assert_block(message) { array.empty? } end def assert_not_empty(array, message = nil) unless array.is_a?(Array) raise ArgumentError, 'First argument must be an Array' end message = [message, "Expected #{array.inspect} to contain items."]. flatten.join("\n") assert_block(message) { !array.empty? } end end
ruby
MIT
1a7db8ca81a72d8102f31d65a1ca7814e806a506
2026-01-04T17:52:16.554329Z
false
heycarsten/email-veracity
https://github.com/heycarsten/email-veracity/blob/1a7db8ca81a72d8102f31d65a1ca7814e806a506/lib/email_veracity.rb
lib/email_veracity.rb
require 'resolv' require 'timeout' require 'email_veracity/utils' require 'email_veracity/validatability' require 'email_veracity/config' require 'email_veracity/server' require 'email_veracity/resolver' require 'email_veracity/domain' require 'email_veracity/address' module EmailVeracity class Error < StandardError; end class MalformedEmailAddressError < Error; end class DomainResourcesTimeoutError < Error; end end
ruby
MIT
1a7db8ca81a72d8102f31d65a1ca7814e806a506
2026-01-04T17:52:16.554329Z
false
heycarsten/email-veracity
https://github.com/heycarsten/email-veracity/blob/1a7db8ca81a72d8102f31d65a1ca7814e806a506/lib/email_veracity/validatability.rb
lib/email_veracity/validatability.rb
module EmailVeracity module Validatability def valid? self.errors.empty? end def errors self.clear_errors! self.validate! @errors end protected def validate! # Adds errors to the object. end def clear_errors! @errors = [] end def add_error(*new_errors) @errors ||= [] @errors.concat(new_errors.flatten) end alias_method :add_errors, :add_error end end
ruby
MIT
1a7db8ca81a72d8102f31d65a1ca7814e806a506
2026-01-04T17:52:16.554329Z
false
heycarsten/email-veracity
https://github.com/heycarsten/email-veracity/blob/1a7db8ca81a72d8102f31d65a1ca7814e806a506/lib/email_veracity/utils.rb
lib/email_veracity/utils.rb
module EmailVeracity module Utils def blank?(obj) obj.respond_to?(:empty?) ? obj.empty? : !obj end module_function :blank? end end
ruby
MIT
1a7db8ca81a72d8102f31d65a1ca7814e806a506
2026-01-04T17:52:16.554329Z
false
heycarsten/email-veracity
https://github.com/heycarsten/email-veracity/blob/1a7db8ca81a72d8102f31d65a1ca7814e806a506/lib/email_veracity/domain.rb
lib/email_veracity/domain.rb
module EmailVeracity class Domain include Validatability def self.whitelisted?(name) Config[:whitelist].include?(name.downcase.strip) end def self.blacklisted?(name) Config[:blacklist].include?(name.downcase.strip) end def initialize(name = '') @name = name end def to_s name end def name @name.to_s.downcase.strip end def whitelisted? Domain.whitelisted?(name) end def blacklisted? Domain.blacklisted?(name) end def address_servers @address_servers ||= servers_in(:a) end def exchange_servers @exchange_servers ||= servers_in(:mx) end def servers address_servers + exchange_servers end protected def validate! return if whitelisted? add_error(:blacklisted) if blacklisted? && Config[:enforce_blacklist] unless Config[:skip_lookup] add_error(:no_records) if servers.empty? && !Config.enforced_record?(:a) && !Config.enforced_record?(:mx) add_error(:no_address_servers) if address_servers.empty? && Config.enforced_record?(:a) add_error(:no_exchange_servers) if exchange_servers.empty? && Config.enforced_record?(:mx) end end def servers_in(record) return [] if Config[:skip_lookup] || Utils.blank?(name) Resolver.get_servers_for(name, record) rescue DomainResourcesTimeoutError add_error :timed_out end end end
ruby
MIT
1a7db8ca81a72d8102f31d65a1ca7814e806a506
2026-01-04T17:52:16.554329Z
false
heycarsten/email-veracity
https://github.com/heycarsten/email-veracity/blob/1a7db8ca81a72d8102f31d65a1ca7814e806a506/lib/email_veracity/address.rb
lib/email_veracity/address.rb
module EmailVeracity class Address include Validatability attr_reader :domain def initialize(email = '') self.email_address = email end def to_s email_address end def email_address @email_address.to_s.strip end def email_address=(new_email_address) @email_address = new_email_address.to_s @domain = Domain.new(@email_address.split('@')[1] || '') end protected def validate! add_error(:malformed) if !pattern_valid? add_errors(domain.errors) end def pattern_valid? @email_address =~ Config[:valid_pattern] end end end
ruby
MIT
1a7db8ca81a72d8102f31d65a1ca7814e806a506
2026-01-04T17:52:16.554329Z
false
heycarsten/email-veracity
https://github.com/heycarsten/email-veracity/blob/1a7db8ca81a72d8102f31d65a1ca7814e806a506/lib/email_veracity/resolver.rb
lib/email_veracity/resolver.rb
module EmailVeracity module Resolver RECORD_NAMES_TO_RESOLVE_MAP = { :a => { :method => 'address', :type => AddressServer, :constant => Resolv::DNS::Resource::IN::A }, :mx => { :method => 'exchange', :type => ExchangeServer, :constant => Resolv::DNS::Resource::IN::MX } } def get_servers_for(domain_name, record = :a) Timeout::timeout(Config[:timeout]) do get_resources_for(domain_name, record).map do |server_name| type = RECORD_NAMES_TO_RESOLVE_MAP[record.to_sym][:type] type.new(server_name) end end rescue Timeout::Error raise DomainResourcesTimeoutError, "Timed out while try to resolve #{domain_name}" end protected def get_resources_for(domain_name, record = :a) Resolv::DNS.open do |server| record_map = RECORD_NAMES_TO_RESOLVE_MAP[record] resources = server.getresources(domain_name, record_map[:constant]) resources_to_servers(resources, record_map[:method]) end end def resources_to_servers(resources, resolve_method) resources.inject([]) do |array, resource| array << resource.method(resolve_method).call.to_s.strip end.reject { |i| Utils.blank?(i) } end module_function :get_servers_for, :get_resources_for, :resources_to_servers end end
ruby
MIT
1a7db8ca81a72d8102f31d65a1ca7814e806a506
2026-01-04T17:52:16.554329Z
false
heycarsten/email-veracity
https://github.com/heycarsten/email-veracity/blob/1a7db8ca81a72d8102f31d65a1ca7814e806a506/lib/email_veracity/config.rb
lib/email_veracity/config.rb
module EmailVeracity module Config DEFAULT_OPTIONS = { :whitelist => %w[ aol.com gmail.com hotmail.com me.com mac.com msn.com rogers.com sympatico.ca yahoo.com telus.com sprint.com sprint.ca ], :blacklist => %w[ dodgeit.com mintemail.com mintemail.uni.cc 1mintemail.mooo.com spammotel.com trashmail.net ], :valid_pattern => %r{ ^ ( [\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+ \. ) * [\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+ @ ( ( ( ( ( [a-z0-9]{1} [a-z0-9\-]{0,62} [a-z0-9]{1} ) | [a-z] ) \. )+ [a-z]{2,6} ) | ( \d{1,3} \. ){3} \d{1,3} ( \:\d{1,5} )? ) $ }xi, :must_include => [], :timeout => 2, :skip_lookup => false, :enforce_blacklist => false, :enforce_whitelist => true } @options = DEFAULT_OPTIONS.clone def [](key) @options[key.to_sym] end def []=(key, value) @options[key.to_sym] = value end def options @options end def options=(options) unless options.is_a?(Hash) raise ArgumentError, "options must be a Hash not #{options.class}" end @options = options end def update(options) unless options.is_a?(Hash) raise ArgumentError, "options must be a Hash not #{options.class}" end @options.update(options) end def enforced_record?(record) return unless @options[:must_include].is_a?(Array) @options[:must_include].any? { |i| i.to_s == record.to_s } end def revert! @options = DEFAULT_OPTIONS.clone end module_function :[], :[]=, :options, :options=, :update, :enforced_record?, :revert! end end
ruby
MIT
1a7db8ca81a72d8102f31d65a1ca7814e806a506
2026-01-04T17:52:16.554329Z
false
heycarsten/email-veracity
https://github.com/heycarsten/email-veracity/blob/1a7db8ca81a72d8102f31d65a1ca7814e806a506/lib/email_veracity/server.rb
lib/email_veracity/server.rb
module EmailVeracity class Server attr_reader :name alias_method :to_s, :name def initialize(name = '') @name = name end end class AddressServer < Server; end class ExchangeServer < Server; end end
ruby
MIT
1a7db8ca81a72d8102f31d65a1ca7814e806a506
2026-01-04T17:52:16.554329Z
false
adammck/ruby-icloud
https://github.com/adammck/ruby-icloud/blob/8a9418a4260dc4faf9dd0b23599cab341443e5ef/test/test_helpers.rb
test/test_helpers.rb
#!/usr/bin/env ruby # vim: et ts=2 sw=2 # Totally arbitrary GUID for this library TEST_CLIENT_ID = "61384E90-4A30-4F2A-89C3-E031E77B4B78" # Consistent for a single test run, otherwise unique. prefix = "Test #{Time.now.to_i}" TEST_TITLE_A = "#{prefix}A" TEST_TITLE_B = "#{prefix}B" TEST_DATE = DateTime.new(2013, 2, 1, 6, 0)
ruby
MIT
8a9418a4260dc4faf9dd0b23599cab341443e5ef
2026-01-04T17:52:21.382901Z
false
adammck/ruby-icloud
https://github.com/adammck/ruby-icloud/blob/8a9418a4260dc4faf9dd0b23599cab341443e5ef/test/integration/test_session.rb
test/integration/test_session.rb
#!/usr/bin/env ruby # vim: et ts=2 sw=2 class TestSession < MiniTest::Unit::TestCase i_suck_and_my_tests_are_order_dependent! def assert_equal_unordered(expected, actual) assert_equal(expected.sort, actual.sort) end def find(title) $session.reminders.find do |reminder| reminder.title == title end end def setup $session ||= ICloud::Session.new(ENV["APPLE_ID"], ENV["APPLE_PW"], TEST_CLIENT_ID) end def test_00_log_in assert $session.login! end def test_01_fetch_collections actual = $session.collections.map(&:title) assert_equal_unordered %w[Alpha Beta], actual end def test_02_fetch_all_reminders actual = $session.reminders.map(&:title) assert_equal_unordered %w[Foo Bar One Two Three], actual end def test_03_create_reminder $session.post_reminder(ICloud::Records::Reminder.new.tap do |r| r.title = TEST_TITLE_A end) end def test_04_created_reminder_is_persisted titles = $session.reminders.map(&:title) assert_includes titles, TEST_TITLE_A end def test_05_update_reminder reminder = find(TEST_TITLE_A) reminder.title = TEST_TITLE_B $session.put_reminder reminder end def test_06_updated_reminder_is_persisted titles = $session.reminders.map(&:title) assert_includes titles, TEST_TITLE_B end def test_07_add_alarm_to_reminder reminder = find(TEST_TITLE_B) reminder.alarms = [ICloud::Records::Alarm.new.tap do |a| a.on_date = TEST_DATE end] $session.put_reminder reminder end def test_08_added_alarm_was_persisted reminder = find(TEST_TITLE_B) alarms = reminder.alarms.map(&:on_date) assert_includes alarms, TEST_DATE end def test_09_delete_reminder reminder = find(TEST_TITLE_B) $session.delete_reminder reminder end def test_10_deleted_reminder_is_persisted titles = $session.reminders.map(&:title) refute_includes titles, TEST_TITLE_B end end
ruby
MIT
8a9418a4260dc4faf9dd0b23599cab341443e5ef
2026-01-04T17:52:21.382901Z
false
adammck/ruby-icloud
https://github.com/adammck/ruby-icloud/blob/8a9418a4260dc4faf9dd0b23599cab341443e5ef/test/unit/test_date_helpers.rb
test/unit/test_date_helpers.rb
#!/usr/bin/env ruby # vim: et ts=2 sw=2 require "date" class TestDateHelpers < MiniTest::Unit::TestCase def setup @dt = DateTime.new 1984, 6, 13, 18, 30, 0 @ic = [19840613, 1984, 6, 13, 18, 30, 1110] end def test_can_read_icloud_dates assert_equal ICloud::date_from_icloud(@ic), @dt end def test_can_write_icloud_dates assert_equal @ic, ICloud::date_to_icloud(@dt) end end
ruby
MIT
8a9418a4260dc4faf9dd0b23599cab341443e5ef
2026-01-04T17:52:21.382901Z
false
adammck/ruby-icloud
https://github.com/adammck/ruby-icloud/blob/8a9418a4260dc4faf9dd0b23599cab341443e5ef/test/unit/test_proxy.rb
test/unit/test_proxy.rb
#!/usr/bin/env ruby # vim: et ts=2 sw=2 require "minitest/mock" class TestProxy < MiniTest::Unit::TestCase def setup @cls = Class.new @cls.send(:include, ICloud::Proxy) @obj = @cls.new end def test_returns_nil_when_no_proxy_is_configured @obj.stub(:env, { }) do assert_nil @obj.proxy end end def test_finds_proxy_settings_in_env @obj.stub(:env, { "HTTPS_PROXY" => "http://adam:password@example.com:8080" }) do @obj.proxy.tap do |uri| assert_equal "example.com", uri.host assert_equal 8080, uri.port assert_equal "adam", uri.user assert_equal "password", uri.password end end end end
ruby
MIT
8a9418a4260dc4faf9dd0b23599cab341443e5ef
2026-01-04T17:52:21.382901Z
false
adammck/ruby-icloud
https://github.com/adammck/ruby-icloud/blob/8a9418a4260dc4faf9dd0b23599cab341443e5ef/test/unit/porcelain/test_reminder.rb
test/unit/porcelain/test_reminder.rb
#!/usr/bin/env ruby # vim: et ts=2 sw=2 class TestPorcelainReminder < MiniTest::Unit::TestCase def setup end # test_finds_existing_reminder # test_updates_existing_reminder # test_deletes_existing_reminder # test_creates_new_reminder end
ruby
MIT
8a9418a4260dc4faf9dd0b23599cab341443e5ef
2026-01-04T17:52:21.382901Z
false
adammck/ruby-icloud
https://github.com/adammck/ruby-icloud/blob/8a9418a4260dc4faf9dd0b23599cab341443e5ef/test/unit/record/test_nested_record.rb
test/unit/record/test_nested_record.rb
#!/usr/bin/env ruby # vim: et ts=2 sw=2 class TestNestedRecord < MiniTest::Unit::TestCase def setup @pet_cls = Class.new do include ICloud::Record has_fields :name end # The block passed to Class.new is instance_evalled in the new class (where # @pet_cls is nil), so we must alias this to a local so we can access it. pc = @pet_cls @person_cls = Class.new do include ICloud::Record has_fields :name has_many :pets, pc end end def make_pet(name) @pet_cls.new.tap do |pet| pet.name = name end end def example_hash { "name" => "Adam", "pets" => [ {"name" => "Mr Jingles"}, {"name" => "Prof Snugglesworth"}, ] } end def example_record @person_cls.new.tap do |r| r.name = "Adam" r.pets = [ make_pet("Mr Jingles"), make_pet("Prof Snugglesworth") ] end end def test_serialization assert_equal(example_hash, example_record.to_icloud) end def test_unserialization assert_equal(example_record, @person_cls.from_icloud(example_hash)) end end
ruby
MIT
8a9418a4260dc4faf9dd0b23599cab341443e5ef
2026-01-04T17:52:21.382901Z
false
adammck/ruby-icloud
https://github.com/adammck/ruby-icloud/blob/8a9418a4260dc4faf9dd0b23599cab341443e5ef/test/unit/record/test_simple_record.rb
test/unit/record/test_simple_record.rb
#!/usr/bin/env ruby # vim: et ts=2 sw=2 class TestSimpleRecord < MiniTest::Unit::TestCase def setup @cls = Class.new do include ICloud::Record has_fields :first_name, :last_name end end def test_serialization record = @cls.new.tap do |r| r.first_name = "Adam" r.last_name = "Mckaig" end assert_equal({ "firstName" => "Adam", "lastName" => "Mckaig" }, record.to_icloud) end def test_unserialization record = @cls.from_icloud({ "firstName" => "Adam", "lastName" => "Mckaig", "junk" => 123 }) assert_equal "Adam", record.first_name assert_equal "Mckaig", record.last_name refute_respond_to record, :junk end def test_snapshots record = @cls.new.tap do |r| r.first_name = "Adam" end record.snapshot! refute record.changed? record.last_name = "Mckaig" assert record.changed? end end
ruby
MIT
8a9418a4260dc4faf9dd0b23599cab341443e5ef
2026-01-04T17:52:21.382901Z
false
adammck/ruby-icloud
https://github.com/adammck/ruby-icloud/blob/8a9418a4260dc4faf9dd0b23599cab341443e5ef/test/unit/records/test_alarm.rb
test/unit/records/test_alarm.rb
#!/usr/bin/env ruby # vim: et ts=2 sw=2 class TestAlarm < MiniTest::Unit::TestCase def setup @cls = ICloud::Records::Alarm end def test_on_date_from_icloud assert_equal DateTime.new(2013, 6, 13, 7, 45), @cls.on_date_from_icloud([20130613, 2013, 6, 13, 7, 45, 465]) assert_nil @cls.on_date_from_icloud(nil) end end
ruby
MIT
8a9418a4260dc4faf9dd0b23599cab341443e5ef
2026-01-04T17:52:21.382901Z
false
adammck/ruby-icloud
https://github.com/adammck/ruby-icloud/blob/8a9418a4260dc4faf9dd0b23599cab341443e5ef/test/unit/records/test_reminder.rb
test/unit/records/test_reminder.rb
#!/usr/bin/env ruby # vim: et ts=2 sw=2 class TestReminder < MiniTest::Unit::TestCase def setup @cls = ICloud::Records::Reminder end def test_complete? incomplete = @cls.new complete = @cls.new.tap { |r| r.completed_date = DateTime.now } refute incomplete.complete? assert complete.complete? end end
ruby
MIT
8a9418a4260dc4faf9dd0b23599cab341443e5ef
2026-01-04T17:52:21.382901Z
false
adammck/ruby-icloud
https://github.com/adammck/ruby-icloud/blob/8a9418a4260dc4faf9dd0b23599cab341443e5ef/lib/icloud.rb
lib/icloud.rb
#!/usr/bin/env ruby # vim: et ts=2 sw=2 module ICloud end require "icloud/core_ext/array" require "icloud/core_ext/date_time" require "icloud/core_ext/object" require "icloud/helpers/date_helpers" require "icloud/helpers/guid" require "icloud/helpers/inflections" require "icloud/helpers/proxy" require "icloud/record" require "icloud/records/alarm" require "icloud/records/collection" require "icloud/records/dsinfo" require "icloud/records/reminder" require "icloud/porcelain/reminder" require "icloud/errors" require "icloud/pool" require "icloud/session" require "icloud/version"
ruby
MIT
8a9418a4260dc4faf9dd0b23599cab341443e5ef
2026-01-04T17:52:21.382901Z
false
adammck/ruby-icloud
https://github.com/adammck/ruby-icloud/blob/8a9418a4260dc4faf9dd0b23599cab341443e5ef/lib/icloud/record.rb
lib/icloud/record.rb
#!/usr/bin/env ruby # vim: et ts=2 sw=2 module ICloud # Public: Mixin to allow a class to be serialized and unserialized into the # format spoken by the icloud.com private JSON API. module Record def self.included base base.extend ClassMethods end # Public: Serialize this record's fields into a camelCased-keys hash, ready # to be sent to iCloud. # # Examples # # class MyRecord # include ICloud::Record # fields :first_name, :last_name # end # # record = MyRecord.new.tap do |r| # r.first_name = "Adam" # r.last_name = "Mckaig" # end # # record.to_icloud # # => { "firstName"=>"Adam", "lastName"=>"Mckaig" } # # Returns the serialized hash. def to_icloud Hash.new.tap do |hsh| dump.each do |name, val| hsh[ICloud.camel_case(name)] = val.to_icloud end end end # Internal: Serialize this record. # Returns the serialized hash. def dump Hash.new.tap do |hsh| self.class.fields.each do |name, has_many_type| hsh[name] = send name end end end # Public: Store a copy of this record. # Returns nothing. def snapshot! @snapshot = dump end # Public: Returns true if this record has changed since `snapshot!` was last # called, or if snapshot has never been called. def changed? @snapshot.nil? or (@snapshot != dump) end # Public: Returns true if this record is equal-ish to `other`. def ==(other) other.respond_to?(:to_icloud) && (dump == other.to_icloud) end module ClassMethods # Public: Returns the field names of this record. def fields @fields or [] end # Public: Add named fields to this record. This creates the accessors, and # keeps track of the field names for [un-]serialization later via the # to_icloud and from_icloud methods. # # Returns nothing. def has_fields *names names.each do |name| has_field name end end # TODO: Documentation def has_many name, cls has_field name, cls end # TODO: Documentation def has_field name, cls=nil @fields ||= [] @fields.push [name.to_s, cls] attr_accessor name end # Public: Create a record from an iCloud-ish (camelCased) hash. To ensure # forwards compatibility, any unrecognized keys are silently ignored. # # hsh - The hash to be unserialized. # # Examples # # class MyRecord # include ICloud::Record # fields :first_name, :last_name # end # # hsh = { # "firstName" => "Adam", # "lastName" => "Mckaig", # "moreStuff" => 123 # } # # MyRecord.from_icloud(hsh) # # => #<MyRecord:0x123 @first_name="Adam", @last_name="Mckaig"> # # Returns the new record. def from_icloud hsh self.new.tap do |record| fields.each do |name, cls| value = hsh[ICloud.camel_case(name)] native_value = if cls value.map do |v| cls.from_icloud(v) end else cast_method = "#{name}_from_icloud" respond_to?(cast_method) ? send(cast_method, value) : value end record.send "#{name}=", native_value end record.snapshot! end end end end end
ruby
MIT
8a9418a4260dc4faf9dd0b23599cab341443e5ef
2026-01-04T17:52:21.382901Z
false
adammck/ruby-icloud
https://github.com/adammck/ruby-icloud/blob/8a9418a4260dc4faf9dd0b23599cab341443e5ef/lib/icloud/session.rb
lib/icloud/session.rb
#!/usr/bin/env ruby # vim: et ts=2 sw=2 require "cgi" require "uri" require "net/https" require "json/pure" module ICloud class Session include Proxy def initialize apple_id, pass, client_id=nil @apple_id = apple_id @pass = pass @user = nil @services = nil @http = {} @cookies = [] @request_id = 1 @client_id = client_id || default_client_id end def pool unless @pool @pool = Pool.new update(get_startup) end @pool end # # Public: Logs in to icloud.com or raises some subclass of Net::HTTPError. # def login!(extended = false) uri = URI.parse("https://setup.icloud.com/setup/ws/1/login") payload = { "apple_id"=>@apple_id, "password"=>@pass, "extended_login"=>extended } response = http(uri.host, uri.port).post(uri.path, payload.to_json, default_headers) @cookies = response.get_fields("set-cookie") body = JSON.parse(response.body) @user = Records::DsInfo.from_icloud(body["dsInfo"]) @services = parse_services(body["webservices"]) true end def user ensure_logged_in @user end def services ensure_logged_in @services end def collections ensure_logged_in pool.find_by_type(Records::Collection) end def reminders ensure_logged_in update(get_completed) pool.find_by_type(Records::Reminder) end def post_reminder(reminder) ensure_logged_in path = "/rd/reminders/#{reminder.p_guid || 'tasks'}" # TODO: Should ClientState always be included in posts? post(service_url(:reminders, path), { }, { "Reminders" => reminder.to_icloud, "ClientState" => client_state }) end def put_reminder(reminder) ensure_logged_in path = "/rd/reminders/#{reminder.p_guid || 'tasks'}" # TODO: Should ClientState always be included in posts? post(service_url(:reminders, path), { "methodOverride" => "PUT" }, { "Reminders" => reminder.to_icloud, "ClientState" => client_state }) end def put_collection_reminder(reminder) ensure_logged_in post(service_url(:reminders, "/rd/reminders/#{reminder.p_guid}"), { "methodOverride" => "PUT" }, { "Reminders" => reminder.to_icloud, "ClientState" => client_state }) end def delete_reminder(reminder) ensure_logged_in path = "/rd/reminders/#{reminder.p_guid || 'tasks'}" post(service_url(:reminders, path), { "methodOverride" => "DELETE", "id" => deletion_id }, { "Reminders" => [reminder.to_icloud], "ClientState" => client_state }) end def apply_changeset(cs) if cs.include?("updates") parse_records(cs["updates"]).each do |record| pool.add(record) end end if cs.include?("deletes") cs["deletes"].each do |hash| pool.delete(hash["guid"]) end end end def update(*args) args.each do |hash| parse_records(hash).each do |record| pool.add(record) end end end # Performs a GET request in this session. def get url, params={}, headers={} uri = URI.parse(url) path = uri.path + "?" + query_string(default_params.merge(params)) response = http(uri.host, uri.port).get(path, default_headers.merge(headers)) JSON.parse(response.body) end # Performs a POST request in this session. def post url, params={}, postdata={}, headers={} uri = URI.parse(url) p = postdata.to_json h = default_headers.merge(headers) path = uri.path + "?" + query_string(default_params.merge(params)) response = http(uri.host, uri.port).post(path, p, h) if (response.code.to_i) == 200 && (response.content_type == "text/json") hash = JSON.parse(response.body) else raise StandardError.new( "Request:\n" + "path: #{path}\n" + "headers: #{h}\n" + "#{p}\n" + "Response:\n" + "--\n" + "Response:\n" + "status: #{response.code}\n" + "content-type: #{response.content_type}\n" + response.body) end # If this response contains a changeset, apply it. if hash.include?("ChangeSet") apply_changeset(hash["ChangeSet"]) end hash end private def get_startup ensure_logged_in get(service_url(:reminders, "/rd/startup")) end def get_completed ensure_logged_in get(service_url(:reminders, "/rd/completed")) end # # Internal: Returns a Net::HTTP object for host:post, which may or may not # have already been used. Proxies and SSL are taken care of. # def http(host, port) @http["#{host}:#{port}"] ||= http_class.new(host, port).tap do |http| http.verify_mode = OpenSSL::SSL::VERIFY_PEER http.use_ssl = true end end # # Internal: Returns the Net::HTTP class which should be used, which might be # a configured Proxy. # def http_class if use_proxy? Net::HTTP::Proxy(proxy.host, proxy.port, proxy.user, proxy.password) else Net::HTTP end end # # Internal: Flattens a hash into a query string. # def query_string(params) params.map do |k, v| "#{CGI::escape(k)}=#{CGI::escape(v)}" end.join("&") end # # Internal: Calls `login!` unless it has already been called. # def ensure_logged_in login! if @user.nil? end def default_headers { "origin" => "https://www.icloud.com", "cookie" => @cookies.join("; ") } end def default_params { "lang" => "en-us", "usertz" => "America/New_York", "dsid" => @user.dsid } end # # Internal: Convert a record name (as returned by icloud.com) into a class. # Names are downcased and singularized before being resolved. # def record_class(name, mod=ICloud::Records) sym = name.capitalize.sub(/s$/, "").to_sym mod.const_get(sym) if mod.const_defined?(sym) end # # Internal: Builds and returns an internal URL. # def service_url service, path @services[service.to_s] + path end # Internal: Parse the "webservices" value returned during login into a hash # of name=>url. def parse_services(json) Hash.new.tap do |hsh| json.map do |name, params| if params["status"] == "active" hsh[name] = params["url"] end end end end # # Internal: Parses a nested hash of records (as passed around by icloud.com) # into a flat array of record instances, silently ignoring any unrecognized # data. # # Examples # # parse_records({ # "Collection": [{ "guid": 123 }, { "guid": 456 }], # "Reminder": [{ "guid": 789 }], # "Whatever": [{ "junk": 1 }] # }) # # # => [<Collection:123>, <Collection:456>, <Reminder:789>] # def parse_records(hash) [].tap do |records| hash.each do |name, hashes| if cls = record_class(name) hashes.each do |hsh| obj = cls.from_icloud(hsh) records.push(obj) end end end end end # # Returns the current client state, i.e. the `guid` and `ctag` (entity tag) # of each collection we know about. The server uses this to decide which # records to send back. # # It looks like multiple record types could be specified here, but haven't # seen that. # def client_state { "Collections" => collections.map do |c| { "guid" => c.guid, "ctag" => c.ctag, } end } end # # Internal: Returns a random 40 character hex string, which icloud.com needs # when deleting a reminder. (I don't know why. It doesn't appear to be used # anywhere else.) # def deletion_id SecureRandom.hex(20) end # # Internal: Returns the default client UUID of this library. It's totally # arbitrary. Please change if it you substantially fork the library. # def default_client_id "1B47512E-9743-11E2-8092-7F654762BE04" end def marshal_dump [@apple_id, @pass, @client_id, @request_id, @user, @services, @cookies] end def marshal_load(ary) @apple_id, @pass, @client_id, @request_id, @user, @services, @cookies = *ary @http = {} end end end
ruby
MIT
8a9418a4260dc4faf9dd0b23599cab341443e5ef
2026-01-04T17:52:21.382901Z
false
adammck/ruby-icloud
https://github.com/adammck/ruby-icloud/blob/8a9418a4260dc4faf9dd0b23599cab341443e5ef/lib/icloud/version.rb
lib/icloud/version.rb
#!/usr/bin/env ruby # vim: et ts=2 sw=2 unless defined?(ICloud::VERSION) module ICloud VERSION = "0.0.1" end end
ruby
MIT
8a9418a4260dc4faf9dd0b23599cab341443e5ef
2026-01-04T17:52:21.382901Z
false
adammck/ruby-icloud
https://github.com/adammck/ruby-icloud/blob/8a9418a4260dc4faf9dd0b23599cab341443e5ef/lib/icloud/errors.rb
lib/icloud/errors.rb
#!/usr/bin/env ruby # vim: et ts=2 sw=2 module ICloud class Error < StandardError; end class LoginFailed < Error; end # # This error should be raised when a request to icloud.com fails. The server # usually responds with something helpful. # class RequestError < Error def initialize(status, message) @status = status @message = message end def to_s "%s (%s)" % [@message, @status] end end end
ruby
MIT
8a9418a4260dc4faf9dd0b23599cab341443e5ef
2026-01-04T17:52:21.382901Z
false
adammck/ruby-icloud
https://github.com/adammck/ruby-icloud/blob/8a9418a4260dc4faf9dd0b23599cab341443e5ef/lib/icloud/pool.rb
lib/icloud/pool.rb
#!/usr/bin/env ruby # vim: et ts=2 sw=2 module ICloud class Pool def initialize @objects = {} end def add obj @objects[obj.guid] = obj end def get guid @objects[guid] end def find hsh @objects.values.select do |obj| hsh.all? do |k, v| obj.send(k) == v end end end def changed @objects.values.select do |obj| obj.changed? end end def delete(guid) @objects.delete(guid) end def alarms find_by_type Alarm end def collections find_by_type Collection end def reminders find_by_type Reminder end def find_by_type cls @objects.values.select do |obj| obj.is_a? cls end end end end
ruby
MIT
8a9418a4260dc4faf9dd0b23599cab341443e5ef
2026-01-04T17:52:21.382901Z
false
adammck/ruby-icloud
https://github.com/adammck/ruby-icloud/blob/8a9418a4260dc4faf9dd0b23599cab341443e5ef/lib/icloud/porcelain/reminder.rb
lib/icloud/porcelain/reminder.rb
#!/usr/bin/env ruby # vim: et ts=2 sw=2 module ICloud class Reminder end end
ruby
MIT
8a9418a4260dc4faf9dd0b23599cab341443e5ef
2026-01-04T17:52:21.382901Z
false