# frozen_string_literal: true # Drop-in Ruby client library for the Sourdough Tracker HTTP API. # # Save this file under your project as `sourdough_client.rb` and require # it directly: # # require_relative 'sourdough_client' # c = SourdoughClient::Client.new('pat_...') # rows = c.account_list(limit: 20, sort: '-created_at') # fresh = c.account_create({ 'name' => 'Example GmbH' }) # # Every endpoint exposed by the HTTP API is wrapped as an # `_` instance method on Client. List methods take keyword # args; get/update/delete methods take the row id as their first # positional argument. # # Provided as-is, with no warranty. Vendor freely; modify as needed. # Targets Ruby 3.0+; uses only the stdlib (`net/http`, `json`, # `securerandom`, `uri`). # # DO NOT EDIT THIS FILE MANUALLY - re-download from the docs site. # Local edits will be overwritten by the once-per-day version check. require 'net/http' require 'uri' require 'json' require 'securerandom' require 'fileutils' module SourdoughClient APP_SLUG = 'sourdough' APP_NAME = 'Sourdough Tracker' MODULE_NAME = 'sourdough_client' CLIENT_VERSION = '0.3.13' LANGUAGE = 'ruby' DEFAULT_BASE = 'https://sourdoughtracker.com' # Per-type metadata baked at generation time. Inspect with JSON.parse # if you need the legal filters / sorts / max_limit per model without # an extra round-trip. TYPES_JSON = <<~'JSON_BLOB' {"log_entry":{"ops":["list","read","create","update","delete"],"create_fields":["parent_id","kind","title","body","occurred_at","rise_pct","aroma_score","bubble_activity","hydration_pct","flour_used","water_temp_c","ambient_temp_c","feeding_ratio","bake_recipe","bake_outcome","loaf_count","tags"],"update_fields":["kind","title","body","occurred_at","rise_pct","aroma_score","bubble_activity","hydration_pct","flour_used","water_temp_c","ambient_temp_c","feeding_ratio","bake_recipe","bake_outcome","loaf_count","tags"],"allowed_filters":["data__parent_id","data__kind","data__bake_outcome","status","is_archived","owned_by"],"allowed_sorts":["data__occurred_at","created_at","updated_at"],"default_sort":"data__occurred_at","max_limit":200,"fields":[{"name":"body","type":"string","max_len":8000},{"name":"kind","type":"enum","values":["feed","bake","observation","milestone","photo"]},{"name":"tags","type":"tags"},{"name":"title","type":"string","max_len":200},{"name":"rise_pct","type":"number"},{"name":"parent_id","type":"string","max_len":64,"ref":{"type":"sourdough","owned":true,"optional":false}},{"name":"flour_used","type":"string","max_len":200},{"name":"loaf_count","type":"number"},{"name":"aroma_score","type":"number"},{"name":"bake_recipe","type":"string","max_len":4000},{"name":"occurred_at","type":"string","max_len":32},{"name":"bake_outcome","type":"enum","values":["amazing","great","ok","dense","flat","undercooked","overcooked"]},{"name":"water_temp_c","type":"number"},{"name":"feeding_ratio","type":"string","max_len":32},{"name":"hydration_pct","type":"number"},{"name":"ambient_temp_c","type":"number"},{"name":"bubble_activity","type":"number"}]},"sourdough":{"ops":["list","read","create","update","delete"],"create_fields":["name","slug","source","started_at","flour_type","hydration_pct","feeding_ratio","feeding_freq_hours","ambient_temp_c","last_fed_at","retired","favorite","tags","color","notes"],"update_fields":["name","slug","source","started_at","flour_type","hydration_pct","feeding_ratio","feeding_freq_hours","ambient_temp_c","last_fed_at","retired","favorite","tags","color","notes"],"allowed_filters":["data__name","data__slug","data__flour_type","data__retired","data__favorite","data__tags","status","is_archived","owned_by"],"allowed_sorts":["created_at","updated_at","data__name","data__started_at","data__last_fed_at"],"default_sort":"data__name","max_limit":200,"fields":[{"name":"mode","type":"enum","values":["establishing","maintenance","activating","baking"]},{"name":"name","type":"string","max_len":120},{"name":"slug","type":"string","max_len":120},{"name":"tags","type":"tags"},{"name":"color","type":"string","max_len":24},{"name":"notes","type":"string","max_len":8000},{"name":"source","type":"string","max_len":200},{"name":"retired","type":"bool"},{"name":"favorite","type":"bool"},{"name":"flour_type","type":"enum","values":["white","whole_wheat","rye","spelt","einkorn","khorasan","mixed","other"]},{"name":"started_at","type":"string","max_len":32},{"name":"last_fed_at","type":"string","max_len":32},{"name":"establish_day","type":"number"},{"name":"feeding_ratio","type":"string","max_len":32},{"name":"hydration_pct","type":"number"},{"name":"ambient_temp_c","type":"number"},{"name":"computed_state","type":"string","max_len":64},{"name":"bake_target_date","type":"string","max_len":32},{"name":"feeding_freq_hours","type":"number"},{"name":"establish_started_at","type":"string","max_len":32},{"name":"establish_step_done_at","type":"string","max_len":64},{"name":"establish_next_remind_at","type":"string","max_len":64}]}} JSON_BLOB RETRYABLE_STATUSES = [408, 425, 429, 500, 502, 503, 504].freeze MAX_RETRIES = 3 DEFAULT_TIMEOUT = 30 class ApiError < StandardError attr_reader :status, :body_raw def initialize(status, message, body = nil) super("HTTP #{status}: #{message}") @status = status @body_raw = body end end class Client def initialize(token = nil) env_base = ENV['XCLIENT_BASE_URL'] @base_url = (env_base && !env_base.empty? ? env_base : DEFAULT_BASE).sub(%r{/+\z}, '') @token = (token && !token.empty? ? token : ENV.fetch('XCLIENT_TOKEN', '')).to_s @device_id = self.class.send(:load_or_mint_device_id) @session_id = SecureRandom.uuid @meta_sent_once = false @autoupdate_tried = false @meta_lock = Mutex.new end def set_token(token); @token = (token || '').to_s; end def set_base_url(url); @base_url = (url || '').sub(%r{/+\z}, ''); end # ── Identifier persistence ───────────────────────────────────── def self.state_dir home = ENV['HOME'] || ENV['USERPROFILE'] return nil if home.nil? || home.empty? d = File.join(home, ".#sourdough_client") FileUtils.mkdir_p(d, mode: 0o700) d rescue StandardError nil end private_class_method :state_dir def self.load_or_mint_device_id d = state_dir return SecureRandom.uuid if d.nil? f = File.join(d, 'device.json') if File.exist?(f) begin blob = JSON.parse(File.read(f)) did = blob['device_id'] return did if did.is_a?(String) && did.length >= 32 rescue StandardError # fall through to mint end end fresh = SecureRandom.uuid begin File.write(f, JSON.dump('device_id' => fresh)) File.chmod(0o600, f) rescue StandardError end fresh end private_class_method :load_or_mint_device_id def self.autoupdate_enabled? v = (ENV['XCLIENT_NO_AUTOUPDATE'] || '').downcase !%w[1 true yes].include?(v) end private_class_method :autoupdate_enabled? # ── Editor / runtime fingerprint ─────────────────────────────── def self.fingerprint tp = (ENV['TERM_PROGRAM'] || '').downcase { 'ruby_version' => RUBY_VERSION, 'ruby_engine' => RUBY_ENGINE, 'os' => RUBY_PLATFORM, 'term_program' => ENV['TERM_PROGRAM'], 'editor_env' => ENV['EDITOR'], 'ci' => !!(ENV['CI'] || ENV['GITHUB_ACTIONS']), 'claude_code' => !!(ENV['CLAUDECODE'] || ENV['CLAUDE_CODE_ENTRYPOINT']), 'codex' => !!ENV['CODEX_HOME'], 'vscode' => tp == 'vscode' && ENV['CURSOR_TRACE_ID'].nil?, 'cursor' => !!ENV['CURSOR_TRACE_ID'], 'antigravity' => !!ENV['ANTIGRAVITY_TRACE_ID'], 'jetbrains' => tp.include?('jetbrains'), } end private_class_method :fingerprint # ── HTTP transport ───────────────────────────────────────────── def request_list(path, opts = nil) qs = [] if opts.is_a?(Hash) opts.each do |k, v| next if v.nil? if k.to_s == 'filters' && v.is_a?(Hash) v.each { |fk, fv| next if fv.nil?; qs << "#{URI.encode_www_form_component(fk.to_s)}=#{URI.encode_www_form_component(fv.to_s)}" } next end qs << "#{URI.encode_www_form_component(k.to_s)}=#{URI.encode_www_form_component(v.to_s)}" end end path = path + (path.include?('?') ? '&' : '?') + qs.join('&') unless qs.empty? request_json('GET', path, nil) end def request_json(method, path, body) maybe_autoupdate url = @base_url + path json = body.nil? ? nil : JSON.dump(body) last_err = nil MAX_RETRIES.times do |attempt| begin status, headers, raw_body = send_following_redirects(method.to_s.upcase, url, json) fresh = headers['x-auth-refresh-token'] @token = fresh if fresh && !fresh.empty? if RETRYABLE_STATUSES.include?(status) && attempt + 1 < MAX_RETRIES ra = headers['retry-after'] sleep(self.class.send(:backoff_seconds, attempt, ra ? ra.to_f : nil)) next end parsed = raw_body.empty? ? nil : (JSON.parse(raw_body) rescue nil) if status >= 400 msg = parsed.is_a?(Hash) ? (parsed['detail'] || parsed['message'] || 'request failed') : 'request failed' emit_call_event(method, path, status, false) raise ApiError.new(status, msg, parsed) end emit_call_event(method, path, status, true) return parsed rescue ApiError raise rescue StandardError => e last_err = e sleep(self.class.send(:backoff_seconds, attempt, nil)) if attempt + 1 < MAX_RETRIES next if attempt + 1 < MAX_RETRIES emit_call_event(method, path, 0, false) raise ApiError.new(0, e.message) end end emit_call_event(method, path, 0, false) raise ApiError.new(0, last_err ? last_err.message : 'request failed') end # Walk the redirect chain manually so Authorization can be dropped # on cross-origin hops. Caps at 5 hops; mirrors RFC 7231 method # rewrite semantics. def send_following_redirects(method, url, json) current_url = url current_method = method current_json = json strip_auth = false 6.times do |hop| uri = URI.parse(current_url) Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https', open_timeout: 15, read_timeout: DEFAULT_TIMEOUT) do |http| klass = case current_method when 'GET' then Net::HTTP::Get when 'POST' then Net::HTTP::Post when 'PATCH' then Net::HTTP::Patch when 'PUT' then Net::HTTP::Put when 'DELETE' then Net::HTTP::Delete when 'HEAD' then Net::HTTP::Head else Net::HTTP::Get end req = klass.new(uri.request_uri) req['Accept'] = 'application/json' req['User-Agent'] = user_agent req['X-Client-Channel'] = 'client_' + LANGUAGE req['X-Client-Version'] = CLIENT_VERSION req['X-Analytics-Device-Id'] = @device_id req['X-Analytics-Session-Id'] = @session_id req['Authorization'] = 'Bearer ' + @token if !strip_auth && !@token.empty? if current_json && current_method != 'GET' && current_method != 'HEAD' req['Content-Type'] = 'application/json' req.body = current_json end resp = http.request(req) status = resp.code.to_i headers = {} resp.each_header { |k, v| headers[k.downcase] = v } if status < 300 || status >= 400 || status == 304 || hop == 5 return [status, headers, resp.body.to_s] end loc = headers['location'] return [status, headers, resp.body.to_s] if loc.nil? || loc.empty? next_uri = (URI.parse(loc).absolute? rescue false) ? URI.parse(loc) : uri + loc if origin_of(next_uri) != origin_of(uri) strip_auth = true end if status == 303 || ([301, 302].include?(status) && current_method != 'GET' && current_method != 'HEAD') current_method = 'GET' current_json = nil end current_url = next_uri.to_s end end [0, {}, ''] end private :send_following_redirects def origin_of(uri) port = uri.port || (uri.scheme == 'https' ? 443 : 80) "#{uri.scheme}://#{uri.host}:#{port}".downcase end private :origin_of def self.backoff_seconds(attempt, retry_after) return [retry_after, 60.0].min if retry_after && retry_after >= 0 [2 ** attempt, 60.0].min.to_f end private_class_method :backoff_seconds def user_agent "#sourdough_client/#{CLIENT_VERSION} (lib/#ruby; ruby/#{RUBY_VERSION})" end private :user_agent # ── Analytics ────────────────────────────────────────────────── def emit_call_event(method, path, status, ok) include_env = nil @meta_lock.synchronize do include_env = !@meta_sent_once @meta_sent_once = true end Thread.new do begin meta = { 'channel' => 'client_' + LANGUAGE, 'client_version' => CLIENT_VERSION, 'module_name' => MODULE_NAME, 'language' => LANGUAGE, 'os' => RUBY_PLATFORM, 'ruby_version' => RUBY_VERSION, } meta['env'] = self.class.send(:fingerprint) if include_env body = { 'device_id' => @device_id, 'session_id' => @session_id, 'events' => [{ 'type' => 'client.call', 'ts_client' => Time.now.to_i, 'meta' => { 'method' => method.to_s.upcase, 'path' => path.split('?').first[0, 128], 'status' => status.to_i, 'ok' => !!ok, }, }], 'meta' => meta, } uri = URI.parse(@base_url + '/xapi2/analytics/challenge') Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https', open_timeout: 2, read_timeout: 4) do |http| req = Net::HTTP::Post.new(uri.request_uri) req['Content-Type'] = 'application/json' req['User-Agent'] = user_agent req.body = JSON.dump(body) http.request(req) end rescue StandardError # fire and forget end end end private :emit_call_event # ── Auto-update ──────────────────────────────────────────────── def maybe_autoupdate return if @autoupdate_tried @autoupdate_tried = true return unless self.class.send(:autoupdate_enabled?) Thread.new { run_autoupdate } end private :maybe_autoupdate def run_autoupdate d = self.class.send(:state_dir) return if d.nil? stamp = File.join(d, 'update_check.json') if File.exist?(stamp) begin blob = JSON.parse(File.read(stamp)) return if (Time.now.to_i - blob['checked_at'].to_i) < 86400 rescue StandardError end end File.write(stamp, JSON.dump('checked_at' => Time.now.to_i)) uri = URI.parse(@base_url + '/xapi2/clients/version') payload = nil Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https', open_timeout: 2, read_timeout: 4) do |http| resp = http.request(Net::HTTP::Get.new(uri.request_uri)) payload = (JSON.parse(resp.body) rescue nil) end return unless payload.is_a?(Hash) && payload['version'] && payload['version'] != CLIENT_VERSION uri2 = URI.parse(@base_url + '/xapi2/clients/script.' + LANGUAGE) body = nil Net::HTTP.start(uri2.host, uri2.port, use_ssl: uri2.scheme == 'https', open_timeout: 2, read_timeout: 10) do |http| body = http.request(Net::HTTP::Get.new(uri2.request_uri)).body end return unless body.is_a?(String) && self.class.send(:looks_like_valid_client?, body) target = File.expand_path(__FILE__) tmp = "#{target}.tmp.#{SecureRandom.hex(6)}" File.write(tmp, body) File.rename(tmp, target) rescue StandardError # best-effort end private :run_autoupdate def self.looks_like_valid_client?(blob) return false unless blob.is_a?(String) && blob.bytesize >= 2000 %w[MODULE_NAME CLIENT_VERSION APP_SLUG request_json].all? { |m| blob.include?(m) } end private_class_method :looks_like_valid_client? # ── Generated per-type wrapper methods ───────────────────────── # Every model that exposes an op gets one `_` method # below. The runtime above does the heavy lifting; these wrappers # just pin the URL + HTTP verb. # List `log_entry` rows. Pass any allowed filters as keyword args. def log_entry_list(**opts) request_list('/xapi2/data/log_entry', opts) end # Fetch one `log_entry` row by id. def log_entry_get(id) request_json('GET', '/xapi2/data/log_entry/' + id, nil) end # Create a new `log_entry` row. def log_entry_create(data) request_json('POST', '/xapi2/data/log_entry', data) end # Patch a `log_entry` row. def log_entry_update(id, data) request_json('PATCH', '/xapi2/data/log_entry/' + id, data) end # Delete a `log_entry` row. Returns true on success. def log_entry_delete(id) request_json('DELETE', '/xapi2/data/log_entry/' + id, nil) true end # List `sourdough` rows. Pass any allowed filters as keyword args. def sourdough_list(**opts) request_list('/xapi2/data/sourdough', opts) end # Fetch one `sourdough` row by id. def sourdough_get(id) request_json('GET', '/xapi2/data/sourdough/' + id, nil) end # Create a new `sourdough` row. def sourdough_create(data) request_json('POST', '/xapi2/data/sourdough', data) end # Patch a `sourdough` row. def sourdough_update(id, data) request_json('PATCH', '/xapi2/data/sourdough/' + id, data) end # Delete a `sourdough` row. Returns true on success. def sourdough_delete(id) request_json('DELETE', '/xapi2/data/sourdough/' + id, nil) true end end end