keinaufwand-sync 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 99d27c728ca508889f1696b869941416fce9bc1edccda9b808b9be1c1945be23
4
- data.tar.gz: d2c70f51bbbfb3f53baeaa0b18c56b23b95914ec93bbe3661ca9bb15424c80b1
3
+ metadata.gz: 40aca6e5323d30d4bb9022e6b704ff911e6822d555a420defc0ad08b93c82cbb
4
+ data.tar.gz: c3b2da274dc98d61c2f076770def04dec09bb825e069e4a53ffcf57aad4fd069
5
5
  SHA512:
6
- metadata.gz: e6fbe5748850a2abb6f6ac2f672afe2ecf7e02400b33ade8b2069fe7bc1602e48dce607bca39d50a70774fcd90bde9fca6c1a0a5740a76a42775dedabf908b96
7
- data.tar.gz: 2f7a1e3e3244914b78e0039167d23db5d835717ba2baac1866a3618d7d93abb8b159da78a593d526249b6fc7944af6e5bbb800317124e3607bdde6a84084af50
6
+ metadata.gz: d135eeff55448b8d304455c22f330a8dbd06196a2edf28dce6bdd4d41b429ecb41c416bdb88d29ad303aedc676b349f27c6c3d9ece183ce7a801fdbf7b0eed14
7
+ data.tar.gz: 0bfc2c7b15e855aafd3f5f854413950072e1b6de16262aabda182e1c47d6bf71f720e998d28f7d7b249247236e606f333da7484f67fdffd2dbda8b1904eb9472
data/config/routes.rb CHANGED
@@ -1,3 +1,3 @@
1
1
  Keinaufwand::Sync::Engine.routes.draw do
2
- post "/", to: "webhooks#receive"
2
+ post '/', to: 'webhooks#receive'
3
3
  end
@@ -1,5 +1,5 @@
1
- require "rails/generators"
2
- require "rails/generators/active_record"
1
+ require 'rails/generators'
2
+ require 'rails/generators/active_record'
3
3
 
4
4
  module Keinaufwand
5
5
  module Sync
@@ -11,14 +11,14 @@ module Keinaufwand
11
11
  operations = manager.migration_operations
12
12
 
13
13
  if operations.empty?
14
- say "Keinaufwand sync indexes are already up to date."
14
+ say 'Keinaufwand sync indexes are already up to date.'
15
15
  return
16
16
  end
17
17
 
18
- migration_number = self.class.next_migration_number(File.join(destination_root, "db/migrate"))
18
+ migration_number = self.class.next_migration_number(File.join(destination_root, 'db/migrate'))
19
19
  class_name = "UpdateKeinaufwandSyncIndexes#{migration_number}"
20
20
  source = manager.migration_source(class_name: class_name)
21
- create_file File.join("db/migrate", "#{migration_number}_#{class_name.underscore}.rb"), source
21
+ create_file File.join('db/migrate', "#{migration_number}_#{class_name.underscore}.rb"), source
22
22
  end
23
23
  end
24
24
  end
@@ -1,20 +1,20 @@
1
- require "rails/generators"
2
- require "rails/generators/active_record"
1
+ require 'rails/generators'
2
+ require 'rails/generators/active_record'
3
3
 
4
4
  module Keinaufwand
5
5
  module Sync
6
6
  class InstallGenerator < Rails::Generators::Base
7
7
  include ActiveRecord::Generators::Migration
8
8
 
9
- source_root File.expand_path("templates", __dir__)
9
+ source_root File.expand_path('templates', __dir__)
10
10
 
11
- class_option :media_route, type: :boolean, default: true, desc: "Mount /media/:id for synced Keinaufwand assets"
12
- class_option :webhook_route, type: :boolean, default: true, desc: "Mount the signed Keinaufwand webhook receiver"
11
+ class_option :media_route, type: :boolean, default: true, desc: 'Mount /media/:id for synced Keinaufwand assets'
12
+ class_option :webhook_route, type: :boolean, default: true, desc: 'Mount the signed Keinaufwand webhook receiver'
13
13
 
14
14
  def copy_migrations
15
- migration_template "create_keinaufwand_sync_tables.rb", "db/migrate/create_keinaufwand_sync_tables.rb"
16
- migration_template "create_keinaufwand_assets.rb", "db/migrate/create_keinaufwand_assets.rb"
17
- migration_template "create_keinaufwand_webhook_receipts.rb", "db/migrate/create_keinaufwand_webhook_receipts.rb"
15
+ migration_template 'create_keinaufwand_sync_tables.rb', 'db/migrate/create_keinaufwand_sync_tables.rb'
16
+ migration_template 'create_keinaufwand_assets.rb', 'db/migrate/create_keinaufwand_assets.rb'
17
+ migration_template 'create_keinaufwand_webhook_receipts.rb', 'db/migrate/create_keinaufwand_webhook_receipts.rb'
18
18
  end
19
19
 
20
20
  def add_webhook_route
@@ -28,8 +28,6 @@ module Keinaufwand
28
28
 
29
29
  route %(get "media/:id", to: "keinaufwand/assets#show", as: :keinaufwand_asset)
30
30
  end
31
-
32
-
33
31
  end
34
32
  end
35
33
  end
@@ -8,7 +8,7 @@ module Keinaufwand
8
8
  return source_url unless asset_url?(source_url)
9
9
 
10
10
  key = key_for(source_url)
11
- exists?(key:) ? "#{Sync.configuration.local_asset_path_prefix}/#{key}" : source_url
11
+ exists?(key: key) ? "#{Sync.configuration.local_asset_path_prefix}/#{key}" : source_url
12
12
  end
13
13
  end
14
14
  end
@@ -3,10 +3,10 @@ module Keinaufwand
3
3
  def show
4
4
  asset = Asset.find(params[:id])
5
5
 
6
- if stale?(etag: asset.checksum, last_modified: asset.synced_at, public: true)
7
- expires_in 1.year, public: true
8
- send_data asset.data, type: asset.content_type, disposition: "inline"
9
- end
6
+ return unless stale?(etag: asset.checksum, last_modified: asset.synced_at, public: true)
7
+
8
+ expires_in 1.year, public: true
9
+ send_data asset.data, type: asset.content_type, disposition: 'inline'
10
10
  end
11
11
  end
12
12
  end
@@ -1,30 +1,30 @@
1
- require "active_record"
2
- require "action_controller/railtie"
3
- require "active_support/core_ext/object/blank"
4
- require "bigdecimal/util"
5
- require "cgi"
6
- require "digest"
7
- require "net/http"
8
- require "openssl"
9
- require "uri"
10
- require "yaml"
11
- require "active_support/core_ext/numeric/time"
12
- require "keinaufwand/api"
1
+ require 'active_record'
2
+ require 'action_controller/railtie'
3
+ require 'active_support/core_ext/object/blank'
4
+ require 'bigdecimal/util'
5
+ require 'cgi'
6
+ require 'digest'
7
+ require 'net/http'
8
+ require 'openssl'
9
+ require 'uri'
10
+ require 'yaml'
11
+ require 'active_support/core_ext/numeric/time'
12
+ require 'keinaufwand/api'
13
13
 
14
- require_relative "sync_core/version"
15
- require_relative "sync_core/configuration"
16
- require_relative "sync_core/asset"
17
- require_relative "sync_core/record"
18
- require_relative "sync_core/sync_state"
19
- require_relative "sync_core/webhook_receipt"
20
- require_relative "sync_core/sync_service"
21
- require_relative "sync_core/webhook_processor"
22
- require_relative "sync_core/webhooks_controller" if defined?(ActionController::API)
23
- require_relative "sync_core/index_manager"
24
- require_relative "sync_core/engine" if defined?(Rails::Engine)
25
- require_relative "sync_core/railtie" if defined?(Rails::Railtie)
26
- require_relative "record"
27
- require_relative "asset"
28
- require_relative "sync_state"
29
- require_relative "webhook_receipt"
30
- require_relative "assets_controller" if defined?(ActionController::Base)
14
+ require_relative 'sync_core/version'
15
+ require_relative 'sync_core/configuration'
16
+ require_relative 'sync_core/asset'
17
+ require_relative 'sync_core/record'
18
+ require_relative 'sync_core/sync_state'
19
+ require_relative 'sync_core/webhook_receipt'
20
+ require_relative 'sync_core/sync_service'
21
+ require_relative 'sync_core/webhook_processor'
22
+ require_relative 'sync_core/webhooks_controller' if defined?(ActionController::API)
23
+ require_relative 'sync_core/index_manager'
24
+ require_relative 'sync_core/engine' if defined?(Rails::Engine)
25
+ require_relative 'sync_core/railtie' if defined?(Rails::Railtie)
26
+ require_relative 'record'
27
+ require_relative 'asset'
28
+ require_relative 'sync_state'
29
+ require_relative 'webhook_receipt'
30
+ require_relative 'assets_controller' if defined?(ActionController::Base)
@@ -2,25 +2,25 @@ module Keinaufwand
2
2
  module Sync
3
3
  class Asset < ActiveRecord::Base
4
4
  self.abstract_class = true
5
- self.table_name = "keinaufwand_assets"
5
+ self.table_name = 'keinaufwand_assets'
6
6
  self.primary_key = :key
7
7
 
8
- ASSET_URL_PATTERN = %r{\Ahttps?://.+/shrine/(?:production|development)/(?:store|cache)/}.freeze
9
- URL_PATTERN = %r{https?://[^"'<>\s\\]+}.freeze
8
+ ASSET_URL_PATTERN = %r{\Ahttps?://.+/shrine/(?:production|development)/(?:store|cache)/}
9
+ URL_PATTERN = %r{https?://[^"'<>\s\\]+}
10
10
 
11
11
  def self.sync_url(source_url)
12
12
  return unless asset_url?(source_url)
13
13
 
14
14
  key = key_for(source_url)
15
- return find_by(key:) if exists?(key:)
15
+ return find_by(key: key) if exists?(key: key)
16
16
 
17
17
  response = fetch(source_url)
18
18
  body = response.body.to_s.b
19
- content_type = response["content-type"].to_s.split(";").first
19
+ content_type = response['content-type'].to_s.split(';').first
20
20
  create!(
21
21
  key: key,
22
22
  source_url: source_url,
23
- content_type: content_type.empty? ? "application/octet-stream" : content_type,
23
+ content_type: content_type.empty? ? 'application/octet-stream' : content_type,
24
24
  byte_size: body.bytesize,
25
25
  checksum: Digest::SHA256.hexdigest(body),
26
26
  data: body,
@@ -52,14 +52,14 @@ module Keinaufwand
52
52
  end
53
53
 
54
54
  def self.fetch(url, limit = 3)
55
- raise ArgumentError, "too many redirects for #{url}" if limit < 0
55
+ raise ArgumentError, "too many redirects for #{url}" if limit.negative?
56
56
 
57
57
  uri = URI(url)
58
- response = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https") do |http|
58
+ response = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https') do |http|
59
59
  http.get(uri.request_uri)
60
60
  end
61
61
 
62
- return fetch(response["location"], limit - 1) if response.is_a?(Net::HTTPRedirection)
62
+ return fetch(response['location'], limit - 1) if response.is_a?(Net::HTTPRedirection)
63
63
  raise "Could not fetch #{url}: #{response.code}" unless response.is_a?(Net::HTTPSuccess)
64
64
 
65
65
  response
@@ -8,7 +8,7 @@ module Keinaufwand
8
8
  @sync_state_class = -> { Keinaufwand::SyncState }
9
9
  @asset_class = -> { Keinaufwand::Asset }
10
10
  @webhook_receipt_class = -> { Keinaufwand::WebhookReceipt }
11
- @local_asset_path_prefix = "/media"
11
+ @local_asset_path_prefix = '/media'
12
12
  end
13
13
 
14
14
  def sync_service(output: nil)
@@ -17,7 +17,7 @@ module Keinaufwand
17
17
  record_class: fetch(:record_class),
18
18
  sync_state_class: fetch(:sync_state_class),
19
19
  receipt_class: resolve(:webhook_receipt_class),
20
- resources: resources || sync_config.map { |item| item.fetch("model") }.presence || SyncService::DEFAULT_RESOURCES,
20
+ resources: resources || sync_config.map { |item| item.fetch('model') }.presence || SyncService::DEFAULT_RESOURCES,
21
21
  asset_class: resolve(:asset_class),
22
22
  output: output
23
23
  )
@@ -38,7 +38,7 @@ module Keinaufwand
38
38
  payload: payload,
39
39
  record_class: fetch(:record_class),
40
40
  receipt_class: fetch(:webhook_receipt_class),
41
- resources: resources || sync_config.map { |item| item.fetch("model") }.presence || SyncService::DEFAULT_RESOURCES,
41
+ resources: resources || sync_config.map { |item| item.fetch('model') }.presence || SyncService::DEFAULT_RESOURCES,
42
42
  asset_class: resolve(:asset_class)
43
43
  )
44
44
  end
@@ -76,7 +76,7 @@ module Keinaufwand
76
76
  end
77
77
 
78
78
  def resolved_config_path
79
- resolve(:config_path) || (Rails.root.join("config/keinaufwand.yml") if defined?(Rails))
79
+ resolve(:config_path) || (Rails.root.join('config/keinaufwand.yml') if defined?(Rails))
80
80
  end
81
81
  end
82
82
 
@@ -1,7 +1,7 @@
1
1
  module Keinaufwand
2
2
  module Sync
3
3
  class IndexManager
4
- TABLE_NAME = "keinaufwand_records"
4
+ TABLE_NAME = 'keinaufwand_records'.freeze
5
5
 
6
6
  def initialize(sync_config: [], adapter: :sqlite3)
7
7
  @sync_config = sync_config
@@ -10,8 +10,8 @@ module Keinaufwand
10
10
 
11
11
  def desired_indices
12
12
  @sync_config.each_with_object({}) do |item, indices|
13
- model = item.fetch("model")
14
- Array(item["indices"]).each do |attribute|
13
+ model = item.fetch('model')
14
+ Array(item['indices']).each do |attribute|
15
15
  indices.merge!(build_index(model, attribute))
16
16
  end
17
17
  end
@@ -31,7 +31,7 @@ module Keinaufwand
31
31
  current_index_names(connection) - desired_indices.keys
32
32
  end
33
33
 
34
- def migration_source(class_name: "UpdateKeinaufwandSyncIndexes", mode: :diff)
34
+ def migration_source(class_name: 'UpdateKeinaufwandSyncIndexes', mode: :diff)
35
35
  operations = migration_operations(mode: mode)
36
36
 
37
37
  <<~RUBY
@@ -61,7 +61,7 @@ module Keinaufwand
61
61
 
62
62
  def build_index(model, attribute)
63
63
  attribute = attribute.to_s
64
- name = "idx_keinaufwand_#{model.underscore}_#{attribute.tr("^a-zA-Z0-9_", "_")}"
64
+ name = "idx_keinaufwand_#{model.underscore}_#{attribute.tr('^a-zA-Z0-9_', '_')}"
65
65
 
66
66
  {
67
67
  name => {
@@ -73,7 +73,7 @@ module Keinaufwand
73
73
 
74
74
  def json_value_expression(attribute)
75
75
  if @adapter == :postgres || @adapter == :postgresql
76
- "data #>> '{#{attribute.split(".").join(",")}}'"
76
+ "data #>> '{#{attribute.split('.').join(',')}}'"
77
77
  else
78
78
  "json_extract(data, '$.#{attribute}')"
79
79
  end
@@ -2,7 +2,7 @@ module Keinaufwand
2
2
  module Sync
3
3
  class Railtie < Rails::Railtie
4
4
  rake_tasks do
5
- load File.expand_path("tasks/keinaufwand_sync.rake", __dir__)
5
+ load File.expand_path('tasks/keinaufwand_sync.rake', __dir__)
6
6
  end
7
7
  end
8
8
  end
@@ -2,7 +2,7 @@ module Keinaufwand
2
2
  module Sync
3
3
  class Record < ActiveRecord::Base
4
4
  self.abstract_class = true
5
- self.table_name = "keinaufwand_records"
5
+ self.table_name = 'keinaufwand_records'
6
6
  self.primary_key = [:id, :type]
7
7
 
8
8
  class_attribute :keinaufwand_schema, instance_writer: false
@@ -15,7 +15,7 @@ module Keinaufwand
15
15
  def self.where_present(*attributes)
16
16
  attributes.reduce(all) do |scope, attribute|
17
17
  expression = json_value(attribute)
18
- scope.where("#{expression} IS NOT NULL").where("#{expression} != ?", "")
18
+ scope.where("#{expression} IS NOT NULL").where("#{expression} != ?", '')
19
19
  end
20
20
  end
21
21
 
@@ -25,26 +25,24 @@ module Keinaufwand
25
25
  ids = ids.flatten
26
26
  return where(id: ids).index_by(&:id).values_at(*ids.map(&:to_i)) if ids.many?
27
27
 
28
- find_by!(id: ids.first)
28
+ find_by!(id: ids.first) # rubocop:disable Rails/FindById -- `find` is this method.
29
29
  end
30
30
 
31
31
  def self.exists?(conditions = :none)
32
- if composite_primary_key? && conditions != :none && !conditions.is_a?(Hash) && !conditions.is_a?(Array)
33
- return super(id: conditions)
34
- end
32
+ return super(id: conditions) if composite_primary_key? && conditions != :none && !conditions.is_a?(Hash) && !conditions.is_a?(Array)
35
33
 
36
34
  super
37
35
  end
38
36
 
39
37
  def self.json_value(attribute)
40
38
  table = connection.quote_table_name(table_name)
41
- column = connection.quote_column_name("data")
39
+ column = connection.quote_column_name('data')
42
40
  json_value_expression("#{table}.#{column}", attribute)
43
41
  end
44
42
 
45
43
  def self.json_value_expression(column, attribute)
46
44
  if connection.adapter_name.match?(/postgres/i)
47
- expression = "#{column} #>> #{connection.quote("{#{attribute.to_s.split(".").join(",")}}")}"
45
+ expression = "#{column} #>> #{connection.quote("{#{attribute.to_s.split('.').join(',')}}")}"
48
46
  postgres_cast(expression, attribute)
49
47
  else
50
48
  expression = "json_extract(#{column}, #{connection.quote("$.#{attribute}")})"
@@ -53,7 +51,7 @@ module Keinaufwand
53
51
  end
54
52
 
55
53
  def self.json_attribute?(attribute)
56
- !column_names.include?(attribute.to_s) && schema_attribute?(attribute)
54
+ column_names.exclude?(attribute.to_s) && schema_attribute?(attribute)
57
55
  end
58
56
 
59
57
  def self.schema
@@ -61,7 +59,7 @@ module Keinaufwand
61
59
  end
62
60
 
63
61
  def self.load_keinaufwand_schema
64
- version = Keinaufwand::Api.configuration.version || "2026-07-02"
62
+ version = Keinaufwand::Api.configuration.version
65
63
  self.keinaufwand_schema = Keinaufwand::Api::Schema.load(Keinaufwand::Api.configuration.schema_path(version))
66
64
  end
67
65
 
@@ -70,21 +68,21 @@ module Keinaufwand
70
68
  end
71
69
 
72
70
  def self.schema_attributes
73
- model_schema&.fetch("attributes", {}) || {}
71
+ model_schema&.fetch('attributes', {}) || {}
74
72
  end
75
73
 
76
74
  def self.schema_associations
77
- model_schema&.fetch("associations", {}) || {}
75
+ model_schema&.fetch('associations', {}) || {}
78
76
  end
79
77
 
80
78
  def self.schema_attribute?(attribute)
81
79
  attribute = attribute.to_s
82
- schema_attributes.key?(attribute) || schema_attributes.key?(attribute.split(".").first)
80
+ schema_attributes.key?(attribute) || schema_attributes.key?(attribute.split('.').first)
83
81
  end
84
82
 
85
83
  def self.schema_attribute_type(attribute)
86
84
  attribute = attribute.to_s
87
- (schema_attributes[attribute].presence || schema_attributes[attribute.split(".").first]).to_s
85
+ (schema_attributes[attribute].presence || schema_attributes[attribute.split('.').first]).to_s
88
86
  end
89
87
 
90
88
  def self.inherited(subclass)
@@ -93,7 +91,7 @@ module Keinaufwand
93
91
  end
94
92
 
95
93
  def self.boot_keinaufwand_dynamics!
96
- return if abstract_class? || name.blank? || name == "Keinaufwand::Record"
94
+ return if abstract_class? || name.blank? || name == 'Keinaufwand::Record'
97
95
 
98
96
  schema_attributes.each_key do |attribute|
99
97
  define_dynamic_attribute(attribute)
@@ -108,7 +106,7 @@ module Keinaufwand
108
106
 
109
107
  def self.define_dynamic_attribute(attribute)
110
108
  attribute = attribute.to_s
111
- return if attribute == "id"
109
+ return if attribute == 'id'
112
110
 
113
111
  define_method(attribute) do |variant = :large|
114
112
  value = read_keinaufwand_value(attribute)
@@ -116,7 +114,7 @@ module Keinaufwand
116
114
  value = derivative_value(value, variant)
117
115
  value = local_asset_url(value) if respond_to?(:local_asset_url)
118
116
  end
119
- value = localize_asset_urls(value) if attribute == "body" && respond_to?(:localize_asset_urls)
117
+ value = localize_asset_urls(value) if attribute == 'body' && respond_to?(:localize_asset_urls)
120
118
  cast_keinaufwand_value(attribute, value)
121
119
  end
122
120
 
@@ -132,8 +130,8 @@ module Keinaufwand
132
130
  type = config[:type].to_s
133
131
  target_class_name = config[:class_name] || association.singularize.classify
134
132
 
135
- define_dynamic_foreign_key(association, type) if %w[belongs_to has_one].include?(type)
136
- define_dynamic_ids(association) if type == "has_and_belongs_to_many"
133
+ define_dynamic_foreign_key(association) if ['belongs_to', 'has_one'].include?(type)
134
+ define_dynamic_ids(association) if type == 'has_and_belongs_to_many'
137
135
 
138
136
  define_method(association) do
139
137
  return instance_variable_get("@#{association}") if instance_variable_defined?("@#{association}")
@@ -148,7 +146,7 @@ module Keinaufwand
148
146
  end
149
147
  end
150
148
 
151
- def self.define_dynamic_foreign_key(association, type)
149
+ def self.define_dynamic_foreign_key(association)
152
150
  key = "#{association}_id"
153
151
  return if schema_attribute?(key)
154
152
 
@@ -168,19 +166,19 @@ module Keinaufwand
168
166
 
169
167
  def self.postgres_cast(expression, attribute)
170
168
  case schema_attribute_type(attribute)
171
- when "integer" then "(#{expression})::integer"
172
- when "float", "decimal" then "(#{expression})::numeric"
173
- when "date" then "(#{expression})::date"
174
- when "datetime", "time" then "(#{expression})::timestamp"
175
- when "boolean" then "(#{expression})::boolean"
169
+ when 'integer' then "(#{expression})::integer"
170
+ when 'float', 'decimal' then "(#{expression})::numeric"
171
+ when 'date' then "(#{expression})::date"
172
+ when 'datetime', 'time' then "(#{expression})::timestamp"
173
+ when 'boolean' then "(#{expression})::boolean"
176
174
  else expression
177
175
  end
178
176
  end
179
177
 
180
178
  def self.sqlite_cast(expression, attribute)
181
179
  case schema_attribute_type(attribute)
182
- when "integer" then "CAST(#{expression} AS INTEGER)"
183
- when "float", "decimal" then "CAST(#{expression} AS REAL)"
180
+ when 'integer' then "CAST(#{expression} AS INTEGER)"
181
+ when 'float', 'decimal' then "CAST(#{expression} AS REAL)"
184
182
  else expression
185
183
  end
186
184
  end
@@ -216,7 +214,7 @@ module Keinaufwand
216
214
  json_value(argument)
217
215
  when Hash
218
216
  argument.map do |attribute, direction|
219
- direction = direction.to_s.downcase == "desc" ? "DESC" : "ASC"
217
+ direction = direction.to_s.downcase == 'desc' ? 'DESC' : 'ASC'
220
218
  "#{json_value(attribute)} #{direction}"
221
219
  end
222
220
  end
@@ -227,7 +225,7 @@ module Keinaufwand
227
225
 
228
226
  case value
229
227
  when Array
230
- return "1=0" if value.empty?
228
+ return '1=0' if value.empty?
231
229
  return "(#{expression} IN (?) OR #{expression} IS NULL)" if value.include?(nil)
232
230
 
233
231
  "#{expression} IN (?)"
@@ -264,9 +262,7 @@ module Keinaufwand
264
262
 
265
263
  def self.json_bind_value(value)
266
264
  case value
267
- when Time, ActiveSupport::TimeWithZone
268
- value.iso8601
269
- when Date
265
+ when Time, ActiveSupport::TimeWithZone, Date
270
266
  value.iso8601
271
267
  else
272
268
  value
@@ -279,11 +275,11 @@ module Keinaufwand
279
275
 
280
276
  def id=(value)
281
277
  if value.is_a?(Array)
282
- write_keinaufwand_column("id", value.first)
283
- write_keinaufwand_column("type", value.second)
278
+ write_keinaufwand_column('id', value.first)
279
+ write_keinaufwand_column('type', value.second)
284
280
  else
285
- write_keinaufwand_column("id", value)
286
- write_keinaufwand_column("type", self.class.name) if self[:type].blank? && self.class.name.present?
281
+ write_keinaufwand_column('id', value)
282
+ write_keinaufwand_column('type', self.class.name) if self[:type].blank? && self.class.name.present?
287
283
  end
288
284
  end
289
285
 
@@ -310,15 +306,15 @@ module Keinaufwand
310
306
  inline_value = read_keinaufwand_value(association)
311
307
 
312
308
  case type
313
- when "belongs_to", "has_one"
309
+ when 'belongs_to', 'has_one'
314
310
  target_id = read_keinaufwand_value("#{association}_id")
315
311
  local = target_class.find_by(id: target_id) if target_id.present?
316
312
  local || build_inline_keinaufwand_records(inline_value, target_class)
317
- when "has_many"
313
+ when 'has_many'
318
314
  foreign_key = config[:foreign_key] || "#{self.class.name.demodulize.underscore}_id"
319
315
  local = target_class.where(foreign_key => id)
320
316
  local.exists? ? local : build_inline_keinaufwand_records(inline_value, target_class)
321
- when "has_and_belongs_to_many"
317
+ when 'has_and_belongs_to_many'
322
318
  target_ids = Array(read_keinaufwand_value("#{association.singularize}_ids"))
323
319
  target_class.where(id: target_ids)
324
320
  else
@@ -328,7 +324,7 @@ module Keinaufwand
328
324
 
329
325
  def build_inline_keinaufwand_records(value, target_class)
330
326
  if value.is_a?(Array)
331
- value.map { |attributes| build_inline_keinaufwand_record(attributes, target_class) }.compact
327
+ value.filter_map { |attributes| build_inline_keinaufwand_record(attributes, target_class) }
332
328
  elsif value.is_a?(Hash)
333
329
  build_inline_keinaufwand_record(value, target_class)
334
330
  end
@@ -337,23 +333,23 @@ module Keinaufwand
337
333
  def build_inline_keinaufwand_record(attributes, target_class)
338
334
  return unless attributes.is_a?(Hash)
339
335
 
340
- target_class.new(id: attributes["id"] || attributes[:id], type: target_class.name, data: attributes.except("id", :id))
336
+ target_class.new(id: attributes['id'] || attributes[:id], type: target_class.name, data: attributes.except('id', :id))
341
337
  end
342
338
 
343
339
  def cast_keinaufwand_value(attribute, value)
344
340
  case self.class.schema_attribute_type(attribute)
345
- when "datetime", "time" then parse_keinaufwand_time(value) || value
346
- when "date" then parse_keinaufwand_date(value) || value
347
- when "integer" then value.to_i if value.present?
348
- when "float" then value.to_f if value.present?
349
- when "decimal" then value.to_d if value.present?
350
- when "boolean" then value == true || value.to_s == "true"
341
+ when 'datetime', 'time' then parse_keinaufwand_time(value) || value
342
+ when 'date' then parse_keinaufwand_date(value) || value
343
+ when 'integer' then value.presence&.to_i
344
+ when 'float' then value.presence&.to_f
345
+ when 'decimal' then value.presence&.to_d
346
+ when 'boolean' then value == true || value.to_s == 'true'
351
347
  else value
352
348
  end
353
349
  end
354
350
 
355
351
  def parse_keinaufwand_time(value)
356
- return value if value.is_a?(Time) || defined?(ActiveSupport::TimeWithZone) && value.is_a?(ActiveSupport::TimeWithZone)
352
+ return value if value.is_a?(Time) || (defined?(ActiveSupport::TimeWithZone) && value.is_a?(ActiveSupport::TimeWithZone))
357
353
  return if value.blank?
358
354
 
359
355
  Time.zone ? Time.zone.parse(value.to_s) : Time.parse(value.to_s)
@@ -371,7 +367,7 @@ module Keinaufwand
371
367
  end
372
368
 
373
369
  def asset_attribute?(attribute, value)
374
- attribute.end_with?("_url") && value.is_a?(Hash)
370
+ attribute.end_with?('_url') && value.is_a?(Hash)
375
371
  end
376
372
 
377
373
  def derivative_value(value, size)
@@ -393,7 +389,7 @@ module Keinaufwand
393
389
  def order(*args)
394
390
  return super unless keinaufwand_record_relation? && args.any? && args.all? { |arg| klass.json_order_argument?(arg) }
395
391
 
396
- super(Arel.sql(args.flat_map { |arg| klass.json_order_sql(arg) }.join(", ")))
392
+ super(Arel.sql(args.flat_map { |arg| klass.json_order_sql(arg) }.join(', ')))
397
393
  end
398
394
 
399
395
  private
@@ -1,8 +1,8 @@
1
1
  module Keinaufwand
2
2
  module Sync
3
3
  class SyncService
4
- DEFAULT_RESOURCES = %w[
5
- Location Product Session EventDetail Event Post InstructorGroup
4
+ DEFAULT_RESOURCES = [
5
+ 'Location', 'Product', 'Session', 'EventDetail', 'Event', 'Post', 'StaffTeam'
6
6
  ].freeze
7
7
 
8
8
  def initialize(client:, record_class:, sync_state_class:, resources: DEFAULT_RESOURCES, asset_class: nil, receipt_class: nil, output: nil)
@@ -20,14 +20,12 @@ module Keinaufwand
20
20
  succeeded = 0
21
21
  log "Starting Keinaufwand Sync (#{@resources.size} resources)"
22
22
  @resources.each_with_index do |resource, index|
23
- begin
24
- sync_resource(resource, index + 1)
25
- succeeded += 1
26
- rescue StandardError => error
27
- log "!! FAILED #{resource}: #{error.message}"
28
- log "Sync stopped (#{succeeded}/#{@resources.size} succeeded)"
29
- raise
30
- end
23
+ sync_resource(resource, index + 1)
24
+ succeeded += 1
25
+ rescue StandardError => e
26
+ log "!! FAILED #{resource}: #{e.message}"
27
+ log "Sync stopped (#{succeeded}/#{@resources.size} succeeded)"
28
+ raise
31
29
  end
32
30
  log "Sync Process Completed in #{format('%.2f', monotonic_time - started)}s (#{succeeded}/#{@resources.size} succeeded)"
33
31
  end
@@ -48,10 +46,10 @@ module Keinaufwand
48
46
  fetch_started = monotonic_time
49
47
  page = @client.public_send("retrieve_#{resource.pluralize.underscore}", params)
50
48
  timings[:fetch] += monotonic_time - fetch_started
51
- total = page.meta.dig("pagination", "count") if page.respond_to?(:meta)
49
+ total = page.meta.dig('pagination', 'count') if page.respond_to?(:meta)
52
50
  latest = nil
53
51
 
54
- while page && !page.empty?
52
+ while page.present?
55
53
  log " Page #{pages + 1}: syncing #{page.count} records#{' and media' if @asset_class}..."
56
54
  media_started = monotonic_time
57
55
  page.each do |record|
@@ -80,18 +78,18 @@ module Keinaufwand
80
78
  { id: record.id, type: resource, data: record.raw_attributes.except(:id), created_at: Time.current, updated_at: Time.current }
81
79
  end
82
80
 
83
- @record_class.upsert_all(rows, unique_by: %i[id type], update_only: %w[data updated_at]) if rows.any?
81
+ @record_class.upsert_all(rows, unique_by: [:id, :type], update_only: ['data', 'updated_at']) if rows.any?
84
82
  end
85
83
  timings[:write] += monotonic_time - write_started
86
84
  stats.merge!(page_stats) { |_key, total, count| total + count }
87
85
  pages += 1
88
86
  processed += page.count
89
87
  rate = processed / [monotonic_time - started, 0.001].max
90
- progress = total && total.positive? ? "#{processed}/#{total} (#{[processed * 100 / total, 100].min}%)" : processed.to_s
91
- eta = total && total.positive? ? "#{format('%.0f', [total - processed, 0].max / rate)}s" : "unknown"
88
+ progress = total&.positive? ? "#{processed}/#{total} (#{[processed * 100 / total, 100].min}%)" : processed.to_s
89
+ eta = total&.positive? ? "#{format('%.0f', [total - processed, 0].max / rate)}s" : 'unknown'
92
90
  log " Processed: #{progress} (New: #{stats[:created]} | Upd: #{stats[:updated]} | Del: #{stats[:destroyed]} | Skip: #{stats[:skipped]}) [#{format('%.1f', rate)} records/s | ETA: #{eta}]"
93
91
 
94
- log " Fetching next page..." if page.respond_to?(:meta) && page.meta.dig("pagination", "next")
92
+ log ' Fetching next page...' if page.respond_to?(:meta) && page.meta.dig('pagination', 'next')
95
93
  fetch_started = monotonic_time
96
94
  page = page.next
97
95
  timings[:fetch] += monotonic_time - fetch_started
@@ -121,7 +119,7 @@ module Keinaufwand
121
119
  return false unless record.server_updated_at
122
120
 
123
121
  stored = @record_class.where(type: resource, id: record.id).pick(:data)
124
- timestamp = stored&.fetch("updated_at", nil)
122
+ timestamp = stored&.fetch('updated_at', nil)
125
123
  timestamps = [
126
124
  (Time.iso8601(timestamp) if timestamp.present?),
127
125
  @receipt_class&.latest_source_updated_at(resource, record.id)
@@ -136,8 +134,8 @@ module Keinaufwand
136
134
  def sync_assets(attributes)
137
135
  @asset_class.urls_from(attributes).uniq.each do |url|
138
136
  @asset_class.sync_url(url)
139
- rescue StandardError => error
140
- warn "Skipping Keinaufwand asset #{url}: #{error.message}"
137
+ rescue StandardError => e
138
+ warn "Skipping Keinaufwand asset #{url}: #{e.message}"
141
139
  end
142
140
  end
143
141
  end
@@ -2,7 +2,7 @@ module Keinaufwand
2
2
  module Sync
3
3
  class SyncState < ActiveRecord::Base
4
4
  self.abstract_class = true
5
- self.table_name = "keinaufwand_sync_states"
5
+ self.table_name = 'keinaufwand_sync_states'
6
6
  self.primary_key = :resource_class
7
7
 
8
8
  def self.inherited(subclass)
@@ -1,19 +1,19 @@
1
1
  namespace :keinaufwand do
2
- desc "Sync Keinaufwand API records into local storage"
2
+ desc 'Sync Keinaufwand API records into local storage'
3
3
  task sync: :environment do
4
4
  Keinaufwand::Sync.sync!
5
5
  end
6
6
 
7
- desc "Clear local Keinaufwand records and run a fresh sync"
7
+ desc 'Clear local Keinaufwand records and run a fresh sync'
8
8
  task resync: :environment do
9
9
  Keinaufwand::Sync.resync!
10
10
  end
11
11
 
12
12
  namespace :indices do
13
- desc "Generate a migration for Keinaufwand JSON indexes from config/keinaufwand.yml"
13
+ desc 'Generate a migration for Keinaufwand JSON indexes from config/keinaufwand.yml'
14
14
  task generate: :environment do
15
- require "rails/generators"
16
- Rails::Generators.invoke("keinaufwand:sync:indexes", [], destination_root: Rails.root.to_s)
15
+ require 'rails/generators'
16
+ Rails::Generators.invoke('keinaufwand:sync:indexes', [], destination_root: Rails.root.to_s)
17
17
  end
18
18
  end
19
19
  end
@@ -1,5 +1,5 @@
1
1
  module Keinaufwand
2
2
  module Sync
3
- VERSION = "0.1.1"
3
+ VERSION = '0.2.0'.freeze
4
4
  end
5
5
  end
@@ -30,11 +30,11 @@ module Keinaufwand
30
30
  private
31
31
 
32
32
  def validate_payload!
33
- raise InvalidPayload, "event_id is required" if event_id.blank?
34
- raise InvalidPayload, "event_type is required" if event_type.blank?
35
- raise InvalidPayload, "api_version is required" if api_version.blank?
36
- raise InvalidPayload, "data must be an object" unless data.is_a?(Hash)
37
- raise InvalidPayload, "data.id is required" if resource_id.blank?
33
+ raise InvalidPayload, 'event_id is required' if event_id.blank?
34
+ raise InvalidPayload, 'event_type is required' if event_type.blank?
35
+ raise InvalidPayload, 'api_version is required' if api_version.blank?
36
+ raise InvalidPayload, 'data must be an object' unless data.is_a?(Hash)
37
+ raise InvalidPayload, 'data.id is required' if resource_id.blank?
38
38
  raise InvalidPayload, "unsupported API version #{api_version}" unless schema.version == api_version
39
39
  end
40
40
 
@@ -44,7 +44,7 @@ module Keinaufwand
44
44
 
45
45
  def resource_type
46
46
  @resource_type ||= schema.model_names.find do |model_name|
47
- schema.for(model_name).fetch(:resource_name).singularize == event_type.split(".").first
47
+ schema.for(model_name).fetch(:resource_name).singularize == event_type.split('.').first
48
48
  end
49
49
  end
50
50
 
@@ -57,7 +57,7 @@ module Keinaufwand
57
57
  end
58
58
 
59
59
  def existing_record_updated_at
60
- value = local_record&.data&.fetch("updated_at", nil)
60
+ value = local_record&.data&.fetch('updated_at', nil)
61
61
  Time.iso8601(value) if value.present?
62
62
  rescue ArgumentError
63
63
  nil
@@ -79,7 +79,7 @@ module Keinaufwand
79
79
  event_id: event_id,
80
80
  event_type: event_type,
81
81
  api_version: api_version,
82
- resource_type: resource_type || event_type.split(".").first.classify,
82
+ resource_type: resource_type || event_type.split('.').first.classify,
83
83
  resource_id: resource_id,
84
84
  source_updated_at: source_updated_at,
85
85
  result: result.to_s,
@@ -93,13 +93,15 @@ module Keinaufwand
93
93
 
94
94
  @asset_class.urls_from(data).uniq.each do |url|
95
95
  @asset_class.sync_url(url)
96
- rescue StandardError => error
97
- warn "Skipping Keinaufwand asset #{url}: #{error.message}"
96
+ rescue StandardError => e
97
+ warn "Skipping Keinaufwand asset #{url}: #{e.message}"
98
98
  end
99
99
  end
100
100
 
101
101
  def local_record
102
- @local_record ||= @record_class.where(type: resource_type).find_by(id: resource_id)
102
+ return @local_record if defined?(@local_record)
103
+
104
+ @local_record = @record_class.where(type: resource_type).find_by(id: resource_id)
103
105
  end
104
106
 
105
107
  def event_id = @payload[:event_id]
@@ -2,7 +2,7 @@ module Keinaufwand
2
2
  module Sync
3
3
  class WebhookReceipt < ActiveRecord::Base
4
4
  self.abstract_class = true
5
- self.table_name = "keinaufwand_webhook_receipts"
5
+ self.table_name = 'keinaufwand_webhook_receipts'
6
6
  self.primary_key = :event_id
7
7
 
8
8
  def self.latest_source_updated_at(resource_type, resource_id)
@@ -6,25 +6,25 @@ module Keinaufwand
6
6
  def receive
7
7
  payload = JSON.parse(request.raw_post)
8
8
  result = Sync.configuration.webhook_processor(payload).perform
9
- Rails.logger.info("[Keinaufwand::Sync] #{payload["event_type"]}: #{result}")
9
+ Rails.logger.info("[Keinaufwand::Sync] #{payload['event_type']}: #{result}")
10
10
  head :ok
11
11
  rescue JSON::ParserError
12
12
  head :bad_request
13
- rescue WebhookProcessor::InvalidPayload => error
14
- Rails.logger.warn("[Keinaufwand::Sync] #{error.message}")
13
+ rescue WebhookProcessor::InvalidPayload => e
14
+ Rails.logger.warn("[Keinaufwand::Sync] #{e.message}")
15
15
  head :unprocessable_entity
16
- rescue StandardError => error
17
- Rails.logger.error("[Keinaufwand::Sync] #{error.class}: #{error.message}")
16
+ rescue StandardError => e
17
+ Rails.logger.error("[Keinaufwand::Sync] #{e.class}: #{e.message}")
18
18
  head :unprocessable_entity
19
19
  end
20
20
 
21
21
  private
22
22
 
23
23
  def verify_signature
24
- signature = request.headers["X-Keinaufwand-Signature"]
24
+ signature = request.headers['X-Keinaufwand-Signature']
25
25
  return head :unauthorized if signature.blank?
26
26
 
27
- expected = OpenSSL::HMAC.hexdigest("SHA256", Sync.configuration.resolved_webhook_secret, request.raw_post)
27
+ expected = OpenSSL::HMAC.hexdigest('SHA256', Sync.configuration.resolved_webhook_secret, request.raw_post)
28
28
  head :unauthorized unless ActiveSupport::SecurityUtils.secure_compare(signature, expected)
29
29
  rescue ArgumentError
30
30
  head :unauthorized
metadata CHANGED
@@ -1,17 +1,16 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: keinaufwand-sync
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.1
4
+ version: 0.2.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Codegestalt
8
- autorequire:
9
8
  bindir: bin
10
9
  cert_chain: []
11
- date: 2026-09-10 00:00:00.000000000 Z
10
+ date: 1980-01-02 00:00:00.000000000 Z
12
11
  dependencies:
13
12
  - !ruby/object:Gem::Dependency
14
- name: activerecord
13
+ name: actionpack
15
14
  requirement: !ruby/object:Gem::Requirement
16
15
  requirements:
17
16
  - - ">="
@@ -25,7 +24,7 @@ dependencies:
25
24
  - !ruby/object:Gem::Version
26
25
  version: '7.2'
27
26
  - !ruby/object:Gem::Dependency
28
- name: actionpack
27
+ name: activerecord
29
28
  requirement: !ruby/object:Gem::Requirement
30
29
  requirements:
31
30
  - - ">="
@@ -39,35 +38,33 @@ dependencies:
39
38
  - !ruby/object:Gem::Version
40
39
  version: '7.2'
41
40
  - !ruby/object:Gem::Dependency
42
- name: railties
41
+ name: keinaufwand
43
42
  requirement: !ruby/object:Gem::Requirement
44
43
  requirements:
45
44
  - - ">="
46
45
  - !ruby/object:Gem::Version
47
- version: '7.2'
46
+ version: 0.3.0
48
47
  type: :runtime
49
48
  prerelease: false
50
49
  version_requirements: !ruby/object:Gem::Requirement
51
50
  requirements:
52
51
  - - ">="
53
52
  - !ruby/object:Gem::Version
54
- version: '7.2'
53
+ version: 0.3.0
55
54
  - !ruby/object:Gem::Dependency
56
- name: keinaufwand
55
+ name: railties
57
56
  requirement: !ruby/object:Gem::Requirement
58
57
  requirements:
59
58
  - - ">="
60
59
  - !ruby/object:Gem::Version
61
- version: 0.1.0
60
+ version: '7.2'
62
61
  type: :runtime
63
62
  prerelease: false
64
63
  version_requirements: !ruby/object:Gem::Requirement
65
64
  requirements:
66
65
  - - ">="
67
66
  - !ruby/object:Gem::Version
68
- version: 0.1.0
69
- description:
70
- email:
67
+ version: '7.2'
71
68
  executables: []
72
69
  extensions: []
73
70
  extra_rdoc_files: []
@@ -102,7 +99,7 @@ homepage: https://keinaufwand.com
102
99
  licenses: []
103
100
  metadata:
104
101
  allowed_push_host: https://rubygems.org
105
- post_install_message:
102
+ rubygems_mfa_required: 'true'
106
103
  rdoc_options: []
107
104
  require_paths:
108
105
  - lib
@@ -117,8 +114,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
117
114
  - !ruby/object:Gem::Version
118
115
  version: '0'
119
116
  requirements: []
120
- rubygems_version: 3.0.3.1
121
- signing_key:
117
+ rubygems_version: 4.0.20
122
118
  specification_version: 4
123
119
  summary: Sync storage for the Keinaufwand API
124
120
  test_files: []