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.
Files changed (48) hide show
  1. checksums.yaml +4 -4
  2. data/.yardopts +11 -0
  3. data/CHANGELOG.md +235 -0
  4. data/LICENSE.AGPL.txt +661 -0
  5. data/LICENSE.MIT.txt +7 -0
  6. data/LICENSE.md +6 -0
  7. data/README.md +794 -0
  8. data/UPGRADING.md +158 -0
  9. data/lib/zammad_api/attribute_access.rb +121 -0
  10. data/lib/zammad_api/client.rb +243 -43
  11. data/lib/zammad_api/collection.rb +233 -0
  12. data/lib/zammad_api/config.rb +239 -0
  13. data/lib/zammad_api/deep_copy.rb +43 -0
  14. data/lib/zammad_api/errors.rb +124 -0
  15. data/lib/zammad_api/resource_proxy.rb +195 -0
  16. data/lib/zammad_api/resources/base.rb +196 -99
  17. data/lib/zammad_api/resources/group.rb +12 -2
  18. data/lib/zammad_api/resources/organization.rb +12 -2
  19. data/lib/zammad_api/resources/ticket.rb +43 -19
  20. data/lib/zammad_api/resources/ticket_article.rb +14 -7
  21. data/lib/zammad_api/resources/ticket_article_attachment.rb +29 -14
  22. data/lib/zammad_api/resources/ticket_priority.rb +10 -2
  23. data/lib/zammad_api/resources/ticket_state.rb +9 -2
  24. data/lib/zammad_api/resources/user.rb +16 -2
  25. data/lib/zammad_api/resources.rb +13 -13
  26. data/lib/zammad_api/response.rb +52 -0
  27. data/lib/zammad_api/transport.rb +212 -40
  28. data/lib/zammad_api/version.rb +4 -1
  29. data/lib/zammad_api.rb +16 -2
  30. data/sig/zammad_api/attribute_access.rbs +31 -0
  31. data/sig/zammad_api/client.rbs +42 -0
  32. data/sig/zammad_api/collection.rbs +46 -0
  33. data/sig/zammad_api/config.rbs +69 -0
  34. data/sig/zammad_api/deep_copy.rbs +7 -0
  35. data/sig/zammad_api/errors.rbs +61 -0
  36. data/sig/zammad_api/resource_proxy.rbs +41 -0
  37. data/sig/zammad_api/resources/base.rbs +66 -0
  38. data/sig/zammad_api/resources/resources.rbs +201 -0
  39. data/sig/zammad_api/response.rbs +16 -0
  40. data/sig/zammad_api/transport.rbs +47 -0
  41. data/sig/zammad_api.rbs +3 -0
  42. metadata +70 -15
  43. data/lib/zammad_api/dispatcher.rb +0 -12
  44. data/lib/zammad_api/json_helper.rb +0 -11
  45. data/lib/zammad_api/list_all.rb +0 -11
  46. data/lib/zammad_api/list_base.rb +0 -83
  47. data/lib/zammad_api/list_search.rb +0 -11
  48. data/lib/zammad_api/log.rb +0 -18
data/README.md ADDED
@@ -0,0 +1,794 @@
1
+ # Zammad API Client (Ruby)
2
+
3
+ [![Gem Version](https://badge.fury.io/rb/zammad_api.svg)](https://badge.fury.io/rb/zammad_api)
4
+ [![CI](https://github.com/zammad/zammad-api-client-ruby/actions/workflows/ci.yml/badge.svg)](https://github.com/zammad/zammad-api-client-ruby/actions/workflows/ci.yml)
5
+
6
+ > [!IMPORTANT]
7
+ > `2.0.0.alpha1` is the first prerelease of a breaking 2.0. Names and defaults can still
8
+ > change: [open an issue](https://github.com/zammad/zammad-api-client-ruby/issues/new) with
9
+ > anything that reads wrong, is missing, or makes upgrading hard. Rough notes are welcome.
10
+ > On 1.x? See [UPGRADING.md][upgrading], which also says how to stay on 1.x.
11
+
12
+ Ruby client for the Zammad API v1.0.
13
+
14
+ - Tickets, articles, attachments, users, organizations, groups, ticket states and
15
+ priorities as records you `find`, `create`, `update` and `destroy`.
16
+ - Collections that paginate themselves: `each`, `first`, `search`, `find_each`.
17
+ - Timeouts, and retries for `GET`, on by default, and one error class per kind of failure.
18
+ - Any other endpoint through a resource you declare or a raw request.
19
+
20
+ ## Installation
21
+
22
+ Requires Ruby 3.4 or later. It is tested against Zammad 7.0, the current stable release
23
+ and the `develop` branch: CI runs the integration specs against all three on every change
24
+ and once a week. Older Zammad releases are not part of that run.
25
+
26
+ 2.0 is a prerelease, and a prerelease has to be asked for:
27
+
28
+ ```ruby
29
+ gem 'zammad_api', '~> 2.0.0.alpha'
30
+ ```
31
+
32
+ Or:
33
+
34
+ ```sh
35
+ gem install zammad_api --pre
36
+ ```
37
+
38
+ ## Quick start
39
+
40
+ ```ruby
41
+ require 'zammad_api'
42
+
43
+ client = ZammadAPI::Client.new(
44
+ url: 'https://zammad.example.com/',
45
+ http_token: 'your-access-token'
46
+ )
47
+
48
+ client.tickets.first(5).each { |ticket| puts ticket.title }
49
+
50
+ ticket = client.tickets.create(
51
+ title: 'Cannot log in',
52
+ group: 'Users',
53
+ customer: 'nicole.braun@zammad.org',
54
+ article: {subject: 'Cannot log in', body: 'My password stopped working.', type: 'note'}
55
+ )
56
+
57
+ ticket.add_article(body: 'Reset link sent.', type: 'note')
58
+ ticket.update(state: 'closed')
59
+
60
+ client.tickets.search('state.name:open').each { |open_ticket| puts open_ticket.number }
61
+
62
+ begin
63
+ client.tickets.find(123_456)
64
+ rescue ZammadAPI::NotFoundError => e
65
+ warn e.server_message
66
+ end
67
+ ```
68
+
69
+ The sections below cover [creating a client](#creating-a-client),
70
+ [records](#working-with-records), [collections](#collections) and
71
+ [error handling](#error-handling).
72
+
73
+ ## Creating a client
74
+
75
+ ### Authentication
76
+
77
+ ```ruby
78
+ client = ZammadAPI::Client.new(
79
+ url: 'https://zammad.example.com/',
80
+ http_token: 'your-access-token'
81
+ )
82
+ ```
83
+
84
+ Or pass `oauth2_token:`, or `user:` and `password:`. Pass one kind of credentials: more
85
+ than one raises `ZammadAPI::ConfigurationError`.
86
+
87
+ ### From the environment
88
+
89
+ `from_env` reads `ZAMMAD_URL` and one of `ZAMMAD_TOKEN`, `ZAMMAD_OAUTH2_TOKEN`, or
90
+ `ZAMMAD_USER` with `ZAMMAD_PASSWORD`. Options passed to it override the environment:
91
+
92
+ ```ruby
93
+ client = ZammadAPI::Client.from_env
94
+ client = ZammadAPI::Client.from_env(timeout: 300)
95
+ ```
96
+
97
+ ### Options
98
+
99
+ | Option | Default | Description |
100
+ | ---------------- | ------------------ | ------------------------------------------------------------------ |
101
+ | `url` | *required* | Base URL. A sub-path such as `https://example.com/zammad/` works; credentials in it are refused. |
102
+ | `http_token` | `nil` | Zammad access token. |
103
+ | `oauth2_token` | `nil` | OAuth2 bearer token. |
104
+ | `user` | `nil` | Login for basic authentication. |
105
+ | `password` | `nil` | Password for basic authentication. |
106
+ | `timeout` | `60` | Seconds to wait for a response. |
107
+ | `open_timeout` | `10` | Seconds to wait for the connection. |
108
+ | `retries` | `2` | Retry attempts for a `GET` that failed transiently. `0` disables retrying. |
109
+ | `retry_interval` | `0.5` | Seconds before the first retry; doubles on each attempt. |
110
+ | `ssl_verify` | `true` | Set to `false` only against a server with a self-signed certificate. |
111
+ | `proxy` | `nil` | Proxy URL. |
112
+ | `user_agent` | `zammad_api-ruby/<version>` | Value of the `User-Agent` header. |
113
+ | `logger` | discards output | Any `Logger`; see [Logging](#logging). |
114
+ | `adapter` | Faraday's default | Name of a Faraday adapter; see [Adapter and middleware](#adapter-and-middleware). |
115
+ | `middleware` | `nil` | Callable that is handed the Faraday connection while it is built. |
116
+
117
+ Credentials are never logged, and `client.config` redacts them when printed.
118
+
119
+ ### Changing options
120
+
121
+ A client is immutable. `with` returns a new one with some options changed, carrying over
122
+ any `on_behalf_of` scope:
123
+
124
+ ```ruby
125
+ bulk = client.with(timeout: 300, retries: 5)
126
+ bulk.tickets.each { |ticket| archive(ticket) }
127
+ ```
128
+
129
+ Naming credentials replaces the ones the client has, whichever kind they were. Because
130
+ clients are immutable, one client and anything derived from it can be shared between
131
+ threads.
132
+
133
+ ### Checking the connection
134
+
135
+ ```ruby
136
+ client.me.email # => "agent@example.com", the account the credentials belong to
137
+ client.version # => "6.4.0", the Zammad instance's version, for an administrator
138
+ ```
139
+
140
+ `client.me` works for any account, so use it to check that the client can reach Zammad and
141
+ authenticate. Zammad serves `client.version` to administrators only: with an agent's or a
142
+ customer's credentials it raises `ZammadAPI::AuthorizationError`. `ZammadAPI::VERSION` is
143
+ the version of this gem.
144
+
145
+ ## Resources
146
+
147
+ `groups`, `organizations`, `tickets`, `ticket_articles`, `ticket_priorities`,
148
+ `ticket_states`, `users`
149
+
150
+ `client.resource_names` returns the current list. Anything else is reachable by declaring
151
+ a resource or with raw requests; see
152
+ [Endpoints this gem does not model](#endpoints-this-gem-does-not-model).
153
+
154
+ ## Working with records
155
+
156
+ ### Create
157
+
158
+ ```ruby
159
+ user = client.users.new(firstname: 'Nicole', lastname: 'Braun', email: 'nicole.braun@zammad.org')
160
+ user.save
161
+
162
+ user.id # => 42
163
+ user.email # => "nicole.braun@zammad.org"
164
+ ```
165
+
166
+ Or in one call:
167
+
168
+ ```ruby
169
+ user = client.users.create(firstname: 'Nicole', lastname: 'Braun', email: 'nicole.braun@zammad.org')
170
+ ```
171
+
172
+ Attributes are a Hash, or anything that converts to one with `to_hash`. In a Rails
173
+ controller that is the permitted parameters:
174
+
175
+ ```ruby
176
+ client.users.create(params.require(:user).permit(:login, :email, :password))
177
+ ```
178
+
179
+ ### Fetch
180
+
181
+ ```ruby
182
+ user = client.users.find(42) # raises NotFoundError if there is none
183
+
184
+ client.users.find_by(email: 'someone@example.com') # => the record, or nil
185
+ client.users.find_by!(email: 'nobody@example.com') # raises NotFoundError
186
+ client.users.exists?(42) # => true
187
+ ```
188
+
189
+ `find_by` returns the first record carrying all of the given values, or `nil`. It searches
190
+ where the resource has a search endpoint and one of the values is a String; otherwise it
191
+ reads the index page by page, which can take many requests on a large instance. What a
192
+ search matches is up to Zammad's search index, so where a miss must be certain, read the
193
+ index yourself: `client.tickets.detect { it[:state] == 'open' }`.
194
+
195
+ ### Reading attributes
196
+
197
+ ```ruby
198
+ user.email # => "nicole.braun@zammad.org"
199
+ user[:email] # the same, and nil when the attribute is absent
200
+ user.fetch(:email) # raises KeyError when the attribute is absent
201
+ user.key?(:email) # => true
202
+ user.to_h # every attribute, as a Hash you may modify
203
+ ```
204
+
205
+ A reader for an attribute the record does not carry raises `NoMethodError`, so a typo does
206
+ not read as `nil`. Use `record[:name]` or `fetch(:name, nil)` where an attribute may be
207
+ absent: custom attributes, or records the authenticated user may only partly see.
208
+
209
+ `attributes` and `changes` are frozen. Assign through a writer (`user.email = '...'`) to
210
+ stage a change.
211
+
212
+ ### Update
213
+
214
+ ```ruby
215
+ user = client.users.find(42)
216
+ user.firstname = 'Nicola'
217
+
218
+ user.changed? # => true
219
+ user.changes # => {firstname: ["Nicole", "Nicola"]}
220
+
221
+ user.save # sends only the changed attributes
222
+ ```
223
+
224
+ `save` with no changes sends no request and returns `true`. Assigning the value an
225
+ attribute already has is not a change.
226
+
227
+ Or in one call:
228
+
229
+ ```ruby
230
+ user.update(firstname: 'Nicola', note: 'Renamed') # assigns, then saves
231
+ user.assign_attributes(firstname: 'Nicola') # assigns without saving
232
+ ```
233
+
234
+ ### Saving and validation failures
235
+
236
+ `save` returns whether the record was stored, and leaves a rejection in `error`:
237
+
238
+ ```ruby
239
+ organization = client.organizations.new(name: '')
240
+
241
+ if organization.save
242
+ puts organization.id
243
+ else
244
+ warn organization.error.server_message # => "Name can't be blank"
245
+ end
246
+ ```
247
+
248
+ Only a validation failure (HTTP 422) is reported this way. Every other failure raises.
249
+
250
+ `save!` and `update!` raise on every failure, including validation:
251
+
252
+ ```ruby
253
+ organization.save! # raises ZammadAPI::ValidationError
254
+ organization.update!(name: '') # the same, in one call
255
+ ```
256
+
257
+ `create` raises on a validation failure, like `save!`. Use `new` and `save` to branch
258
+ instead.
259
+
260
+ ### Reload and destroy
261
+
262
+ ```ruby
263
+ user.reload # re-reads from Zammad, discarding unsaved changes
264
+ user.destroy # => true
265
+
266
+ user.destroyed? # => true
267
+ user.persisted? # => false
268
+
269
+ client.users.destroy(42) # delete by id, without fetching first
270
+ ```
271
+
272
+ ### Associations
273
+
274
+ Zammad expands an association into a name beside the id, so those reads cost nothing:
275
+
276
+ ```ruby
277
+ ticket = client.tickets.find(1)
278
+
279
+ ticket.customer # => "customer@example.com"
280
+ ticket.state # => "open"
281
+ ticket.group # => "Users"
282
+ ticket.customer_id # => 7
283
+ ```
284
+
285
+ The whole record behind one of those is a `find` by its id, which costs a request:
286
+
287
+ ```ruby
288
+ client.users.find(ticket.customer_id).firstname # => "Nicole"
289
+ ```
290
+
291
+ A foreign key that may be empty, such as a user's `organization_id`, is `nil` then, and
292
+ `find` needs an id:
293
+
294
+ ```ruby
295
+ user.organization_id && client.organizations.find(user.organization_id)
296
+ ```
297
+
298
+ ### Articles and attachments
299
+
300
+ ```ruby
301
+ ticket.articles # => [TicketArticle, ...]
302
+ ticket.add_article(body: 'Reset link sent.', type: 'note') # => the created TicketArticle
303
+
304
+ ticket.articles.each do |article|
305
+ article.attachments.each do |attachment|
306
+ File.binwrite(File.basename(attachment.filename), attachment.download)
307
+ end
308
+ end
309
+ ```
310
+
311
+ `articles` is one request, and is fetched on each call. `download` returns the file
312
+ contents as a binary String.
313
+
314
+ To send a file, give the article its `attachments`, each with its content encoded as
315
+ Base64:
316
+
317
+ ```ruby
318
+ ticket.add_article(
319
+ body: 'Invoice attached.',
320
+ type: 'note',
321
+ attachments: [{
322
+ filename: 'invoice.pdf',
323
+ data: [File.binread('invoice.pdf')].pack('m0'),
324
+ 'mime-type': 'application/pdf'
325
+ }]
326
+ )
327
+ ```
328
+
329
+ `pack('m0')` is what `Base64.strict_encode64` does, without the `base64` gem, which Ruby
330
+ no longer ships by default. The `article:` of `client.tickets.create` takes `attachments`
331
+ the same way.
332
+
333
+ ### Comparing and serializing
334
+
335
+ Two records of the same kind with the same id are equal, so `uniq`, `Set` and `include?`
336
+ work as expected:
337
+
338
+ ```ruby
339
+ client.tickets.find(1) == client.tickets.find(1) # => true
340
+ ```
341
+
342
+ `to_json` renders the attributes, and `as_json` returns them as a Hash:
343
+
344
+ ```ruby
345
+ client.groups.find(1).to_json # => "{\"id\":1,\"name\":\"Support\"}"
346
+ ```
347
+
348
+ ### Pattern matching
349
+
350
+ Records implement `deconstruct_keys`, so they work with `case/in`:
351
+
352
+ ```ruby
353
+ case client.tickets.find(1)
354
+ in {state: 'closed'}
355
+ nil
356
+ in {state: String => state, priority: '3 high'}
357
+ escalate(state)
358
+ in {group: 'Support'}
359
+ notify_support
360
+ end
361
+ ```
362
+
363
+ ## Collections
364
+
365
+ `all`, `search` and `order` return a `ZammadAPI::Collection`. It is `Enumerable`, makes no
366
+ request until you iterate, and fetches pages as needed.
367
+
368
+ ### Iterating
369
+
370
+ ```ruby
371
+ client.tickets.each { |ticket| puts ticket.title }
372
+
373
+ # One request, for five records.
374
+ client.tickets.first(5)
375
+
376
+ # Lazy chains stop fetching once they have enough.
377
+ client.tickets.lazy.select { |ticket| ticket.state == 'open' }.first(10)
378
+
379
+ # One array of records per request, e.g. for a bulk import.
380
+ client.tickets.in_batches(of: 50) { |tickets| import(tickets) }
381
+
382
+ # Record by record, 50 per request.
383
+ client.tickets.find_each(batch_size: 50) { |ticket| archive(ticket) }
384
+
385
+ # Attribute values instead of records.
386
+ client.users.pluck(:email) # => ["a@example.com", ...]
387
+ client.tickets.pluck(:id, :title) # => [[1, "Help"], ...]
388
+ ```
389
+
390
+ `client.tickets` and `client.tickets.all` are the same collection. Nothing is cached, so
391
+ iterating again fetches again.
392
+
393
+ `client.tickets.find(1)` looks up by id. To find with a block, use `detect`.
394
+
395
+ ### Searching
396
+
397
+ ```ruby
398
+ client.tickets.search('state.name:open').each { |ticket| puts ticket.title }
399
+ client.organizations.search('zammad').first(10)
400
+ ```
401
+
402
+ Zammad's index endpoints do not filter; only the search endpoints do. That is why a
403
+ collection has no `where`. `users`, `organizations`, `tickets` and `groups` can be
404
+ searched. On the others `search` raises `ZammadAPI::Error`, so use `find_by` or `select`:
405
+
406
+ ```ruby
407
+ client.ticket_states.find_by(name: 'open')
408
+ client.ticket_priorities.select { it.active }
409
+ ```
410
+
411
+ Keywords are passed on to the search endpoint as query parameters: `condition:` and `ids:`
412
+ on every search, and `role_ids:`, `group_ids:` and `permissions:` on users. Zammad ignores
413
+ a parameter it does not read.
414
+
415
+ ```ruby
416
+ client.users.search('smith', role_ids: [2])
417
+ client.tickets.search('printer', condition: {'ticket.group_id' => {operator: 'is', value: [2]}})
418
+ ```
419
+
420
+ A blank term raises `ArgumentError`. `search('*')` asks for every record.
421
+
422
+ ### Sorting
423
+
424
+ `order` sorts on the server:
425
+
426
+ ```ruby
427
+ client.groups.order(:name) # ascending
428
+ client.organizations.order(name: :desc)
429
+ client.groups.order(:active, name: :desc) # by active, then by name descending
430
+ ```
431
+
432
+ `/api/v1/tickets` and `/api/v1/users` are always served in id order, so `order` on
433
+ `client.tickets` or `client.users` raises `ArgumentError`. Sort a search instead:
434
+
435
+ ```ruby
436
+ client.tickets.search('state.name:open').order(created_at: :desc)
437
+ ```
438
+
439
+ ### Pages
440
+
441
+ ```ruby
442
+ client.tickets.page(2) # page 2 at the size the endpoint serves
443
+ client.tickets.page(2, per_page: 10) # records 11 to 20
444
+ ```
445
+
446
+ By default a request asks for the largest page the endpoint serves: 100 for tickets, 200
447
+ for a search, 1000 elsewhere. Pass a smaller size with `find_each(batch_size:)`,
448
+ `in_batches(of:)` or `page(n, per_page:)`; a larger one is capped.
449
+
450
+ Collections are immutable: `order` and `page` return a new collection.
451
+
452
+ ### Counting
453
+
454
+ `count` on a search is one request. Every other collection is read page by page, because
455
+ an index endpoint reports no total:
456
+
457
+ ```ruby
458
+ client.tickets.search('state.name:open').count # one request
459
+ client.tickets.count # one request per page
460
+ client.tickets.search('state.name:merged').empty? # one request, for one record
461
+ ```
462
+
463
+ ## Acting on behalf of another user
464
+
465
+ Zammad can perform
466
+ [actions on behalf of another user](https://docs.zammad.org/en/latest/api/intro.html#actions-on-behalf-of-other-users).
467
+ `on_behalf_of` returns a new client:
468
+
469
+ ```ruby
470
+ support = client.on_behalf_of('agent@example.com')
471
+ support.tickets.create(title: 'Help', group: 'Users', customer_id: 1)
472
+ ```
473
+
474
+ Or scoped to a block:
475
+
476
+ ```ruby
477
+ client.on_behalf_of('agent@example.com') do |scoped|
478
+ scoped.tickets.find(1)
479
+ end
480
+ ```
481
+
482
+ The identifier can be a login, an email address or a user id. A `nil` or blank identifier
483
+ raises `ArgumentError`. This sends the HTTP `From` header and requires Zammad 5.0 or later.
484
+
485
+ ## Error handling
486
+
487
+ ```ruby
488
+ begin
489
+ client.tickets.find(1)
490
+ rescue ZammadAPI::NotFoundError
491
+ nil
492
+ rescue ZammadAPI::RateLimitError => e
493
+ # The client already waited and retried, so this limit outlasted that.
494
+ reschedule(in: e.retry_after || 60)
495
+ rescue ZammadAPI::ResponseError => e
496
+ warn "#{e.status}: #{e.server_message}"
497
+ warn e.body.inspect
498
+ end
499
+ ```
500
+
501
+ `save` and `update` return `false` on a 422 instead of raising; see
502
+ [Saving and validation failures](#saving-and-validation-failures).
503
+
504
+ Every error descends from `ZammadAPI::Error`:
505
+
506
+ ```text
507
+ ZammadAPI::Error
508
+ ├── ZammadAPI::ConfigurationError invalid client options
509
+ ├── ZammadAPI::UnknownResourceError no such resource, e.g. client.resource(:unicorn)
510
+ ├── ZammadAPI::ParseError unexpected response shape
511
+ ├── ZammadAPI::PaginationError endpoint ignored the page parameter
512
+ ├── ZammadAPI::TransportError
513
+ │ ├── ZammadAPI::ConnectionError unreachable host, TLS failure or open_timeout
514
+ │ └── ZammadAPI::TimeoutError exceeded timeout
515
+ └── ZammadAPI::ResponseError carries the HTTP response
516
+ ├── ZammadAPI::ClientError 4xx
517
+ │ ├── ZammadAPI::AuthenticationError 401
518
+ │ ├── ZammadAPI::AuthorizationError 403
519
+ │ ├── ZammadAPI::NotFoundError 404
520
+ │ ├── ZammadAPI::ValidationError 422
521
+ │ └── ZammadAPI::RateLimitError 429
522
+ └── ZammadAPI::ServerError 5xx
523
+ ```
524
+
525
+ `ResponseError` exposes `response` (a `ZammadAPI::Response`) and, as shortcuts, `status`,
526
+ `body`, `headers` and `server_message`. Its message names the request that failed:
527
+ `GET api/v1/tickets/1 failed: Couldn't find Ticket with 'id'="1"`.
528
+
529
+ A `TransportError` is a request with no answer, which is not the same as one Zammad never
530
+ saw: a write that timed out may have been applied.
531
+
532
+ ### Timeouts and retries
533
+
534
+ A `GET` is retried on connection failures, timeouts and the statuses 429, 500, 502, 503
535
+ and 504, with exponential backoff. A write is never retried. Both are options:
536
+
537
+ ```ruby
538
+ client = ZammadAPI::Client.new(
539
+ url: 'https://zammad.example.com/',
540
+ http_token: 'token',
541
+ timeout: 10,
542
+ retries: 5
543
+ )
544
+ ```
545
+
546
+ A `Retry-After` header is honoured up to `timeout` seconds. A longer one is not waited
547
+ out: the request fails at once, and `RateLimitError#retry_after` carries the figure.
548
+
549
+ A write that fails raises, because repeating it could create a second record or send an
550
+ e-mail twice. The calling code decides whether to send it again:
551
+
552
+ ```ruby
553
+ begin
554
+ ticket.update!(state: 'closed')
555
+ rescue ZammadAPI::TransportError, ZammadAPI::ServerError
556
+ ticket.reload # did it arrive?
557
+ retry if ticket.state != 'closed'
558
+ end
559
+ ```
560
+
561
+ ## Logging
562
+
563
+ ```ruby
564
+ client = ZammadAPI::Client.new(
565
+ url: 'https://zammad.example.com/',
566
+ http_token: 'token',
567
+ logger: Logger.new($stdout)
568
+ )
569
+ ```
570
+
571
+ Requests, response statuses and durations are logged at `debug` level. Anything that
572
+ responds to `debug` works in place of a `Logger`. Payload keys, query parameters and
573
+ headers that look like credentials (`password`, `token`, `secret`, `cookie`, ...) are
574
+ redacted, and a path is logged without its query string.
575
+
576
+ ## Endpoints this gem does not model
577
+
578
+ ### Declaring a resource
579
+
580
+ For an endpoint that serves records like the modelled ones (an index, and a member under
581
+ its id), declare a class with a path. `client.resource` then works like `client.tickets`:
582
+
583
+ ```ruby
584
+ class Role < ZammadAPI::Resources::Base
585
+ path 'api/v1/roles'
586
+ end
587
+
588
+ roles = client.resource(Role)
589
+
590
+ roles.each { |role| puts role.name }
591
+ roles.find(2).update(note: 'Reviewed')
592
+ roles.create(name: 'Auditor')
593
+ roles.find_by(name: 'Agent')
594
+ ```
595
+
596
+ Declare where the endpoint differs from the defaults:
597
+
598
+ | Declaration | Default | Says |
599
+ | ------------------ | ---------- | ------------------------------------------------------------- |
600
+ | `path '…'` | *required* | The index endpoint, relative to the instance URL. |
601
+ | `searchable true` | `false` | Zammad routes `<path>/search`, so `search` works and `find_by` uses it. |
602
+ | `max_per_page 100` | `1000` | The largest page the index endpoint serves. |
603
+ | `sortable false` | `true` | The index endpoint is always served in the same order, so `order` refuses it. |
604
+
605
+ A subclass of a modelled resource works too, and inherits what its parent declares:
606
+ `class MyTicket < ZammadAPI::Resources::Ticket`.
607
+
608
+ For an endpoint that ignores `page` and returns everything at once, or one that is an
609
+ action, a report or a setting, use a raw request.
610
+
611
+ ### Raw requests
612
+
613
+ `get`, `post`, `put` and `delete` reach any endpoint of the Zammad API, with the same
614
+ authentication, timeouts, retries and error classes:
615
+
616
+ ```ruby
617
+ client.get('api/v1/roles').body
618
+ # => [{id: 1, name: "Admin", ...}, ...]
619
+
620
+ client.post('api/v1/tags/add', query: {object: 'Ticket', o_id: 1, item: 'urgent'})
621
+ client.put('api/v1/roles/2', body: {note: 'Updated'})
622
+ client.delete('api/v1/tags/remove', query: {object: 'Ticket', o_id: 1, item: 'urgent'})
623
+
624
+ client.get('api/v1/tickets/1', headers: {'Accept-Language' => 'de-de'})
625
+ ```
626
+
627
+ A `body:` is sent as JSON, and a String body is sent as it is. Each call returns a
628
+ `ZammadAPI::Response`:
629
+
630
+ ```ruby
631
+ response = client.get('api/v1/tickets')
632
+ response.status # => 200
633
+ response.headers['content-type']
634
+ response.body # decoded JSON, or the raw body for anything else
635
+ response.raw_body # the body as it arrived
636
+ ```
637
+
638
+ Paths are relative to the instance URL, and a leading slash is ignored. A path that opens
639
+ with a scheme, such as `https://other.example/collect`, raises `ArgumentError`, so the
640
+ client's credentials only go to the instance it was configured for.
641
+
642
+ ### Coverage
643
+
644
+ Modelled: tickets, ticket articles and their attachments, ticket states and priorities,
645
+ users, organizations and groups, the same set as 1.x.
646
+
647
+ Not modelled yet: roles; text modules; ticket tags, links, mentions, time accounting,
648
+ checklists, shared drafts, merge and history; the knowledge base; global search; CSV
649
+ imports. Declare a resource or use raw requests for those, and
650
+ [open an issue](https://github.com/zammad/zammad-api-client-ruby/issues/new) for the one
651
+ you need, so we know what to model first.
652
+
653
+ The [features roadmap][roadmap] shows what is planned for 2.0, beside 1.x and the
654
+ PHP client.
655
+
656
+ ## Adapter and middleware
657
+
658
+ The client is built on Faraday. `adapter:` picks the Faraday adapter, and `middleware:`
659
+ adds your own middleware, such as instrumentation or a cache:
660
+
661
+ ```ruby
662
+ client = ZammadAPI::Client.new(
663
+ url: 'https://zammad.example.com/',
664
+ http_token: 'token',
665
+ adapter: :net_http_persistent,
666
+ middleware: ->(connection) { connection.use(MyInstrumentation) }
667
+ )
668
+ ```
669
+
670
+ To pass arguments to an adapter, set it inside the callable:
671
+ `->(connection) { connection.adapter :net_http_persistent, pool_size: 5 }`. Do not add
672
+ `response :json` or `response :raise_error`; the client decodes JSON and maps errors
673
+ itself.
674
+
675
+ Faraday's default adapter opens a connection per request. For anything that reads many
676
+ pages, downloads attachments in a loop or runs a worker pool, add
677
+ `faraday-net_http_persistent` to your Gemfile and pass `adapter: :net_http_persistent`.
678
+
679
+ ## Type signatures
680
+
681
+ RBS signatures ship in `sig/` and are checked in CI with [Steep](https://github.com/soutaro/steep).
682
+ Add the gem to your own RBS collection to type-check calls into this client. Records are
683
+ typed, not only the client:
684
+
685
+ ```ruby
686
+ ticket = client.tickets.find(1)
687
+
688
+ ticket.title # String
689
+ ticket.organization_id # Integer?
690
+ ticket.titel # a type error: no such attribute is declared
691
+ ```
692
+
693
+ Attributes an administrator added, columns only newer Zammad versions serve, and expanded
694
+ association names that can be absent (such as `organization`) are not declared. Read those
695
+ with `ticket[:name]`, or reopen the class in your own signatures:
696
+
697
+ ```rbs
698
+ class ZammadAPI::Resources::Ticket
699
+ attr_accessor escalation_reason: String?
700
+ end
701
+ ```
702
+
703
+ A resource of your own needs an annotation:
704
+
705
+ ```ruby
706
+ roles = client.resource(Role) #: ZammadAPI::ResourceProxy[Role]
707
+ ```
708
+
709
+ ## Recipes
710
+
711
+ ### Resuming a long read
712
+
713
+ Keep the page number yourself when a job has to survive being interrupted. Save it once a
714
+ page is handled, so a rerun repeats at most one page:
715
+
716
+ ```ruby
717
+ page = File.exist?('cursor') ? Integer(File.read('cursor')) : 1
718
+
719
+ loop do
720
+ tickets = client.tickets.page(page, per_page: 50).to_a
721
+ break if tickets.empty?
722
+
723
+ import(tickets)
724
+
725
+ page += 1
726
+ File.write('cursor', page)
727
+ end
728
+ ```
729
+
730
+ A page number is a position, so this suits a list that only grows: tickets are served in
731
+ id order, and new ones arrive at the end.
732
+
733
+ `in_batches` without a block is an Enumerator, for pulling one page at a time as a
734
+ consumer is ready: `pages = client.tickets.in_batches(of: 50)`, then `pages.next`.
735
+
736
+ ### Sharing one client between threads
737
+
738
+ A client is immutable, so one instance serves every thread, and an `on_behalf_of` scope in
739
+ one thread cannot leak into another. In Rails, build it once in an initializer:
740
+
741
+ ```ruby
742
+ # config/initializers/zammad.rb
743
+ ZAMMAD = ZammadAPI::Client.new(
744
+ url: Rails.application.credentials.zammad_url,
745
+ http_token: Rails.application.credentials.zammad_token,
746
+ logger: Rails.logger
747
+ )
748
+ ```
749
+
750
+ A worker pool shares it the same way:
751
+
752
+ ```ruby
753
+ queue = Queue.new
754
+ client.tickets.first(40).each { queue << it.id }
755
+ queue.close
756
+
757
+ workers = Array.new(4) do
758
+ Thread.new do
759
+ while (id = queue.pop)
760
+ sync(client.tickets.find(id))
761
+ end
762
+ end
763
+ end
764
+
765
+ workers.each(&:join)
766
+ ```
767
+
768
+ ## Development
769
+
770
+ ```sh
771
+ bin/setup # bundle install, plus the overcommit git hooks
772
+ bundle exec rake # unit specs, RuboCop, Steep and the shipped signatures
773
+ ```
774
+
775
+ Integration specs need a disposable Zammad named by `TEST_URL`; see
776
+ [CONTRIBUTING.md][contributing].
777
+
778
+ ## Upgrading from 1.x
779
+
780
+ Most code needs one rename: `client.ticket` is `client.tickets`. Nearly everything else
781
+ that changed raises at the call site. [UPGRADING.md][upgrading] lists every change, and
782
+ says how to stay on 1.x.
783
+
784
+ ## License
785
+
786
+ Dual licensed under the [AGPL-3.0-only][agpl] or [MIT][mit] licenses. See
787
+ [LICENSE.md][license].
788
+
789
+ [upgrading]: https://github.com/zammad/zammad-api-client-ruby/blob/master/UPGRADING.md
790
+ [contributing]: https://github.com/zammad/zammad-api-client-ruby/blob/master/CONTRIBUTING.md
791
+ [roadmap]: https://github.com/zammad/zammad-api-client-ruby/blob/master/ROADMAP.md
792
+ [agpl]: https://github.com/zammad/zammad-api-client-ruby/blob/master/LICENSE.AGPL.txt
793
+ [mit]: https://github.com/zammad/zammad-api-client-ruby/blob/master/LICENSE.MIT.txt
794
+ [license]: https://github.com/zammad/zammad-api-client-ruby/blob/master/LICENSE.md