zammad_api 1.3.1 → 2.0.0.alpha1
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 +4 -4
- data/.yardopts +11 -0
- data/CHANGELOG.md +235 -0
- data/LICENSE.AGPL.txt +661 -0
- data/LICENSE.MIT.txt +7 -0
- data/LICENSE.md +6 -0
- data/README.md +794 -0
- data/UPGRADING.md +158 -0
- data/lib/zammad_api/attribute_access.rb +121 -0
- data/lib/zammad_api/client.rb +243 -43
- data/lib/zammad_api/collection.rb +233 -0
- data/lib/zammad_api/config.rb +239 -0
- data/lib/zammad_api/deep_copy.rb +43 -0
- data/lib/zammad_api/errors.rb +124 -0
- data/lib/zammad_api/resource_proxy.rb +195 -0
- data/lib/zammad_api/resources/base.rb +196 -99
- data/lib/zammad_api/resources/group.rb +12 -2
- data/lib/zammad_api/resources/organization.rb +12 -2
- data/lib/zammad_api/resources/ticket.rb +43 -19
- data/lib/zammad_api/resources/ticket_article.rb +14 -7
- data/lib/zammad_api/resources/ticket_article_attachment.rb +29 -14
- data/lib/zammad_api/resources/ticket_priority.rb +10 -2
- data/lib/zammad_api/resources/ticket_state.rb +9 -2
- data/lib/zammad_api/resources/user.rb +16 -2
- data/lib/zammad_api/resources.rb +13 -13
- data/lib/zammad_api/response.rb +52 -0
- data/lib/zammad_api/transport.rb +212 -40
- data/lib/zammad_api/version.rb +4 -1
- data/lib/zammad_api.rb +16 -2
- data/sig/zammad_api/attribute_access.rbs +31 -0
- data/sig/zammad_api/client.rbs +42 -0
- data/sig/zammad_api/collection.rbs +46 -0
- data/sig/zammad_api/config.rbs +69 -0
- data/sig/zammad_api/deep_copy.rbs +7 -0
- data/sig/zammad_api/errors.rbs +61 -0
- data/sig/zammad_api/resource_proxy.rbs +41 -0
- data/sig/zammad_api/resources/base.rbs +66 -0
- data/sig/zammad_api/resources/resources.rbs +201 -0
- data/sig/zammad_api/response.rbs +16 -0
- data/sig/zammad_api/transport.rbs +47 -0
- data/sig/zammad_api.rbs +3 -0
- metadata +70 -15
- data/lib/zammad_api/dispatcher.rb +0 -12
- data/lib/zammad_api/json_helper.rb +0 -11
- data/lib/zammad_api/list_all.rb +0 -11
- data/lib/zammad_api/list_base.rb +0 -83
- data/lib/zammad_api/list_search.rb +0 -11
- data/lib/zammad_api/log.rb +0 -18
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module ZammadAPI
|
|
4
|
+
# A lazily fetched, automatically paginated list of records.
|
|
5
|
+
#
|
|
6
|
+
# Nothing is requested until the collection is iterated. {#order} and
|
|
7
|
+
# {#page} return new collections, so a collection can be built up in
|
|
8
|
+
# steps and shared without being disturbed.
|
|
9
|
+
#
|
|
10
|
+
# {#each} walks every page until the server runs out of records, so it is
|
|
11
|
+
# safe to iterate a collection larger than one page. {#first} reads one page
|
|
12
|
+
# sized for what it was asked for, and +lazy+, +detect+ and the rest of
|
|
13
|
+
# +Enumerable+ stop the walk as soon as they have enough.
|
|
14
|
+
#
|
|
15
|
+
# @example Iterate every ticket
|
|
16
|
+
# client.tickets.all.each { |ticket| puts ticket.title }
|
|
17
|
+
#
|
|
18
|
+
# @example Narrow to matches, then stop after the first five
|
|
19
|
+
# client.tickets.search('state.name:open').first(5)
|
|
20
|
+
#
|
|
21
|
+
# @example Sorted by the server
|
|
22
|
+
# client.groups.order(:name).each { |group| puts group.name }
|
|
23
|
+
#
|
|
24
|
+
# @example Work in batches, e.g. for an import
|
|
25
|
+
# client.tickets.all.in_batches(of: 50) { |tickets| import(tickets) }
|
|
26
|
+
#
|
|
27
|
+
# @example One explicit page
|
|
28
|
+
# client.tickets.all.page(2, per_page: 50).to_a
|
|
29
|
+
class Collection
|
|
30
|
+
include Enumerable
|
|
31
|
+
|
|
32
|
+
# Largest page size Zammad's search endpoints serve.
|
|
33
|
+
SEARCH_MAX_PER_PAGE = 200
|
|
34
|
+
|
|
35
|
+
# @api private
|
|
36
|
+
# @param per_page [Integer, nil] records fetched per request, or nil for
|
|
37
|
+
# as many as the endpoint serves
|
|
38
|
+
# @param search [Boolean] whether this is a search endpoint, which can
|
|
39
|
+
# serve a short page before the last one, can count its results and
|
|
40
|
+
# always sorts
|
|
41
|
+
def initialize(transport, resource_class, search: false, query: {}, per_page: nil, page: nil)
|
|
42
|
+
max_per_page = search ? SEARCH_MAX_PER_PAGE : resource_class.page_limit
|
|
43
|
+
|
|
44
|
+
@transport = transport
|
|
45
|
+
@resource_class = resource_class
|
|
46
|
+
@search = search
|
|
47
|
+
@path = search ? "#{resource_class.resource_path}/search" : resource_class.resource_path
|
|
48
|
+
@query = { expand: true }.merge(query)
|
|
49
|
+
@per_page = [per_page || max_per_page, max_per_page].min
|
|
50
|
+
@page = page
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
# Yields every record, fetching pages as needed.
|
|
54
|
+
#
|
|
55
|
+
# @yieldparam record [Resources::Base]
|
|
56
|
+
# @return [Enumerator] when no block is given
|
|
57
|
+
def each(&block)
|
|
58
|
+
return to_enum(:each) if !block
|
|
59
|
+
|
|
60
|
+
in_batches { |records| records.each(&block) }
|
|
61
|
+
self
|
|
62
|
+
end
|
|
63
|
+
|
|
64
|
+
# Yields every record, fetching +batch_size+ records per request.
|
|
65
|
+
#
|
|
66
|
+
# @param batch_size [Integer, nil]
|
|
67
|
+
# @yieldparam record [Resources::Base]
|
|
68
|
+
# @return [Enumerator] when no block is given
|
|
69
|
+
def find_each(batch_size: nil, &block)
|
|
70
|
+
return to_enum(:find_each, batch_size: batch_size) if !block
|
|
71
|
+
return with(per_page: batch_size).find_each(&block) if batch_size
|
|
72
|
+
|
|
73
|
+
each(&block)
|
|
74
|
+
end
|
|
75
|
+
|
|
76
|
+
# Yields one array of records per page.
|
|
77
|
+
#
|
|
78
|
+
# @param of [Integer, nil] records fetched per request
|
|
79
|
+
# @yieldparam records [Array<Resources::Base>]
|
|
80
|
+
# @return [Enumerator] when no block is given
|
|
81
|
+
def in_batches(of: nil, &block)
|
|
82
|
+
return to_enum(:in_batches, of: of) if !block
|
|
83
|
+
return with(per_page: of).in_batches(&block) if of
|
|
84
|
+
|
|
85
|
+
walk(&block)
|
|
86
|
+
self
|
|
87
|
+
end
|
|
88
|
+
|
|
89
|
+
# Returns a new collection limited to a single page.
|
|
90
|
+
#
|
|
91
|
+
# @example
|
|
92
|
+
# client.tickets.all.page(2, per_page: 50).to_a
|
|
93
|
+
#
|
|
94
|
+
# @param number [Integer] one-based page number
|
|
95
|
+
# @param per_page [Integer, nil] records on the page, at most what the
|
|
96
|
+
# endpoint serves
|
|
97
|
+
# @return [Collection]
|
|
98
|
+
def page(number, per_page: nil) = with(page: number, per_page: per_page || @per_page)
|
|
99
|
+
|
|
100
|
+
# Returns a new collection sorted by the server.
|
|
101
|
+
#
|
|
102
|
+
# Attributes named on their own sort ascending, and a keyword says which
|
|
103
|
+
# way one runs. A second +order+ sorts within the first.
|
|
104
|
+
#
|
|
105
|
+
# @example
|
|
106
|
+
# client.groups.order(:name).first(5)
|
|
107
|
+
# client.organizations.order(name: :desc)
|
|
108
|
+
#
|
|
109
|
+
# @param attributes [Array<Symbol, String>] attributes to sort by, ascending
|
|
110
|
+
# @param directions [Hash{Symbol => Symbol, String}] attributes to sort by,
|
|
111
|
+
# each with +:asc+ or +:desc+
|
|
112
|
+
# @return [Collection]
|
|
113
|
+
# @raise [ArgumentError] for an endpoint that does not sort
|
|
114
|
+
def order(*attributes, **directions)
|
|
115
|
+
raise ArgumentError, "#{@path} is always served in the same order and ignores sort_by" if !@search && !@resource_class.sortable?
|
|
116
|
+
|
|
117
|
+
requested = attributes.to_h { [it.to_s, 'asc'] }.merge(directions.to_h { |name, direction| [name.to_s, direction.to_s] })
|
|
118
|
+
columns = sorted_by.merge(requested)
|
|
119
|
+
with(query: @query.merge(sort_by: columns.keys.join(','), order_by: columns.values.join(',')))
|
|
120
|
+
end
|
|
121
|
+
|
|
122
|
+
# Reads one or more attributes from every record.
|
|
123
|
+
#
|
|
124
|
+
# @example
|
|
125
|
+
# client.users.all.pluck(:email) # => ["a@example.com", ...]
|
|
126
|
+
# client.tickets.all.pluck(:id, :title) # => [[1, "Help"], ...]
|
|
127
|
+
#
|
|
128
|
+
# @param keys [Array<Symbol, String>] attribute names
|
|
129
|
+
# @return [Array]
|
|
130
|
+
def pluck(*keys)
|
|
131
|
+
return map { it[keys.first] } if keys.one?
|
|
132
|
+
|
|
133
|
+
map { |record| keys.map { record[it] } }
|
|
134
|
+
end
|
|
135
|
+
|
|
136
|
+
# The first record, or the first +count+ of them, read with a request sized
|
|
137
|
+
# for what was asked rather than a whole page.
|
|
138
|
+
#
|
|
139
|
+
# @param count [Integer, nil]
|
|
140
|
+
# @return [Resources::Base, Array<Resources::Base>, nil]
|
|
141
|
+
def first(count = nil)
|
|
142
|
+
source = @page ? self : with(per_page: count || 1)
|
|
143
|
+
|
|
144
|
+
count.nil? ? source.each.first : source.each.first(count)
|
|
145
|
+
end
|
|
146
|
+
|
|
147
|
+
# +Enumerable#find+, which takes a block. Look a record up by id on the
|
|
148
|
+
# resource instead: +client.tickets.find(1)+.
|
|
149
|
+
#
|
|
150
|
+
# @yieldparam record [Resources::Base]
|
|
151
|
+
# @return [Resources::Base, nil]
|
|
152
|
+
# @raise [ArgumentError] when given an id where a block belongs
|
|
153
|
+
def find(*args, &block)
|
|
154
|
+
raise ArgumentError, "find on a collection takes a block; look a record up by id with client.<resource>.find(#{args.first.inspect})" if block.nil? && !args.empty?
|
|
155
|
+
|
|
156
|
+
super
|
|
157
|
+
end
|
|
158
|
+
|
|
159
|
+
# Number of records in this collection: one request on a search, which
|
|
160
|
+
# Zammad can count without serving the records, and a walk otherwise.
|
|
161
|
+
#
|
|
162
|
+
# There is no +size+ or +length+: +each_slice+ and +each_cons+ ask for
|
|
163
|
+
# the size before they start, and that would read every record twice.
|
|
164
|
+
#
|
|
165
|
+
# @return [Integer]
|
|
166
|
+
def count(*args, &block)
|
|
167
|
+
return super if !args.empty? || block || @page || !@search
|
|
168
|
+
|
|
169
|
+
total_count || super
|
|
170
|
+
end
|
|
171
|
+
|
|
172
|
+
# @return [Boolean] whether the collection holds no records, read with
|
|
173
|
+
# one request for one record
|
|
174
|
+
def empty? = first.nil?
|
|
175
|
+
|
|
176
|
+
def inspect
|
|
177
|
+
"#<#{self.class.name} #{@resource_class.name} path=#{@path.inspect} per_page=#{@per_page}#{" page=#{@page}" if @page}>"
|
|
178
|
+
end
|
|
179
|
+
|
|
180
|
+
private
|
|
181
|
+
|
|
182
|
+
# Fetches page after page until one comes back empty. An index also stops
|
|
183
|
+
# at a short page; a search can serve one before the last.
|
|
184
|
+
#
|
|
185
|
+
# Not `loop`, which would end the walk quietly on a StopIteration raised
|
|
186
|
+
# by the caller's block; and the page is judged before the block gets it,
|
|
187
|
+
# since the block may change the Array.
|
|
188
|
+
def walk
|
|
189
|
+
number = @page || 1
|
|
190
|
+
previous = nil
|
|
191
|
+
last = false
|
|
192
|
+
|
|
193
|
+
until last
|
|
194
|
+
records = fetch(number)
|
|
195
|
+
break if records.empty?
|
|
196
|
+
|
|
197
|
+
ids = records.map(&:id)
|
|
198
|
+
raise PaginationError, repeated_page_message(number) if ids == previous
|
|
199
|
+
|
|
200
|
+
last = !@page.nil? || (!@search && records.size < @per_page)
|
|
201
|
+
yield records
|
|
202
|
+
|
|
203
|
+
previous = ids
|
|
204
|
+
number += 1
|
|
205
|
+
end
|
|
206
|
+
end
|
|
207
|
+
|
|
208
|
+
def fetch(number)
|
|
209
|
+
response = @transport.get(@path, query: @query.merge(page: number, per_page: @per_page))
|
|
210
|
+
|
|
211
|
+
response.decoded(:array).map { @resource_class.from_response(@transport, it) }
|
|
212
|
+
end
|
|
213
|
+
|
|
214
|
+
def repeated_page_message(number)
|
|
215
|
+
"#{@path}: page #{number} repeated page #{number - 1}, so the endpoint is ignoring the page parameter. " \
|
|
216
|
+
'If it serves every record in one response, read it with client.get instead.'
|
|
217
|
+
end
|
|
218
|
+
|
|
219
|
+
def total_count
|
|
220
|
+
response = @transport.get(@path, query: @query.merge(only_total_count: true))
|
|
221
|
+
total = response.body.is_a?(Hash) ? response.body[:total_count] : nil
|
|
222
|
+
total if total.is_a?(Integer)
|
|
223
|
+
end
|
|
224
|
+
|
|
225
|
+
def sorted_by
|
|
226
|
+
@query.fetch(:sort_by, '').to_s.split(',').zip(@query.fetch(:order_by, '').to_s.split(',')).to_h
|
|
227
|
+
end
|
|
228
|
+
|
|
229
|
+
def with(page: @page, per_page: @per_page, query: @query)
|
|
230
|
+
self.class.new(@transport, @resource_class, search: @search, query: query, per_page: per_page, page: page)
|
|
231
|
+
end
|
|
232
|
+
end
|
|
233
|
+
end
|
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require 'logger'
|
|
4
|
+
require 'uri'
|
|
5
|
+
|
|
6
|
+
module ZammadAPI
|
|
7
|
+
# Immutable, validated client configuration.
|
|
8
|
+
#
|
|
9
|
+
# Credentials are never included in {#inspect} output, so configuration
|
|
10
|
+
# objects are safe to log or attach to exception reports.
|
|
11
|
+
#
|
|
12
|
+
# @example
|
|
13
|
+
# ZammadAPI::Config.new(url: 'https://zammad.example.com/', http_token: 'secret')
|
|
14
|
+
#
|
|
15
|
+
# @!attribute [r] url
|
|
16
|
+
# @return [String] base URL, always with a trailing slash
|
|
17
|
+
# @!attribute [r] user
|
|
18
|
+
# @return [String, nil] login for basic authentication
|
|
19
|
+
# @!attribute [r] password
|
|
20
|
+
# @return [String, nil] password for basic authentication
|
|
21
|
+
# @!attribute [r] http_token
|
|
22
|
+
# @return [String, nil] Zammad access token
|
|
23
|
+
# @!attribute [r] oauth2_token
|
|
24
|
+
# @return [String, nil] OAuth2 bearer token
|
|
25
|
+
# @!attribute [r] user_agent
|
|
26
|
+
# @return [String] value of the +User-Agent+ request header
|
|
27
|
+
# @!attribute [r] timeout
|
|
28
|
+
# @return [Numeric] seconds to wait for a response
|
|
29
|
+
# @!attribute [r] open_timeout
|
|
30
|
+
# @return [Numeric] seconds to wait for the connection
|
|
31
|
+
# @!attribute [r] retries
|
|
32
|
+
# @return [Integer] retry attempts for a request that only reads
|
|
33
|
+
# @!attribute [r] retry_interval
|
|
34
|
+
# @return [Numeric] seconds before the first retry, doubling after that
|
|
35
|
+
# up to {#timeout}, with up to half of it added as jitter
|
|
36
|
+
# @!attribute [r] ssl_verify
|
|
37
|
+
# @return [Boolean] whether TLS certificates are verified
|
|
38
|
+
# @!attribute [r] proxy
|
|
39
|
+
# @return [String, nil] proxy URL
|
|
40
|
+
# @!attribute [r] adapter
|
|
41
|
+
# @return [Symbol, nil] name of the Faraday adapter, +nil+ for Faraday's default
|
|
42
|
+
# @!attribute [r] middleware
|
|
43
|
+
# @return [Proc, nil] called with the Faraday connection while it is
|
|
44
|
+
# being built, after this gem's own middleware
|
|
45
|
+
# @!attribute [r] logger
|
|
46
|
+
# @return [Logger] where debug output goes
|
|
47
|
+
Config = Data.define(
|
|
48
|
+
:url,
|
|
49
|
+
:user,
|
|
50
|
+
:password,
|
|
51
|
+
:http_token,
|
|
52
|
+
:oauth2_token,
|
|
53
|
+
:user_agent,
|
|
54
|
+
:timeout,
|
|
55
|
+
:open_timeout,
|
|
56
|
+
:retries,
|
|
57
|
+
:retry_interval,
|
|
58
|
+
:ssl_verify,
|
|
59
|
+
:proxy,
|
|
60
|
+
:adapter,
|
|
61
|
+
:middleware,
|
|
62
|
+
:logger
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
class Config
|
|
66
|
+
# Seconds to wait for a response.
|
|
67
|
+
DEFAULT_TIMEOUT = 60
|
|
68
|
+
|
|
69
|
+
# Seconds to wait for the connection.
|
|
70
|
+
DEFAULT_OPEN_TIMEOUT = 10
|
|
71
|
+
|
|
72
|
+
# Retry attempts for a request that only reads.
|
|
73
|
+
DEFAULT_RETRIES = 2
|
|
74
|
+
|
|
75
|
+
# Seconds before the first retry.
|
|
76
|
+
DEFAULT_RETRY_INTERVAL = 0.5
|
|
77
|
+
|
|
78
|
+
# Value of the +User-Agent+ header unless one is configured.
|
|
79
|
+
DEFAULT_USER_AGENT = "zammad_api-ruby/#{ZammadAPI::VERSION}".freeze
|
|
80
|
+
|
|
81
|
+
# What {#inspect} and the log show in place of a credential.
|
|
82
|
+
REDACTION = '[REDACTED]'
|
|
83
|
+
|
|
84
|
+
# The options of each way to authenticate.
|
|
85
|
+
CREDENTIAL_OPTIONS = {
|
|
86
|
+
http_token: %i[http_token],
|
|
87
|
+
oauth2_token: %i[oauth2_token],
|
|
88
|
+
basic: %i[user password]
|
|
89
|
+
}.freeze
|
|
90
|
+
|
|
91
|
+
# Lays +overrides+ over +options+, dropping the credentials they replace.
|
|
92
|
+
#
|
|
93
|
+
# A configuration authenticates one way, so an override that names one
|
|
94
|
+
# takes the place of every other. The options of its own scheme are kept,
|
|
95
|
+
# so overriding +password:+ alone still pairs it with the +user+ there.
|
|
96
|
+
#
|
|
97
|
+
# @api private
|
|
98
|
+
# @param options [Hash{Symbol => Object}] the options being overridden
|
|
99
|
+
# @param overrides [Hash{Symbol => Object}]
|
|
100
|
+
# @return [Hash{Symbol => Object}]
|
|
101
|
+
def self.merge_options(options, overrides)
|
|
102
|
+
named = CREDENTIAL_OPTIONS.select { |_, keys| keys.any? { !overrides[it].to_s.strip.empty? } }
|
|
103
|
+
replaced = named.empty? ? [] : CREDENTIAL_OPTIONS.except(*named.keys).values.flatten
|
|
104
|
+
|
|
105
|
+
options.except(*replaced).merge(overrides)
|
|
106
|
+
end
|
|
107
|
+
|
|
108
|
+
# @param url [String] base URL of the Zammad instance
|
|
109
|
+
# @param user [String, nil] login for basic authentication
|
|
110
|
+
# @param password [String, nil] password for basic authentication
|
|
111
|
+
# @param http_token [String, nil] Zammad access token
|
|
112
|
+
# @param oauth2_token [String, nil] OAuth2 bearer token
|
|
113
|
+
# @param user_agent [String, nil] value of the +User-Agent+ header
|
|
114
|
+
# @param timeout [Numeric] seconds to wait for a response
|
|
115
|
+
# @param open_timeout [Numeric] seconds to wait for the connection
|
|
116
|
+
# @param retries [Integer] retry attempts for a request that only reads
|
|
117
|
+
# @param retry_interval [Numeric] seconds before the first retry
|
|
118
|
+
# @param ssl_verify [Boolean] whether TLS certificates are verified
|
|
119
|
+
# @param proxy [String, nil] proxy URL
|
|
120
|
+
# @param adapter [Symbol, String, nil] name of a Faraday adapter
|
|
121
|
+
# @param middleware [#call, nil] called with the Faraday connection while it is built
|
|
122
|
+
# @param logger [Logger, nil] where debug output goes; discarded by default
|
|
123
|
+
# @raise [ConfigurationError] when the options are incomplete or invalid
|
|
124
|
+
def initialize(
|
|
125
|
+
url: nil,
|
|
126
|
+
user: nil,
|
|
127
|
+
password: nil,
|
|
128
|
+
http_token: nil,
|
|
129
|
+
oauth2_token: nil,
|
|
130
|
+
user_agent: nil,
|
|
131
|
+
timeout: DEFAULT_TIMEOUT,
|
|
132
|
+
open_timeout: DEFAULT_OPEN_TIMEOUT,
|
|
133
|
+
retries: DEFAULT_RETRIES,
|
|
134
|
+
retry_interval: DEFAULT_RETRY_INTERVAL,
|
|
135
|
+
ssl_verify: true,
|
|
136
|
+
proxy: nil,
|
|
137
|
+
adapter: nil,
|
|
138
|
+
middleware: nil,
|
|
139
|
+
logger: nil
|
|
140
|
+
)
|
|
141
|
+
# RBS cannot describe the initializer that Data.define generates.
|
|
142
|
+
# steep:ignore:start
|
|
143
|
+
super(
|
|
144
|
+
url: normalize_url(url),
|
|
145
|
+
user: present(user),
|
|
146
|
+
password: present(password),
|
|
147
|
+
http_token: stripped(http_token),
|
|
148
|
+
oauth2_token: stripped(oauth2_token),
|
|
149
|
+
user_agent: stripped(user_agent) || DEFAULT_USER_AGENT,
|
|
150
|
+
timeout: timeout,
|
|
151
|
+
open_timeout: open_timeout,
|
|
152
|
+
retries: retries,
|
|
153
|
+
retry_interval: retry_interval,
|
|
154
|
+
ssl_verify: ssl_verify,
|
|
155
|
+
proxy: present(proxy),
|
|
156
|
+
adapter: present(adapter)&.to_sym,
|
|
157
|
+
middleware: middleware,
|
|
158
|
+
logger: logger || Logger.new(IO::NULL)
|
|
159
|
+
)
|
|
160
|
+
# steep:ignore:end
|
|
161
|
+
|
|
162
|
+
validate_credentials!
|
|
163
|
+
end
|
|
164
|
+
|
|
165
|
+
# @return [Symbol] +:http_token+, +:oauth2_token+ or +:basic+
|
|
166
|
+
def authentication_scheme
|
|
167
|
+
return :http_token if http_token
|
|
168
|
+
return :oauth2_token if oauth2_token
|
|
169
|
+
|
|
170
|
+
:basic
|
|
171
|
+
end
|
|
172
|
+
|
|
173
|
+
# Returns a copy with some options changed, re-validated. Naming one way
|
|
174
|
+
# to authenticate replaces the one this configuration had.
|
|
175
|
+
#
|
|
176
|
+
# @param options [Hash] any option this class accepts
|
|
177
|
+
# @return [Config]
|
|
178
|
+
# @raise [ConfigurationError] when the resulting options are invalid
|
|
179
|
+
def with(**options) = self.class.new(**self.class.merge_options(to_h, options))
|
|
180
|
+
|
|
181
|
+
# @return [String] configuration description with credentials redacted
|
|
182
|
+
def inspect
|
|
183
|
+
rendered = to_h.map { |key, value| "#{key}=#{render(key, value)}" }
|
|
184
|
+
"#<data ZammadAPI::Config #{rendered.join(', ')}>"
|
|
185
|
+
end
|
|
186
|
+
alias to_s inspect
|
|
187
|
+
|
|
188
|
+
# What +pp+, and so a console, prints: {#inspect}, rather than every member.
|
|
189
|
+
#
|
|
190
|
+
# @api private
|
|
191
|
+
# @param printer [PP]
|
|
192
|
+
# @return [void]
|
|
193
|
+
def pretty_print(printer) = printer.text(inspect)
|
|
194
|
+
|
|
195
|
+
private
|
|
196
|
+
|
|
197
|
+
def render(key, value)
|
|
198
|
+
return value.inspect if value.nil?
|
|
199
|
+
|
|
200
|
+
case key
|
|
201
|
+
when :password, :http_token, :oauth2_token then REDACTION
|
|
202
|
+
when :proxy then value.to_s.sub(%r{//[^/@]*@}, "//#{REDACTION}@").inspect
|
|
203
|
+
when :logger, :middleware then "#<#{value.class}>"
|
|
204
|
+
else value.inspect
|
|
205
|
+
end
|
|
206
|
+
end
|
|
207
|
+
|
|
208
|
+
def normalize_url(value)
|
|
209
|
+
raise ConfigurationError, 'missing url in config' if value.to_s.empty?
|
|
210
|
+
|
|
211
|
+
uri = URI.parse(value.to_s)
|
|
212
|
+
raise ConfigurationError, 'config url needs to start with http:// or https:// and name a host' if !uri.is_a?(URI::HTTP) || uri.host.to_s.empty?
|
|
213
|
+
raise ConfigurationError, 'config url carries credentials: pass user: and password:, or a token, instead' if uri.userinfo
|
|
214
|
+
|
|
215
|
+
value.end_with?('/') ? value : "#{value}/"
|
|
216
|
+
rescue URI::InvalidURIError
|
|
217
|
+
raise ConfigurationError, 'config url is not a valid URL'
|
|
218
|
+
end
|
|
219
|
+
|
|
220
|
+
def validate_credentials!
|
|
221
|
+
given = CREDENTIAL_OPTIONS.select { |_, options| options.any? { !public_send(it).nil? } }.keys
|
|
222
|
+
if given.size > 1
|
|
223
|
+
named = given.map { CREDENTIAL_OPTIONS.fetch(it).join(' and ') }.join(', ')
|
|
224
|
+
raise ConfigurationError, "config names more than one way to authenticate (#{named}): pass http_token:, or oauth2_token:, or user: and password:"
|
|
225
|
+
end
|
|
226
|
+
return if http_token || oauth2_token
|
|
227
|
+
|
|
228
|
+
raise ConfigurationError, 'missing user in config' if user.nil?
|
|
229
|
+
raise ConfigurationError, 'missing password in config' if password.nil?
|
|
230
|
+
end
|
|
231
|
+
|
|
232
|
+
def present(value) = value.nil? || value.to_s.empty? ? nil : value
|
|
233
|
+
|
|
234
|
+
def stripped(value)
|
|
235
|
+
text = value.to_s.strip
|
|
236
|
+
text.empty? ? nil : text
|
|
237
|
+
end
|
|
238
|
+
end
|
|
239
|
+
end
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module ZammadAPI
|
|
4
|
+
# Recursive copies of the plain JSON structures this gem passes around.
|
|
5
|
+
#
|
|
6
|
+
# @api private
|
|
7
|
+
module DeepCopy
|
|
8
|
+
module_function
|
|
9
|
+
|
|
10
|
+
# A frozen deep copy, so a record's attributes cannot change behind its
|
|
11
|
+
# back. Hash keys become Symbols, so that caller-supplied attributes
|
|
12
|
+
# behave the same as decoded responses. Strings are copied before they
|
|
13
|
+
# are frozen, so the caller's own values are left alone.
|
|
14
|
+
#
|
|
15
|
+
# @param value [Object]
|
|
16
|
+
# @return [Object] a frozen copy
|
|
17
|
+
def frozen_copy(value)
|
|
18
|
+
case value
|
|
19
|
+
when Hash then value.to_h { |key, nested| [symbolize(key), frozen_copy(nested)] }.freeze
|
|
20
|
+
when Array then value.map { frozen_copy(it) }.freeze
|
|
21
|
+
when String then value.dup.freeze
|
|
22
|
+
else value
|
|
23
|
+
end
|
|
24
|
+
end
|
|
25
|
+
|
|
26
|
+
# A writable deep copy of a frozen structure.
|
|
27
|
+
#
|
|
28
|
+
# @param value [Object]
|
|
29
|
+
# @return [Object]
|
|
30
|
+
def writable_copy(value)
|
|
31
|
+
case value
|
|
32
|
+
when Hash then value.to_h { |key, nested| [key, writable_copy(nested)] }
|
|
33
|
+
when Array then value.map { writable_copy(it) }
|
|
34
|
+
when String then value.dup
|
|
35
|
+
else value
|
|
36
|
+
end
|
|
37
|
+
end
|
|
38
|
+
|
|
39
|
+
# @param key [Object]
|
|
40
|
+
# @return [Object] the key as a Symbol, where it converts to one
|
|
41
|
+
def symbolize(key) = key.respond_to?(:to_sym) ? key.to_sym : key
|
|
42
|
+
end
|
|
43
|
+
end
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module ZammadAPI
|
|
4
|
+
# Base class for every error raised by this gem.
|
|
5
|
+
#
|
|
6
|
+
# Rescuing +ZammadAPI::Error+ catches all of them.
|
|
7
|
+
class Error < StandardError; end
|
|
8
|
+
|
|
9
|
+
# Raised when {Config} cannot be built from the supplied options.
|
|
10
|
+
class ConfigurationError < Error; end
|
|
11
|
+
|
|
12
|
+
# Raised when a resource name is requested that this client does not know
|
|
13
|
+
# about, e.g. +client.unicorn+.
|
|
14
|
+
class UnknownResourceError < Error; end
|
|
15
|
+
|
|
16
|
+
# Base class for failures that prevented a request from completing.
|
|
17
|
+
class TransportError < Error; end
|
|
18
|
+
|
|
19
|
+
# Raised when the connection to the Zammad instance could not be
|
|
20
|
+
# established: DNS, a refused connection, a TLS failure, or no connection
|
|
21
|
+
# within {Config#open_timeout}.
|
|
22
|
+
class ConnectionError < TransportError; end
|
|
23
|
+
|
|
24
|
+
# Raised when a response took longer than {Config#timeout}.
|
|
25
|
+
class TimeoutError < TransportError; end
|
|
26
|
+
|
|
27
|
+
# Raised when a response did not have the shape the caller expected.
|
|
28
|
+
class ParseError < Error; end
|
|
29
|
+
|
|
30
|
+
# Raised when an endpoint answers a page request with the same records as
|
|
31
|
+
# the page before it. It is ignoring +page+ then, and a walk would never end.
|
|
32
|
+
class PaginationError < Error; end
|
|
33
|
+
|
|
34
|
+
# Base class for errors carrying an HTTP response.
|
|
35
|
+
#
|
|
36
|
+
# Use {.build} rather than +new+ to get the most specific subclass for a
|
|
37
|
+
# given status code.
|
|
38
|
+
class ResponseError < Error
|
|
39
|
+
# @return [Response, nil] the decoded HTTP response
|
|
40
|
+
attr_reader :response
|
|
41
|
+
|
|
42
|
+
# Returns the most specific error class for +response+ and instantiates it.
|
|
43
|
+
#
|
|
44
|
+
# @param response [Response]
|
|
45
|
+
# @param request [String] the request that was answered, such as
|
|
46
|
+
# +"GET api/v1/tickets/1"+
|
|
47
|
+
# @return [ResponseError]
|
|
48
|
+
def self.build(response, request)
|
|
49
|
+
error_class = STATUS_ERRORS.fetch(response.status) { response.status >= 500 ? ServerError : ClientError }
|
|
50
|
+
|
|
51
|
+
error_class.new("#{request} failed", response: response)
|
|
52
|
+
end
|
|
53
|
+
|
|
54
|
+
# @param message [String] what failed. What the response says about it,
|
|
55
|
+
# Zammad's own message or the status, is added to it.
|
|
56
|
+
# @param response [Response, nil]
|
|
57
|
+
def initialize(message, response: nil)
|
|
58
|
+
@response = response
|
|
59
|
+
super(response ? "#{message}: #{server_message || "HTTP #{status}"}" : message)
|
|
60
|
+
end
|
|
61
|
+
|
|
62
|
+
# The status of the response, or, for an error raised without one such as
|
|
63
|
+
# {ResourceProxy#find_by!} finding nothing, the status its class stands for.
|
|
64
|
+
#
|
|
65
|
+
# @return [Integer, nil] HTTP status code
|
|
66
|
+
def status
|
|
67
|
+
response&.status || STATUS_ERRORS.key(self.class)
|
|
68
|
+
end
|
|
69
|
+
|
|
70
|
+
# @return [Hash, String, nil] parsed JSON body, or the raw body for
|
|
71
|
+
# non-JSON responses
|
|
72
|
+
def body
|
|
73
|
+
response&.body
|
|
74
|
+
end
|
|
75
|
+
|
|
76
|
+
# @return [Hash] response headers, empty when there is no response
|
|
77
|
+
def headers
|
|
78
|
+
response&.headers || {}
|
|
79
|
+
end
|
|
80
|
+
|
|
81
|
+
# @return [String, nil] the error message reported by Zammad, if any
|
|
82
|
+
def server_message
|
|
83
|
+
return nil if !body.is_a?(Hash)
|
|
84
|
+
|
|
85
|
+
value = body[:error_human] || body[:error]
|
|
86
|
+
value.to_s.empty? ? nil : value.to_s
|
|
87
|
+
end
|
|
88
|
+
end
|
|
89
|
+
|
|
90
|
+
# Any 4xx response that has no more specific subclass.
|
|
91
|
+
class ClientError < ResponseError; end
|
|
92
|
+
|
|
93
|
+
# Any 5xx response.
|
|
94
|
+
class ServerError < ResponseError; end
|
|
95
|
+
|
|
96
|
+
# 401 - credentials missing, wrong, or expired.
|
|
97
|
+
class AuthenticationError < ClientError; end
|
|
98
|
+
|
|
99
|
+
# 403 - authenticated, but not permitted to perform the operation.
|
|
100
|
+
class AuthorizationError < ClientError; end
|
|
101
|
+
|
|
102
|
+
# 404 - the requested record does not exist.
|
|
103
|
+
class NotFoundError < ClientError; end
|
|
104
|
+
|
|
105
|
+
# 422 - Zammad rejected the submitted attributes.
|
|
106
|
+
class ValidationError < ClientError; end
|
|
107
|
+
|
|
108
|
+
# 429 - too many requests.
|
|
109
|
+
class RateLimitError < ClientError
|
|
110
|
+
# @return [Integer, nil] value of the +Retry-After+ response header, in seconds
|
|
111
|
+
def retry_after = Integer(headers['retry-after'].to_s, 10, exception: false)
|
|
112
|
+
end
|
|
113
|
+
|
|
114
|
+
class ResponseError
|
|
115
|
+
STATUS_ERRORS = {
|
|
116
|
+
401 => AuthenticationError,
|
|
117
|
+
403 => AuthorizationError,
|
|
118
|
+
404 => NotFoundError,
|
|
119
|
+
422 => ValidationError,
|
|
120
|
+
429 => RateLimitError
|
|
121
|
+
}.freeze
|
|
122
|
+
private_constant :STATUS_ERRORS
|
|
123
|
+
end
|
|
124
|
+
end
|