Skip to content

Commit c055bc9

Browse files
committed
docs: document 2.0 and the way up from 1.x
The README is rewritten around the 2.0 API: creating a client, the resources, records, collections, errors, timeouts and retries, logging, the test kit and the type signatures. A coverage table sets what 1.x and 2.0 model against what Zammad's API serves, and the text around it says how to reach the rest: a resource class of the caller's own, or a raw request. "Migrating from 1.x" lists every call that changed. It starts with the changes that do not announce themselves, where 1.x code keeps running and does something different. The changelog entry for 2.0.0.alpha1 carries the same changes as a list. "Staying on 1.x" is for those who do not move yet: the 1.x code lives on the 1-stable branch, it installs with a version constraint below 2, and it stays in maintenance mode, with fixes and no new features. examples/ holds nine runnable scripts, each built on Client.from_env: a quickstart, the ways to read a collection, pagination driven by hand, a CSV export, triage with pattern matching, onboarding a customer on behalf of a user, attachment downloads, error handling, and a worker pool sharing one client. The single 1.x example went with the rewrite.
1 parent 5b0298d commit c055bc9

12 files changed

Lines changed: 2397 additions & 250 deletions

‎CHANGELOG.md‎

Lines changed: 660 additions & 0 deletions
Large diffs are not rendered by default.

‎README.md‎

Lines changed: 1154 additions & 250 deletions
Large diffs are not rendered by default.

‎examples/README.md‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# Examples
2+
3+
Runnable scripts showing how the 2.0 API works in a real project. Each one is
4+
self-contained and builds its client with `ZammadAPI::Client.from_env`, which
5+
reads the credentials from the environment:
6+
7+
```sh
8+
export ZAMMAD_URL=https://zammad.example.com/
9+
export ZAMMAD_TOKEN=your-access-token
10+
11+
ruby examples/quickstart.rb
12+
```
13+
14+
`ZAMMAD_USER` and `ZAMMAD_PASSWORD` work instead of a token, as does
15+
`ZAMMAD_OAUTH2_TOKEN`.
16+
17+
> These scripts **create, modify and delete records**. Point them at a
18+
> disposable instance.
19+
20+
None of them set a timeout or a retry policy: requests time out after 60s and
21+
a read that fails transiently is retried with backoff out of the box, so the
22+
examples show what is left for your own code to do. A write is never repeated;
23+
`error_handling.rb` shows what that leaves to you.
24+
25+
| Script | What it does | API features it shows |
26+
| ------ | ------------ | --------------------- |
27+
| [`quickstart.rb`](quickstart.rb) | Creates a ticket, reads it back, adds an article, updates it | The basics end to end |
28+
| [`pagination.rb`](pagination.rb) | Reads a collection every available way | `each`, `find_each`, `in_batches`, `page(n, per_page: m)`, `search`, `order`, `count`, `empty?`, `lazy`, `first(n)`, `detect`, collection immutability |
29+
| [`manual_batches.rb`](manual_batches.rb) | Drives pagination by hand: pull-based, numbered, resumable | `in_batches` as an Enumerator (`next`, `with_index`), an explicit `page(n, per_page: m)` loop with a persisted cursor |
30+
| [`ticket_report.rb`](ticket_report.rb) | Exports every ticket to CSV | Automatic pagination, `in_batches` batching, `fetch` for required attributes |
31+
| [`triage_tickets.rb`](triage_tickets.rb) | Flags urgent tickets, nudges stale ones | `search`, `case/in` pattern matching on records, staged `changes` so only diffs are sent, `add_article` |
32+
| [`onboard_customer.rb`](onboard_customer.rb) | Creates an organization, a user, and a welcome ticket raised as that user | `find_by`, `create`, `on_behalf_of` as a scoped client and as a block |
33+
| [`download_attachments.rb`](download_attachments.rb) | Saves a ticket's attachments to disk | `articles`, attachment metadata, binary-safe `download` |
34+
| [`error_handling.rb`](error_handling.rb) | Handles the failures that are yours to handle | The error hierarchy, `save` → `false` with `record.error`, rescuing by category, `client.with` for different retry settings |
35+
| [`concurrent_sync.rb`](concurrent_sync.rb) | Syncs tickets with a worker pool sharing one client | Immutable clients are thread-safe; also sketches the Rails initializer pattern |
36+
37+
The examples are linted along with the rest of the repository (`rake rubocop`),
38+
so they cannot silently rot.

‎examples/concurrent_sync.rb‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
#!/usr/bin/env ruby
2+
# frozen_string_literal: true
3+
4+
# Syncs tickets from a worker pool that shares a single client.
5+
#
6+
# A client is immutable once built, so one instance is safe to share between
7+
# threads: no locking, no client per thread, and `on_behalf_of` scoping in one
8+
# thread cannot leak into another. It is the same reason one client works as a
9+
# Rails initializer constant used from every background worker:
10+
#
11+
# # config/initializers/zammad.rb
12+
# ZAMMAD = ZammadAPI::Client.new(
13+
# url: Rails.application.credentials.zammad_url,
14+
# http_token: Rails.application.credentials.zammad_token,
15+
# logger: Rails.logger
16+
# )
17+
#
18+
# ZAMMAD_URL=https://zammad.example.com/ ZAMMAD_TOKEN=... \
19+
# ruby examples/concurrent_sync.rb
20+
21+
require 'zammad_api'
22+
23+
WORKERS = 4
24+
25+
client = ZammadAPI::Client.from_env
26+
27+
# Collect the work first; `first` stops paginating once it has enough.
28+
queue = Queue.new
29+
client.tickets.all.first(40).each { queue << it.id }
30+
queue.close # so a worker draining an empty queue stops instead of blocking
31+
32+
results = Queue.new
33+
34+
workers = Array.new(WORKERS) do
35+
Thread.new do
36+
# Every worker shares this one client. Nothing about it is mutated by
37+
# making a request, so there is nothing to synchronise.
38+
while (id = queue.pop)
39+
results << begin
40+
client.tickets.find(id)
41+
:ok
42+
rescue ZammadAPI::Error => e
43+
# Transient failures were already retried, so anything arriving here
44+
# is worth reporting rather than trying again.
45+
warn "ticket #{id}: #{e.class}"
46+
:failed
47+
end
48+
end
49+
end
50+
end
51+
52+
workers.each(&:join)
53+
54+
tally = Hash.new(0)
55+
tally[results.pop] += 1 until results.empty?
56+
57+
puts "synced #{tally[:ok]}, failed #{tally[:failed]}"

‎examples/download_attachments.rb‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
#!/usr/bin/env ruby
2+
# frozen_string_literal: true
3+
4+
# Saves every attachment of a ticket to a directory.
5+
#
6+
# Shows walking articles, attachment metadata, and binary-safe downloads.
7+
#
8+
# ZAMMAD_URL=https://zammad.example.com/ ZAMMAD_TOKEN=... \
9+
# ruby examples/download_attachments.rb 12345 ./downloads
10+
11+
require 'zammad_api'
12+
require 'fileutils'
13+
14+
client = ZammadAPI::Client.from_env
15+
16+
ticket_id = Integer(ARGV.fetch(0) { abort "usage: #{$PROGRAM_NAME} TICKET_ID [DIRECTORY]" })
17+
directory = ARGV.fetch(1, "ticket-#{ticket_id}")
18+
19+
ticket = client.tickets.find(ticket_id)
20+
FileUtils.mkdir_p(directory)
21+
22+
# The filename comes from the server, so `File.basename` strips any directory
23+
# part that would otherwise let `../` escape the download directory. The ids
24+
# keep two same-named attachments from overwriting each other.
25+
def safe_filename(article_id, attachment)
26+
name = File.basename(attachment.filename.to_s)
27+
name = 'attachment' if name.empty? || name.start_with?('.')
28+
"#{article_id}-#{attachment.id}-#{name}"
29+
end
30+
31+
saved = 0
32+
33+
ticket.articles.each do |article|
34+
article.attachments.each do |attachment|
35+
# `download` returns the bytes as ASCII-8BIT, so images and archives
36+
# survive intact.
37+
contents = attachment.download
38+
File.binwrite(File.join(directory, safe_filename(article.id, attachment)), contents)
39+
saved += 1
40+
41+
puts format('%<file>-40s %<size>8d bytes', file: attachment.filename, size: contents.bytesize)
42+
end
43+
end
44+
45+
puts saved.zero? ? "Ticket ##{ticket.number} has no attachments." : "Saved #{saved} file(s) to #{directory}/"

‎examples/error_handling.rb‎

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
#!/usr/bin/env ruby
2+
# frozen_string_literal: true
3+
4+
# What to rescue, and what the client has already handled for you.
5+
#
6+
# Timeouts, connection failures and the transient statuses (429, 500, 502,
7+
# 503, 504) are retried with backoff on a GET before any error reaches your
8+
# code. A write is never repeated, because only you know whether sending it
9+
# twice is safe. So what is left to handle is what only you can decide about:
10+
# a missing record, a rejected attribute, bad credentials, a write that may or
11+
# may not have arrived.
12+
#
13+
# ZAMMAD_URL=https://zammad.example.com/ ZAMMAD_TOKEN=... \
14+
# ruby examples/error_handling.rb
15+
16+
require 'zammad_api'
17+
18+
# Options are validated up front, before any request is made.
19+
begin
20+
ZammadAPI::Client.new(url: 'not-a-url', http_token: 'x')
21+
rescue ZammadAPI::ConfigurationError => e
22+
puts "rejected early: #{e.message}"
23+
end
24+
25+
client = ZammadAPI::Client.from_env
26+
27+
# A missing record is a decision to make, not a failure to retry.
28+
ticket = begin
29+
client.tickets.find(0)
30+
rescue ZammadAPI::NotFoundError
31+
nil
32+
end
33+
34+
puts "missing ticket: #{ticket.inspect}"
35+
36+
# A rejected attribute (422) makes `save` return false and leaves the reason
37+
# on the record, so branching needs no begin/rescue.
38+
group = client.groups.new(name: '')
39+
40+
if group.save
41+
puts "created group: #{group.id}"
42+
else
43+
puts "rejected save: #{group.error.status} #{group.error.server_message}"
44+
puts " body #{group.error.body.inspect}"
45+
puts " operation #{group.error.operation} on #{group.error.resource_class}"
46+
end
47+
48+
# `create` and `save!` raise instead, which is what a script wants.
49+
begin
50+
client.groups.create(name: '')
51+
rescue ZammadAPI::ValidationError => e
52+
puts "raised instead: #{e.class}"
53+
end
54+
55+
# Rescue by category where the exact class does not matter.
56+
begin
57+
client.tickets.find(0)
58+
rescue ZammadAPI::ClientError => e # any 4xx
59+
puts "client error: #{e.status}"
60+
rescue ZammadAPI::ServerError => e # any 5xx, including an HTML proxy page
61+
puts "server error: #{e.status}"
62+
rescue ZammadAPI::TransportError => e # never reached the server, retries spent
63+
puts "transport error: #{e.message}"
64+
end
65+
66+
# Or catch everything this gem raises in one place.
67+
begin
68+
client.tickets.find(0)
69+
rescue ZammadAPI::Error => e
70+
puts "any gem error: #{e.class}"
71+
end
72+
73+
# Where the defaults do not suit the job, change them once on a derived
74+
# client instead of writing a retry loop around every call.
75+
patient = client.with(retries: 5, retry_interval: 1)
76+
77+
puts "derived client: #{patient.config.retries} retries, original still #{client.config.retries}"

‎examples/manual_batches.rb‎

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
#!/usr/bin/env ruby
2+
# frozen_string_literal: true
3+
4+
# Driving pagination yourself, for when the loop is not yours to own: a job
5+
# that has to checkpoint and resume, or a producer feeding a queue.
6+
#
7+
# ZAMMAD_URL=https://zammad.example.com/ ZAMMAD_TOKEN=... \
8+
# ruby examples/manual_batches.rb
9+
10+
require 'zammad_api'
11+
require 'fileutils'
12+
require 'tmpdir'
13+
14+
PER_PAGE = 50
15+
CURSOR = File.join(Dir.tmpdir, 'zammad_batch_cursor')
16+
17+
client = ZammadAPI::Client.from_env
18+
tickets = client.tickets.all
19+
20+
# 1. Pull a page when you are ready for it -----------------------------------
21+
#
22+
# `in_batches` without a block is an Enumerator: nothing is fetched until
23+
# `next`, and each `next` costs exactly one request.
24+
25+
puts '1. pulling two pages, leaving the rest unfetched'
26+
27+
pages = tickets.in_batches(of: PER_PAGE)
28+
29+
2.times do
30+
puts " pulled #{pages.next.size} tickets"
31+
rescue StopIteration
32+
break
33+
end
34+
35+
# 2. Numbered batches --------------------------------------------------------
36+
#
37+
# `with_index` is Ruby's own, and works for the same reason: an Enumerator.
38+
39+
puts '2. every batch, numbered'
40+
41+
tickets.in_batches(of: PER_PAGE).with_index do |batch, index|
42+
puts " batch #{index}: #{batch.size} tickets"
43+
end
44+
45+
# 3. A resumable page loop ---------------------------------------------------
46+
#
47+
# Own the page number when the job has to survive being interrupted. A page
48+
# shorter than the page size is the last one.
49+
50+
puts '3. resumable page loop'
51+
52+
page = File.exist?(CURSOR) ? Integer(File.read(CURSOR)) : 1
53+
puts " starting at page #{page}"
54+
55+
loop do
56+
batch = tickets.page(page, per_page: PER_PAGE).to_a
57+
break if batch.empty?
58+
59+
puts " page #{page}: #{batch.size} tickets"
60+
61+
# Checkpoint once the batch is safely handled, so an interrupted run
62+
# repeats a batch rather than skipping one.
63+
File.write(CURSOR, page + 1)
64+
break if batch.size < PER_PAGE
65+
66+
page += 1
67+
end
68+
69+
FileUtils.rm_f(CURSOR)
70+
71+
puts <<~NOTE
72+
73+
Which to reach for:
74+
75+
each / find_each the loop is yours and runs to completion
76+
in_batches you want one whole response at a time
77+
in_batches.next you want to pull batches as a consumer is ready
78+
in_batches.with_index you want the batches numbered as they arrive
79+
page(n, per_page: m) the page number must be persisted, retried or skipped
80+
81+
Pacing is not on this list: the client already backs off and retries a 429,
82+
so a manual sleep loop only duplicates it.
83+
NOTE

‎examples/onboard_customer.rb‎

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
#!/usr/bin/env ruby
2+
# frozen_string_literal: true
3+
4+
# Onboards a new customer: organization, user, and a welcome ticket raised as
5+
# that user.
6+
#
7+
# Shows `find_by` for a lookup by attribute, `create`, and `on_behalf_of` both
8+
# as a scoped client and as a block.
9+
#
10+
# ZAMMAD_URL=https://zammad.example.com/ ZAMMAD_TOKEN=... \
11+
# ruby examples/onboard_customer.rb "Acme Inc" jane@acme.test Jane Doe
12+
13+
require 'zammad_api'
14+
15+
client = ZammadAPI::Client.from_env
16+
17+
company, email, firstname, lastname = ARGV
18+
abort "usage: #{$PROGRAM_NAME} COMPANY EMAIL FIRSTNAME LASTNAME" if [company, email, firstname, lastname].any?(&:nil?)
19+
20+
# `find_by` searches and then checks the hits itself, because Zammad's index
21+
# endpoints cannot filter. It returns a record that genuinely carries the
22+
# attribute, or nil - never an unrelated one.
23+
#
24+
# What the search surfaces is Zammad's business, so a value it has not indexed
25+
# is a record this will not find, and the `|| create` below would then make a
26+
# second organization. Searching by hand has the same gap.
27+
organization = client.organizations.find_by(name: company) ||
28+
client.organizations.create(name: company)
29+
30+
puts "organization: #{organization.name} (id=#{organization.id})"
31+
32+
user = client.users.find_by(email: email) ||
33+
client.users.create(
34+
firstname: firstname,
35+
lastname: lastname,
36+
email: email,
37+
organization_id: organization.id,
38+
roles: ['Customer']
39+
)
40+
41+
puts "user: #{user.firstname} #{user.lastname} <#{user.email}> (id=#{user.id})"
42+
43+
# `on_behalf_of` returns a new client rather than mutating this one, so the
44+
# admin client stays unscoped and both remain safe to use.
45+
as_customer = client.on_behalf_of(user.email)
46+
47+
ticket = as_customer.tickets.create(
48+
title: "Welcome, #{firstname}!",
49+
group: 'Users',
50+
customer: user.email,
51+
article: {
52+
subject: 'Getting started',
53+
body: "Hi #{firstname},\n\nyour account is ready.",
54+
type: 'note'
55+
}
56+
)
57+
58+
puts "ticket: ##{ticket.number} raised as #{user.email}"
59+
60+
# The block form scopes a single operation.
61+
own_tickets = client.on_behalf_of(user.email) { |scoped| scoped.tickets.all.count }
62+
63+
puts "the customer can see #{own_tickets} ticket(s) of their own"

0 commit comments

Comments
 (0)