Shared Atlassian clients: atlassian/jira and atlassian/confluence

New library module yetano.dev/yetano/yetano-clients (owner decision
2026-11-01) replacing the three own Jira clients in yareco, yabaratla
and yamcp:

- atlassian: Options, Auth (api_token, basic, bearer/pat, cookie),
  Deployment (Cloud/Data Center), TLS, APIError and sentinel errors.
- atlassian/internal/transport: retry with backoff on 5xx/connection
  errors, shared adaptive 429 throttle honouring Retry-After (from
  yabaratla/yareco), CA file, proxy, cross-host redirect hardening,
  response cap (from yamcp), startAt pagination, file downloads.
- atlassian/jira: typed reads (projects, versions, fields, issues,
  comments, changelog, editmeta, transitions), JQL search on Cloud
  (/search/jql) and Data Center, classic search pages, issue writes,
  ADF/plain-text bodies per deployment, custom-field helpers.
- atlassian/confluence: small content API client (CQL search, pages,
  spaces, current user, create/update page with version check,
  comment, label), taken over from yamcp.

Standard library only; tests against httptest servers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
terminarandClaude Opus 5.5 committed 2026-11-01 14:11:00 +01:00
commit 6a97dbd4c6
24 files changed
+3524

No files matched your search

+49
View File
@@ -0,0 +1,49 @@
# AGENTS.md
Guidance for anyone (human or coding agent) working on `yetano-clients`.
The meta-repository's `AGENTS.md` (`../AGENTS.md`) applies as well; this
file only adds what is specific here. User-facing docs are in
[README.md](README.md), open work in [TODO.md](TODO.md).
## What this is
A library module, `yetano.dev/yetano/yetano-clients`, imported like
`core`: no `main`, no Makefile publish, no `internal/version`, no
Yetanofile. A release is a git tag (`vX.Y.Z`); consumers reach a change
only through a new tag. Never force-move a tag.
## Checks
```sh
make # gofmt check, go vet, go test -race, govulncheck
```
Tests use `httptest` servers only -- never a live Atlassian site.
## Rules
- Standard library only. A new dependency needs a real reason.
- `atlassian/internal/transport` owns everything HTTP: auth, TLS, proxy,
redirects, retries, the 429 throttle, pagination, downloads.
`jira` and `confluence` build requests and decode answers, nothing
more. Public configuration and error types live in `atlassian`.
- Credentials are never logged and never put into an error. Redirects
to another host drop them.
- No program-specific behaviour: no localized messages, no config-file
knowledge, no output shapes for a particular tool. Those stay in the
consuming program (yareco's `internal/jirautil`, yamcp's error mapping).
- Every call takes a `context.Context`, and every wait (backoff,
Retry-After, throttle, `APIDelay`) ends when it is cancelled.
- Cloud and Server/Data Center differ in API prefix and body encoding;
keep that switch inside the client (`APIPrefix`, `TextBody`), never in
the caller.
- An unexpected answer is an error, never an empty result (`ErrNotJSON`,
`OptionValues`/`SprintValues` on an unknown shape).
- Comments explain why, not what. Every exported identifier has a doc
comment.
## Consumers
`yareco`, `yabaratla`, `yamcp` (all in the yetano meta-repository). A
breaking API change needs a new minor version and the consumers bumped
in the same wave.
+15
View File
@@ -0,0 +1,15 @@
Copyright (c) 2026 Bjoern Kalkbrenner. All rights reserved.
This software and its documentation are proprietary
(SPDX: LicenseRef-Proprietary). No license to use, copy, modify, merge,
publish, distribute, sublicense or sell copies of this software, in whole
or in part, is granted without the prior written permission of the
copyright holder.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
+52
View File
@@ -0,0 +1,52 @@
# yetano-clients is a library (atlassian/jira, atlassian/confluence):
# nothing to build or publish, only to check. A release is a git tag --
# see README.md, "Versioning".
.PHONY: all
all: ci
.PHONY: test
test:
go test ./... -race
.PHONY: fmt
fmt:
@out="$$(gofmt -l .)"; \
if [ -n "$$out" ]; then \
echo "not gofmt'ed:"; echo "$$out"; exit 1; \
fi
.PHONY: fmt-fix
fmt-fix:
gofmt -w .
.PHONY: vet
vet:
go vet ./...
# govulncheck at a pinned version via "go run" -- no global install. Not
# part of test on purpose: it needs network access to vuln.go.dev, and
# since that database changes daily, a check would start failing without
# any code change (see ../TODO.md "govulncheck in allen Go-Modulen").
GOVULNCHECK ?= go run golang.org/x/vuln/cmd/govulncheck@v1.9.0
.PHONY: vulncheck
vulncheck:
$(GOVULNCHECK) ./...
.PHONY: tidy
tidy:
go mod tidy
.PHONY: ci
ci: fmt vet test vulncheck
.PHONY: help
help:
@echo "Targets:"
@echo " ci fmt + vet + test + vulncheck (the default)"
@echo " fmt fail if a file is not gofmt'ed (fmt-fix rewrites them)"
@echo " vet go vet"
@echo " test go test -race"
@echo " vulncheck govulncheck $(subst go run ,,$(GOVULNCHECK))"
@echo " tidy go mod tidy"
+118
View File
@@ -0,0 +1,118 @@
# yetano-clients
Shared Go clients for the external services Yetano programs talk to.
This is a library module (`yetano.dev/yetano/yetano-clients`), imported
like `core` -- nothing here is built or published as a program.
Today it holds the Atlassian clients that `yareco`, `yabaratla` and
`yamcp` used to carry as three separate copies (owner decision
2026-11-01):
| Package | What |
|---|---|
| `atlassian` | `Options`, `Auth`, `Deployment`, `TLS`, the error types (`APIError`, `StatusOf`, `ErrNotJSON`, `ErrResponseTooLarge`, `ErrInvalidArgument`) |
| `atlassian/jira` | Jira REST API client (Cloud v3 and Server/Data Center v2) |
| `atlassian/confluence` | small Confluence REST API client (classic content API) |
| `atlassian/internal/transport` | the HTTP machinery both share; not importable from outside |
Standard library only, no third-party dependencies.
## Usage
```go
c, err := jira.New(atlassian.Options{
BaseURL: "https://example.atlassian.net",
Deployment: atlassian.Cloud, // or atlassian.DataCenter
Auth: atlassian.Auth{Type: atlassian.AuthAPIToken, Username: email, Password: token},
Timeout: 60 * time.Second,
MaxRetries: 3,
})
issues, err := c.SearchAll(ctx, jira.SearchQuery{JQL: "project = DEV", Fields: []string{"summary"}})
```
`New` never sends a request. Every call takes a context; cancelling it
also ends a backoff or rate-limit wait.
## Transport behaviour
One `Options` drives both clients:
- **Auth**: `api_token` (e-mail + API token as basic auth, Cloud),
`basic`, `bearer`/`pat` (Data Center personal access token), `cookie`
(a raw Cookie header). The zero `Type` picks from the fields that are
set. A type whose fields are empty sends no header at all.
- **TLS/proxy**: optional CA bundle, explicit `InsecureSkipVerify`,
`ProxyURL` or the environment's `HTTPS_PROXY`.
- **Redirects** to another host drop `Authorization` and `Cookie`
(also for downloads, e.g. a signed media URL).
- **Retries**: 5xx and connection errors are retried `MaxRetries`
attempts in total with backoff 2s, 4s, ... (cap 30s). 4xx is never
retried.
- **429**: pauses every request of the client until `Retry-After` and
widens a shared minimum gap between requests, which narrows again on
success; up to 10 such retries that do not count against `MaxRetries`.
`DisableRateLimitRetry` returns the 429 at once instead.
- **APIDelay**: fixed pause after every response.
- **Bodies**: an empty 2xx body reads as `{}`; a non-JSON 2xx body
(e.g. an SSO login page) is `ErrNotJSON`, never an empty result.
`MaxResponseBytes` caps what is read into memory.
- **Errors**: a non-2xx answer is an `*atlassian.APIError` (method,
path, status, body; `Message()` extracts Atlassian's error text).
Credentials never appear in an error or a log line; a download URL's
query is dropped from errors and logs.
- **Pagination**: `Paginate` walks `startAt`/`maxResults` listings and
advances by the number of items actually returned (Jira may cap
`maxResults`).
## Jira
Typed calls: `Myself`, `ServerInfo`, `ListProjects`, `Project`,
`ProjectVersions`, `Version`, `UpdateVersion`, `Fields`, `Issue`,
`Search`/`SearchAll` (Cloud: `/search/jql` with `nextPageToken`; Data
Center: `/search` with offsets), `SearchPage` (one classic offset page),
`CommentPage`, `Comments`, `Changelog`, `EditMeta`, `Transitions`,
`EditIssue`/`UpdateIssue`, `CreateIssue`, `AddComment`, `DoTransition`,
`AssignIssue`, `LinkIssues`; `TextBody` encodes plain text as ADF on
Cloud and as a string on Data Center. Field helpers for custom fields:
`OptionValues`, `SprintValues`, `CustomFieldNumber`, `Names`.
Everything else goes through the raw `Get`/`Post`/`Put`/`Delete`/
`Paginate`/`DownloadFile` (paths are absolute, e.g.
`/rest/agile/1.0/board`).
## Confluence
`Search` (CQL), `Page`, `PageChildren`, `Space`, `ListSpaces`,
`CurrentUser`, `Ping`, `CreatePage`, `UpdatePage` (re-reads the page and
returns `*VersionConflictError` instead of overwriting a newer version),
`AddComment`, `AddLabel`; `StorageFromText` turns plain text into an
escaped storage-format body. Kept small on purpose -- see `TODO.md` for
what is not covered.
## Where the code came from
| Part | Origin |
|---|---|
| retry/backoff, 429 throttle, `APIDelay`, `Paginate`, `DownloadFile`, cookie auth | `yabaratla/internal/jira` (via `yareco`, which added contexts and `log/slog`) |
| typed Jira reads, `Search` with `nextPageToken`, field helpers | `yareco/internal/jira` |
| bearer/PAT/basic auth, CA file, proxy, redirect hardening, response cap, Atlassian error messages, Cloud/Data Center split, Jira writes, the Confluence client | `yamcp/internal/provider/atlassian` |
Program-specific parts stayed in the programs: yareco's German operator
messages and field resolution, yamcp's error taxonomy and MCP output
types, yabaratla's Confluence site-backup client.
## Checks
```sh
make # fmt + vet + test (-race) + vulncheck
make test
```
## Versioning
A release is a plain semver git tag (`v0.1.0`, ...) on this repository;
consumers require that tag. Never force-move a tag -- always cut a new
one, even for a one-line fix (see the meta-repository's `AGENTS.md`).
## License
Proprietary, see [LICENSE](LICENSE).
+29
View File
@@ -0,0 +1,29 @@
# TODO
## Next
- [ ] Tag `v0.1.0` (owner) once the first consumer switch is reviewed;
`yareco`, `yabaratla` and `yamcp` already require `v0.1.0`.
## Open
- [ ] **yamcp search on Cloud.** yamcp's `jira_search_issues` still
uses `SearchPage` (classic `POST /rest/api/3/search`), which Atlassian
has deprecated on Cloud in favour of `/search/jql` (`Search`). Moving
yamcp means a token-based paging contract for its tool (no `startAt`,
no `total`) -- a yamcp tool-API decision, tracked in yamcp's TODO.md.
- [ ] **Confluence site backup.** yabaratla's `internal/confluence`
(undocumented `/wiki/rest/obm/1.0` backup trigger/progress endpoints,
resumable range download of very large archives) stayed in yabaratla:
it is backup-tool logic on an unsupported API. Move it here only if a
second program needs it.
- [ ] **ADF rendering.** yareco (`internal/adf`) and yamcp
(`internal/sanitize/adf.go`) each turn Atlassian Document Format into
text, with different goals (release notes vs. sanitized MCP output).
A shared `atlassian/adf` is possible but needs both outputs compared
first.
- [ ] Confluence v2 API (`/wiki/api/v2`), attachments, page history:
not covered; add when a consumer needs them.
- [ ] Data Center `Changelog`: `/issue/{key}/changelog` exists on Cloud
only; on Data Center the history comes from `Issue(..., "changelog")`.
No consumer needs it yet.
+151
View File
@@ -0,0 +1,151 @@
// Package atlassian holds what the Jira and Confluence clients share:
// connection options, authentication, deployment kind and the error
// types every request can return. The HTTP machinery itself (retries,
// rate-limit throttling, pagination, downloads) lives in
// atlassian/internal/transport and is reached only through
// atlassian/jira and atlassian/confluence.
package atlassian
import (
"log/slog"
"net/http"
"time"
)
// Deployment selects the API flavour: Atlassian Cloud or a self-hosted
// Server/Data Center instance. The zero value is Cloud.
type Deployment string
const (
// Cloud is Atlassian Cloud (Jira REST API v3, ADF bodies,
// Confluence under /wiki).
Cloud Deployment = "cloud"
// DataCenter is Jira/Confluence Server or Data Center (Jira REST API
// v2, plain-text/wiki-markup bodies, Confluence at the site root).
DataCenter Deployment = "datacenter"
)
// IsCloud reports whether d is Cloud (including the zero value).
func (d Deployment) IsCloud() bool { return d != DataCenter }
// AuthType selects how Auth is applied to a request.
type AuthType string
const (
// AuthAuto picks from the fields that are set: Username+Password as
// basic auth, else Token as bearer, else Cookie.
AuthAuto AuthType = ""
// AuthAPIToken is HTTP basic auth with the account e-mail as
// Username and the API token as Password (Atlassian Cloud).
AuthAPIToken AuthType = "api_token"
// AuthBasic is HTTP basic auth with username and password.
AuthBasic AuthType = "basic"
// AuthBearer sends "Authorization: Bearer <Token>" (Data Center
// personal access tokens, OAuth bearer tokens).
AuthBearer AuthType = "bearer"
// AuthPAT is AuthBearer under the name Data Center uses.
AuthPAT AuthType = "pat"
// AuthCookie sends Cookie verbatim as the Cookie header (a browser
// session, for sites where no token can be issued).
AuthCookie AuthType = "cookie"
)
// Auth is the resolved authentication material for one site. It lives
// in memory only and is never logged or put into an error.
type Auth struct {
Type AuthType
Username string // e-mail for AuthAPIToken
Password string // API token for AuthAPIToken
Token string // AuthBearer/AuthPAT
Cookie string // AuthCookie: the raw Cookie header value
}
// Apply sets the credentials on req. A type whose fields are empty sends
// nothing rather than an empty Authorization header.
func (a Auth) Apply(req *http.Request) {
switch a.effectiveType() {
case AuthAPIToken, AuthBasic:
if a.Username != "" && a.Password != "" {
req.SetBasicAuth(a.Username, a.Password)
}
case AuthBearer, AuthPAT:
if a.Token != "" {
req.Header.Set("Authorization", "Bearer "+a.Token)
}
case AuthCookie:
if a.Cookie != "" {
req.Header.Set("Cookie", a.Cookie)
}
}
}
// IsSet reports whether Apply would send any credentials.
func (a Auth) IsSet() bool {
switch a.effectiveType() {
case AuthAPIToken, AuthBasic:
return a.Username != "" && a.Password != ""
case AuthBearer, AuthPAT:
return a.Token != ""
case AuthCookie:
return a.Cookie != ""
}
return false
}
func (a Auth) effectiveType() AuthType {
if a.Type != AuthAuto {
return a.Type
}
switch {
case a.Username != "" && a.Password != "":
return AuthBasic
case a.Token != "":
return AuthBearer
case a.Cookie != "":
return AuthCookie
}
return AuthAuto
}
// TLS configures certificate verification.
type TLS struct {
// CAFile is a PEM bundle used instead of the system roots.
CAFile string
// InsecureSkipVerify turns verification off; an explicit opt-in.
InsecureSkipVerify bool
}
// Options configures a Jira or Confluence client.
type Options struct {
// BaseURL is the site root ("https://example.atlassian.net"), without
// /rest/... or /wiki; a trailing slash is ignored.
BaseURL string
Deployment Deployment
Auth Auth
TLS TLS
// ProxyURL overrides the proxy; empty uses HTTP(S)_PROXY from the
// environment.
ProxyURL string
// Timeout bounds one request, 0 means none.
Timeout time.Duration
// DownloadTimeout bounds one file download, 0 means none.
DownloadTimeout time.Duration
// MaxRetries is the number of attempts for 5xx answers and connection
// errors (values below 1 mean 1, i.e. no retry). Backoff is
// exponential, 2s, 4s, ... capped at 30s.
MaxRetries int
// DisableRateLimitRetry returns a 429 as an *APIError right away.
// Without it a 429 pauses every request of the client until
// Retry-After and is retried (up to 10 times) without using up
// MaxRetries.
DisableRateLimitRetry bool
// APIDelay is a fixed pause after every response.
APIDelay time.Duration
// MaxResponseBytes caps a response body read into memory; 0 means no
// cap. A larger body fails with ErrResponseTooLarge.
MaxResponseBytes int64
// Logger receives retry and throttling messages (never headers or
// credentials). Nil means slog.Default().
Logger *slog.Logger
}
+201
View File
@@ -0,0 +1,201 @@
// Package confluence is a small Confluence REST API client (the classic
// /rest/api content API) for Atlassian Cloud and Server/Data Center:
// CQL search, pages with their children and ancestors, spaces, the
// current user, and the writes create page, update page (with an
// optimistic version check), footer comment and label.
//
// It is deliberately small -- what yamcp uses, taken over from there --
// not a complete Confluence SDK. Cloud's newer v2 API (/wiki/api/v2),
// attachments and the site-backup endpoints yabaratla drives are not
// covered (see the repository's TODO.md).
package confluence
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
"strconv"
"time"
"yetano.dev/yetano/yetano-clients/atlassian"
"yetano.dev/yetano/yetano-clients/atlassian/internal/transport"
)
// Client is a Confluence client. It is safe for concurrent use.
type Client struct {
t *transport.Client
cloud bool
}
// New builds a Client. BaseURL is the site root: on Cloud without the
// /wiki suffix (the client adds it), on Server/Data Center the
// Confluence root. It sends no request.
func New(o atlassian.Options) (*Client, error) {
t, err := transport.New(o)
if err != nil {
return nil, err
}
return &Client{t: t, cloud: o.Deployment.IsCloud()}, nil
}
// BaseURL is the site root without trailing slash.
func (c *Client) BaseURL() string { return c.t.BaseURL() }
// IsCloud reports whether the client talks to Atlassian Cloud.
func (c *Client) IsCloud() bool { return c.cloud }
// APIPrefix is /wiki/rest/api on Cloud and /rest/api on Server/Data
// Center.
func (c *Client) APIPrefix() string {
if c.cloud {
return "/wiki/rest/api"
}
return "/rest/api"
}
func (c *Client) api(suffix string) string { return c.APIPrefix() + suffix }
// WebBase is the root of the browsable site (with /wiki on Cloud).
func (c *Client) WebBase() string {
if c.cloud {
return c.BaseURL() + "/wiki"
}
return c.BaseURL()
}
// PageURL is the browser URL of a page: from its _links.webui when
// known, else the viewpage.action form.
func (c *Client) PageURL(id string, links *Links) string {
if links != nil && links.WebUI != "" {
return c.WebBase() + links.WebUI
}
return fmt.Sprintf("%s/pages/viewpage.action?pageId=%s", c.WebBase(), id)
}
// Close releases idle connections.
func (c *Client) Close() { c.t.Close() }
// SetSleep replaces every wait -- for tests that must not really wait.
func (c *Client) SetSleep(f func(ctx context.Context, d time.Duration) error) { c.t.SetSleep(f) }
// Get issues a GET against BaseURL+path (for endpoints without a typed
// call) and returns the JSON body.
func (c *Client) Get(ctx context.Context, path string, params url.Values) (json.RawMessage, error) {
return c.t.Do(ctx, http.MethodGet, path, params, nil)
}
func (c *Client) do(ctx context.Context, method, path string, q url.Values, body, out any) error {
raw, err := c.t.Do(ctx, method, path, q, body)
if err != nil {
return err
}
if out == nil {
return nil
}
if err := json.Unmarshal(raw, out); err != nil {
return fmt.Errorf("%s %s: decoding response: %w", method, path, err)
}
return nil
}
func requireID(what, v string) error {
if v == "" {
return fmt.Errorf("%w: %s must not be empty", atlassian.ErrInvalidArgument, what)
}
return nil
}
const contentExpand = "space,version,body.storage,ancestors"
// SearchOptions is one CQL search page. SpaceKey and ContentType are
// convenience filters ANDed onto CQL.
type SearchOptions struct {
CQL string
Start int
Limit int
SpaceKey string
ContentType string // "page", "blogpost", ...
}
// Search runs a CQL search and returns one page of content with space,
// version, storage body and ancestors expanded.
func (c *Client) Search(ctx context.Context, o SearchOptions) (ContentList, error) {
var out ContentList
cql := o.CQL
if o.SpaceKey != "" {
cql = addCQLClause(cql, fmt.Sprintf("space = %q", o.SpaceKey))
}
if o.ContentType != "" {
cql = addCQLClause(cql, fmt.Sprintf("type = %q", o.ContentType))
}
if cql == "" {
return out, fmt.Errorf("%w: cql (or space/content type filters) must resolve to a non-empty query", atlassian.ErrInvalidArgument)
}
q := url.Values{
"cql": {cql},
"start": {strconv.Itoa(o.Start)},
"limit": {strconv.Itoa(o.Limit)},
"expand": {contentExpand},
}
return out, c.do(ctx, http.MethodGet, c.api("/content/search"), q, nil, &out)
}
func addCQLClause(existing, clause string) string {
if existing == "" {
return clause
}
return existing + " AND " + clause
}
// Page returns one page (or other content) with space, version, storage
// body and ancestors.
func (c *Client) Page(ctx context.Context, id string) (Content, error) {
var out Content
if err := requireID("page id", id); err != nil {
return out, err
}
q := url.Values{"expand": {contentExpand}}
return out, c.do(ctx, http.MethodGet, c.api("/content/"+url.PathEscape(id)), q, nil, &out)
}
// PageChildren returns one page of a page's direct child pages.
func (c *Client) PageChildren(ctx context.Context, id string, start, limit int) (ContentList, error) {
var out ContentList
if err := requireID("page id", id); err != nil {
return out, err
}
q := url.Values{"start": {strconv.Itoa(start)}, "limit": {strconv.Itoa(limit)}}
return out, c.do(ctx, http.MethodGet, c.api("/content/"+url.PathEscape(id)+"/child/page"), q, nil, &out)
}
// Space returns one space with its plain description and home page.
func (c *Client) Space(ctx context.Context, key string) (Space, error) {
var out Space
if err := requireID("space key", key); err != nil {
return out, err
}
q := url.Values{"expand": {"description.plain,homepage"}}
return out, c.do(ctx, http.MethodGet, c.api("/space/"+url.PathEscape(key)), q, nil, &out)
}
// ListSpaces returns one page of the spaces the account can see.
func (c *Client) ListSpaces(ctx context.Context, start, limit int) (SpaceList, error) {
var out SpaceList
q := url.Values{"start": {strconv.Itoa(start)}, "limit": {strconv.Itoa(limit)}}
return out, c.do(ctx, http.MethodGet, c.api("/space"), q, nil, &out)
}
// CurrentUser returns the authenticated account.
func (c *Client) CurrentUser(ctx context.Context) (User, error) {
var out User
return out, c.do(ctx, http.MethodGet, c.api("/user/current"), nil, nil, &out)
}
// Ping checks that the API answers (one space listed). Confluence has no
// server-info endpoint that is stable across Cloud and Data Center, so
// this is reachability only, not a version.
func (c *Client) Ping(ctx context.Context) error {
return c.do(ctx, http.MethodGet, c.api("/space"), url.Values{"limit": {"1"}}, nil, nil)
}
+174
View File
@@ -0,0 +1,174 @@
package confluence
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"testing"
"yetano.dev/yetano/yetano-clients/atlassian"
)
func newTestClient(t *testing.T, h http.HandlerFunc, dep atlassian.Deployment) *Client {
t.Helper()
srv := httptest.NewServer(h)
t.Cleanup(srv.Close)
c, err := New(atlassian.Options{BaseURL: srv.URL, Deployment: dep,
Auth: atlassian.Auth{Type: atlassian.AuthBearer, Token: "t"},
Logger: slog.New(slog.NewTextHandler(io.Discard, nil))})
if err != nil {
t.Fatal(err)
}
return c
}
func TestPrefixesAndURLs(t *testing.T) {
noop := func(http.ResponseWriter, *http.Request) {}
cloud := newTestClient(t, noop, atlassian.Cloud)
dc := newTestClient(t, noop, atlassian.DataCenter)
if cloud.APIPrefix() != "/wiki/rest/api" || dc.APIPrefix() != "/rest/api" {
t.Errorf("prefixes = %q, %q", cloud.APIPrefix(), dc.APIPrefix())
}
if got := cloud.PageURL("5", &Links{WebUI: "/spaces/IT/pages/5"}); got != cloud.BaseURL()+"/wiki/spaces/IT/pages/5" {
t.Errorf("PageURL with links = %q", got)
}
if got := dc.PageURL("5", nil); got != dc.BaseURL()+"/pages/viewpage.action?pageId=5" {
t.Errorf("PageURL fallback = %q", got)
}
}
func TestSearchBuildsCQLFromFilters(t *testing.T) {
var gotCQL, gotPath string
c := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
gotPath, gotCQL = r.URL.Path, r.URL.Query().Get("cql")
fmt.Fprint(w, `{"results":[{"id":"1","title":"A","version":{"number":2}}],"size":1}`)
}, atlassian.Cloud)
res, err := c.Search(context.Background(), SearchOptions{CQL: `text ~ "x"`, SpaceKey: "IT", ContentType: "page", Limit: 5})
if err != nil || len(res.Results) != 1 || res.Results[0].Version.Number != 2 {
t.Fatalf("res = %+v, %v", res, err)
}
if gotPath != "/wiki/rest/api/content/search" || gotCQL != `text ~ "x" AND space = "IT" AND type = "page"` {
t.Errorf("path = %q, cql = %q", gotPath, gotCQL)
}
}
func TestEmptyArgumentsSendNothing(t *testing.T) {
c := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
t.Errorf("request sent: %s %s", r.Method, r.URL.Path)
}, atlassian.Cloud)
ctx := context.Background()
errs := map[string]error{}
_, errs["Search"] = c.Search(ctx, SearchOptions{})
_, errs["Page"] = c.Page(ctx, "")
_, errs["Space"] = c.Space(ctx, "")
_, errs["AddComment"] = c.AddComment(ctx, "", "x")
for name, err := range errs {
if !errors.Is(err, atlassian.ErrInvalidArgument) {
t.Errorf("%s: err = %v, want ErrInvalidArgument", name, err)
}
}
}
func pageHandler(t *testing.T, onPut func(body map[string]any)) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet {
fmt.Fprint(w, `{"id":"123","title":"Page","space":{"key":"IT"},"version":{"number":5}}`)
return
}
if onPut == nil {
t.Fatalf("unexpected %s", r.Method)
}
var body map[string]any
_ = json.NewDecoder(r.Body).Decode(&body)
onPut(body)
fmt.Fprint(w, `{}`)
}
}
func TestUpdatePageRefusesStaleVersion(t *testing.T) {
c := newTestClient(t, pageHandler(t, nil), atlassian.Cloud)
err := c.UpdatePage(context.Background(), UpdatePageInput{ID: "123", Content: "new", ExpectedVersion: 3})
var vc *VersionConflictError
if !errors.As(err, &vc) || vc.Current != 5 || vc.Expected != 3 {
t.Fatalf("err = %v, want VersionConflictError 5/3", err)
}
}
func TestUpdatePageWritesNextVersion(t *testing.T) {
var put map[string]any
c := newTestClient(t, pageHandler(t, func(b map[string]any) { put = b }), atlassian.Cloud)
if err := c.UpdatePage(context.Background(), UpdatePageInput{ID: "123", Content: "a <b>\n\nc", ExpectedVersion: 5}); err != nil {
t.Fatal(err)
}
if put["version"].(map[string]any)["number"].(float64) != 6 || put["title"] != "Page" {
t.Errorf("PUT = %v", put)
}
storage := put["body"].(map[string]any)["storage"].(map[string]any)
if storage["value"] != "<p>a &lt;b&gt;</p><p>c</p>" || storage["representation"] != "storage" {
t.Errorf("storage = %v", storage)
}
}
func TestCreatePageCommentLabel(t *testing.T) {
bodies := map[string]any{}
c := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
var body any
_ = json.NewDecoder(r.Body).Decode(&body)
key := r.Method + " " + r.URL.Path
if m, ok := body.(map[string]any); ok && m["type"] == "comment" {
key += " comment"
}
bodies[key] = body
fmt.Fprint(w, `{"id":"9"}`)
}, atlassian.DataCenter)
ctx := context.Background()
if id, err := c.CreatePage(ctx, CreatePageInput{SpaceKey: "IT", Title: "T", Content: "x", ParentPageID: "1"}); err != nil || id != "9" {
t.Fatalf("create = %q, %v", id, err)
}
if id, err := c.AddComment(ctx, "9", "hi"); err != nil || id != "9" {
t.Fatalf("comment = %q, %v", id, err)
}
if err := c.AddLabel(ctx, "9", "ops"); err != nil {
t.Fatal(err)
}
page := bodies["POST /rest/api/content"].(map[string]any)
if page["ancestors"].([]any)[0].(map[string]any)["id"] != "1" || page["space"].(map[string]any)["key"] != "IT" {
t.Errorf("create body = %v", page)
}
comment := bodies["POST /rest/api/content comment"].(map[string]any)
if comment["container"].(map[string]any)["id"] != "9" {
t.Errorf("comment body = %v", comment)
}
label := bodies["POST /rest/api/content/9/label"].([]any)[0].(map[string]any)
if label["prefix"] != "global" || label["name"] != "ops" {
t.Errorf("label body = %v", label)
}
}
func TestPingAndCurrentUser(t *testing.T) {
c := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Authorization") != "Bearer t" {
t.Errorf("auth header = %q", r.Header.Get("Authorization"))
}
switch r.URL.Path {
case "/wiki/rest/api/space":
fmt.Fprint(w, `{"results":[],"size":0}`)
case "/wiki/rest/api/user/current":
fmt.Fprint(w, `{"accountId":"a1","displayName":"Ada"}`)
default:
w.WriteHeader(http.StatusNotFound)
}
}, atlassian.Cloud)
if err := c.Ping(context.Background()); err != nil {
t.Fatal(err)
}
u, err := c.CurrentUser(context.Background())
if err != nil || u.DisplayName != "Ada" {
t.Fatalf("user = %+v, %v", u, err)
}
}
+94
View File
@@ -0,0 +1,94 @@
package confluence
// Content is a page, blog post or comment.
type Content struct {
ID string `json:"id"`
Type string `json:"type"`
Status string `json:"status"`
Title string `json:"title"`
Space *SpaceRef `json:"space"`
Version *Version `json:"version"`
Body *Body `json:"body"`
Ancestors []ContentRef `json:"ancestors"`
Links *Links `json:"_links"`
}
// ContentRef is a minimal content reference (ancestors, children, home
// page).
type ContentRef struct {
ID string `json:"id"`
Title string `json:"title,omitempty"`
}
// SpaceRef identifies a space inside content.
type SpaceRef struct {
ID int `json:"id,omitempty"`
Key string `json:"key"`
Name string `json:"name,omitempty"`
}
// Version is a content version.
type Version struct {
Number int `json:"number"`
When string `json:"when"`
By *User `json:"by"`
}
// Body holds the storage-format body when expanded.
type Body struct {
Storage *BodyRepresentation `json:"storage"`
}
// BodyRepresentation is one body format ("storage", "plain", ...).
type BodyRepresentation struct {
Value string `json:"value"`
Representation string `json:"representation"`
}
// Links are the _links of a content object.
type Links struct {
WebUI string `json:"webui"`
Base string `json:"base"`
}
// User is a Confluence account: AccountID on Cloud, Username on
// Server/Data Center.
type User struct {
AccountID string `json:"accountId"`
Username string `json:"username"`
DisplayName string `json:"displayName"`
Email string `json:"email"`
AccountEmail string `json:"accountEmail,omitempty"`
}
// ContentList is one page of content.
type ContentList struct {
Results []Content `json:"results"`
Start int `json:"start"`
Limit int `json:"limit"`
Size int `json:"size"`
}
// Space is a Confluence space.
type Space struct {
ID int `json:"id"`
Key string `json:"key"`
Name string `json:"name"`
Type string `json:"type"`
Status string `json:"status"`
Description *SpaceDescription `json:"description"`
Homepage *ContentRef `json:"homepage"`
}
// SpaceDescription holds the expanded plain description.
type SpaceDescription struct {
Plain *BodyRepresentation `json:"plain"`
}
// SpaceList is one page of spaces.
type SpaceList struct {
Results []Space `json:"results"`
Start int `json:"start"`
Limit int `json:"limit"`
Size int `json:"size"`
}
+148
View File
@@ -0,0 +1,148 @@
package confluence
import (
"context"
"fmt"
"html"
"net/http"
"net/url"
"strings"
)
// StorageFromText turns plain text into a minimal storage-format body:
// each blank-line-separated paragraph becomes an HTML-escaped <p>. It
// never passes markup through, so text from an untrusted source cannot
// inject active content into a page.
func StorageFromText(text string) string {
var b strings.Builder
for _, p := range strings.Split(strings.TrimSpace(text), "\n\n") {
p = strings.TrimSpace(p)
if p == "" {
continue
}
b.WriteString("<p>")
b.WriteString(html.EscapeString(p))
b.WriteString("</p>")
}
return b.String()
}
type storageBody struct {
Storage BodyRepresentation `json:"storage"`
}
func storage(text string) storageBody {
return storageBody{Storage: BodyRepresentation{Value: StorageFromText(text), Representation: "storage"}}
}
// CreatePageInput describes a new page; Content is plain text (see
// StorageFromText).
type CreatePageInput struct {
SpaceKey string
Title string
Content string
ParentPageID string
}
// CreatePage creates a page and returns its ID.
func (c *Client) CreatePage(ctx context.Context, in CreatePageInput) (string, error) {
body := map[string]any{
"type": "page",
"title": in.Title,
"space": SpaceRef{Key: in.SpaceKey},
"body": storage(in.Content),
}
if in.ParentPageID != "" {
body["ancestors"] = []ContentRef{{ID: in.ParentPageID}}
}
var resp Content
if err := c.do(ctx, http.MethodPost, c.api("/content"), nil, body, &resp); err != nil {
return "", err
}
return resp.ID, nil
}
// VersionConflictError is returned by UpdatePage when the page changed
// since the caller read it.
type VersionConflictError struct {
PageID string
Current int
Expected int
}
func (e *VersionConflictError) Error() string {
return fmt.Sprintf("page %s has changed since it was last read (current version %d, expected %d); re-read the page and retry",
e.PageID, e.Current, e.Expected)
}
// UpdatePageInput describes an update; Content is plain text.
type UpdatePageInput struct {
ID string
Title string // empty keeps the current title
Content string
ExpectedVersion int // the version the caller last read
NewParentID string // empty keeps the parent
}
// UpdatePage replaces a page's body, never blindly: it re-reads the page
// and returns a *VersionConflictError without writing anything when its
// current version is not ExpectedVersion.
func (c *Client) UpdatePage(ctx context.Context, in UpdatePageInput) error {
current, err := c.Page(ctx, in.ID)
if err != nil {
return err
}
if current.Version == nil {
return fmt.Errorf("page %s has no version information", in.ID)
}
if current.Version.Number != in.ExpectedVersion {
return &VersionConflictError{PageID: in.ID, Current: current.Version.Number, Expected: in.ExpectedVersion}
}
title := in.Title
if title == "" {
title = current.Title
}
spaceKey := ""
if current.Space != nil {
spaceKey = current.Space.Key
}
body := map[string]any{
"id": in.ID,
"type": "page",
"title": title,
"space": SpaceRef{Key: spaceKey},
"body": storage(in.Content),
"version": map[string]int{"number": current.Version.Number + 1},
}
if in.NewParentID != "" {
body["ancestors"] = []ContentRef{{ID: in.NewParentID}}
}
return c.do(ctx, http.MethodPut, c.api("/content/"+url.PathEscape(in.ID)), nil, body, nil)
}
// AddComment adds a plain-text footer comment to a page and returns its
// ID.
func (c *Client) AddComment(ctx context.Context, pageID, text string) (string, error) {
if err := requireID("page id", pageID); err != nil {
return "", err
}
body := map[string]any{
"type": "comment",
"container": map[string]string{"id": pageID, "type": "page"},
"body": storage(text),
}
var resp Content
if err := c.do(ctx, http.MethodPost, c.api("/content"), nil, body, &resp); err != nil {
return "", err
}
return resp.ID, nil
}
// AddLabel adds a global label to a page.
func (c *Client) AddLabel(ctx context.Context, pageID, label string) error {
if err := requireID("page id", pageID); err != nil {
return err
}
body := []map[string]string{{"prefix": "global", "name": label}}
return c.do(ctx, http.MethodPost, c.api("/content/"+url.PathEscape(pageID)+"/label"), nil, body, nil)
}
+82
View File
@@ -0,0 +1,82 @@
package atlassian
import (
"encoding/json"
"errors"
"fmt"
"strings"
)
// ErrResponseTooLarge is returned when a response body exceeds
// Options.MaxResponseBytes.
var ErrResponseTooLarge = errors.New("response body too large")
// ErrNotJSON is returned when a successful response carries a body that
// is not JSON -- typically an HTML login page from an SSO proxy in front
// of the site. It is never silently treated as an empty object.
var ErrNotJSON = errors.New("response is not JSON")
// ErrTLSConfig marks a client that could not be built because its CA
// file is unreadable or holds no certificate.
var ErrTLSConfig = errors.New("TLS configuration")
// ErrInvalidArgument marks a call rejected before any request was sent
// (an empty key, an empty query, ...).
var ErrInvalidArgument = errors.New("invalid argument")
// APIError is a non-successful HTTP answer (after any retries).
type APIError struct {
StatusCode int
Method string
Path string // request path without query or host
Body string // response body as received
}
func (e *APIError) Error() string {
body := strings.TrimSpace(e.Body)
if len(body) > 300 {
body = body[:300]
}
return fmt.Sprintf("%s %s: HTTP %d: %s", e.Method, e.Path, e.StatusCode, body)
}
// Message extracts the human-readable message from Atlassian's error
// bodies ({"errorMessages":[...]}, {"errors":{field:msg}},
// {"message":...}); for any other body it returns at most 500 bytes of
// it, and a fixed text for an empty one.
func (e *APIError) Message() string {
body := []byte(e.Body)
var parsed struct {
ErrorMessages []string `json:"errorMessages"`
Errors map[string]string `json:"errors"`
Message string `json:"message"`
}
if err := json.Unmarshal(body, &parsed); err != nil {
if len(body) == 0 {
return "no additional detail from upstream"
}
if len(body) > 500 {
body = body[:500]
}
return string(body)
}
if len(parsed.ErrorMessages) > 0 {
return parsed.ErrorMessages[0]
}
if parsed.Message != "" {
return parsed.Message
}
for field, msg := range parsed.Errors {
return field + ": " + msg
}
return "no additional detail from upstream"
}
// StatusOf returns the HTTP status of an *APIError in err's chain, or 0.
func StatusOf(err error) int {
var apiErr *APIError
if errors.As(err, &apiErr) {
return apiErr.StatusCode
}
return 0
}
+111
View File
@@ -0,0 +1,111 @@
package transport
import (
"context"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"time"
)
var errRateLimited = errors.New("rate limited (429)")
// DownloadFile streams fileURL -- absolute, or a path starting with "/"
// resolved against BaseURL -- to dest, creating dest's directory. It
// retries like Do (MaxRetries for errors, the separate budget for 429s)
// and removes a partial file before every retry and after a failure.
// Credentials go with the request itself -- the caller passes URLs the
// API handed out (attachment "content" links) -- but, as everywhere, not
// along a redirect to another host (e.g. a signed media URL).
func (c *Client) DownloadFile(ctx context.Context, fileURL, dest string) error {
full := fileURL
if strings.HasPrefix(fileURL, "/") {
full = c.baseURL + fileURL
}
var lastErr error
rateLimited := 0
for attempt := 1; attempt <= c.maxRetries; attempt++ {
err := c.downloadOnce(ctx, full, dest, rateLimited+1)
if err == nil {
return nil
}
lastErr = err
os.Remove(dest) //nolint:errcheck // best-effort cleanup of a partial download
if ctx.Err() != nil {
return ctx.Err()
}
if errors.Is(err, errRateLimited) {
if rateLimited++; rateLimited > maxRateLimitRetries {
break
}
attempt-- // throttling doesn't use up MaxRetries, see Do
continue
}
if attempt < c.maxRetries {
c.log.Warn("atlassian download failed, retrying", "attempt", attempt, "max", c.maxRetries, "url", redactURL(full), "err", err)
if err := c.sleep(ctx, backoff(attempt, 30)); err != nil {
return err
}
}
}
return fmt.Errorf("download failed after %d attempt(s): %w", c.maxRetries, lastErr)
}
func (c *Client) downloadOnce(ctx context.Context, full, dest string, rateLimitAttempt int) error {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, full, nil)
if err != nil {
return err
}
c.auth.Apply(req)
if err := c.throttle.acquire(ctx, c.sleep); err != nil {
return err
}
resp, err := c.download.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusTooManyRequests && c.retry429 {
c.throttle.rateLimited(retryAfter(resp.Header, rateLimitAttempt, time.Now()))
return errRateLimited
}
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("GET %s: HTTP %d", redactURL(full), resp.StatusCode)
}
if err := os.MkdirAll(filepath.Dir(dest), 0o755); err != nil {
return err
}
f, err := os.Create(dest)
if err != nil {
return err
}
if _, err := io.Copy(f, resp.Body); err != nil {
f.Close()
return err
}
if err := f.Close(); err != nil {
return err
}
c.throttle.succeeded()
return nil
}
// redactURL drops the query, which on signed media URLs is a credential.
func redactURL(s string) string {
u, err := url.Parse(s)
if err != nil {
return "(unparsable URL)"
}
u.RawQuery = ""
u.User = nil
return u.String()
}
+109
View File
@@ -0,0 +1,109 @@
package transport
import (
"context"
"log/slog"
"net/http"
"strconv"
"sync"
"time"
)
// Adaptive throttling across all goroutines sharing one Client: a 429
// pauses every request until Retry-After and widens a shared minimum gap
// between request starts (multiplicative increase); each success narrows
// it again (slow decrease) until it is back to zero, i.e. only APIDelay
// applies. With parallel workers a 429 that only slept its own request
// would leave the others hammering the API.
const (
minInterval = 100 * time.Millisecond
maxInterval = 10 * time.Second
recoverFactor = 0.95
maxRateLimitRetries = 10
)
type throttle struct {
mu sync.Mutex
interval time.Duration // shared minimum gap between request starts
next time.Time // earliest start for the next request
pauseUntil time.Time // global pause after a 429
now func() time.Time
log *slog.Logger
}
func newThrottle(log *slog.Logger) *throttle {
return &throttle{now: time.Now, log: log}
}
// acquire blocks until this request may start, or ctx ends.
func (t *throttle) acquire(ctx context.Context, sleep func(context.Context, time.Duration) error) error {
t.mu.Lock()
at := t.now()
if t.pauseUntil.After(at) {
at = t.pauseUntil
}
if t.next.After(at) {
at = t.next
}
t.next = at.Add(t.interval)
wait := at.Sub(t.now())
t.mu.Unlock()
if wait > 0 {
return sleep(ctx, wait)
}
return ctx.Err()
}
// rateLimited records a 429: pause everyone for wait and slow down.
// Requests that hit the same burst while the pause is already active
// don't slow down any further, so N parallel 429s count as one signal.
func (t *throttle) rateLimited(wait time.Duration) {
t.mu.Lock()
defer t.mu.Unlock()
now := t.now()
if now.Before(t.pauseUntil) {
if until := now.Add(wait); until.After(t.pauseUntil) {
t.pauseUntil = until
}
return
}
t.pauseUntil = now.Add(wait)
t.interval = min(max(t.interval*2, minInterval), maxInterval)
t.log.Warn("atlassian rate limited (429)", "pause", wait, "interval", t.interval)
}
// succeeded narrows the gap again after a successful response.
func (t *throttle) succeeded() {
t.mu.Lock()
defer t.mu.Unlock()
if t.interval == 0 {
return
}
t.interval = time.Duration(float64(t.interval) * recoverFactor)
if t.interval < minInterval {
t.interval = 0
t.log.Info("atlassian rate limit recovered")
}
}
// retryAfter returns how long a 429 response asks us to wait: the
// Retry-After header (seconds or HTTP date), else exponential backoff.
func retryAfter(header http.Header, attempt int, now time.Time) time.Duration {
if ra := header.Get("Retry-After"); ra != "" {
if secs, err := strconv.Atoi(ra); err == nil && secs >= 0 {
return time.Duration(secs) * time.Second
}
if t, err := http.ParseTime(ra); err == nil {
if d := t.Sub(now); d > 0 {
return d
}
return 0
}
}
return backoff(attempt, 60)
}
@@ -0,0 +1,118 @@
package transport
import (
"context"
"net/http"
"sync"
"testing"
"time"
)
// fakeClock drives the throttle without real waiting.
type fakeClock struct {
mu sync.Mutex
t time.Time
slept time.Duration
}
func (c *fakeClock) now() time.Time {
c.mu.Lock()
defer c.mu.Unlock()
return c.t
}
func (c *fakeClock) sleep(_ context.Context, d time.Duration) error {
c.mu.Lock()
defer c.mu.Unlock()
c.t = c.t.Add(d)
c.slept += d
return nil
}
func newFakeThrottle() (*throttle, *fakeClock) {
clk := &fakeClock{t: time.Date(2026, 10, 14, 3, 0, 0, 0, time.UTC)}
th := newThrottle(quietLogger())
th.now = clk.now
return th, clk
}
func TestThrottleUnthrottledByDefault(t *testing.T) {
th, clk := newFakeThrottle()
for i := 0; i < 5; i++ {
if err := th.acquire(context.Background(), clk.sleep); err != nil {
t.Fatal(err)
}
}
if clk.slept != 0 {
t.Errorf("slept %s without any 429, want 0", clk.slept)
}
}
func TestThrottleRateLimitPausesAndSpacesRequests(t *testing.T) {
th, clk := newFakeThrottle()
th.rateLimited(5 * time.Second)
if th.interval != minInterval {
t.Fatalf("interval = %s, want %s", th.interval, minInterval)
}
_ = th.acquire(context.Background(), clk.sleep) // waits out the pause
_ = th.acquire(context.Background(), clk.sleep) // then one interval later
if want := 5*time.Second + minInterval; clk.slept != want {
t.Errorf("slept %s, want %s", clk.slept, want)
}
}
func TestThrottleConcurrent429sCountOnce(t *testing.T) {
th, _ := newFakeThrottle()
th.rateLimited(time.Second)
th.rateLimited(time.Second)
th.rateLimited(2 * time.Second)
if th.interval != minInterval {
t.Errorf("interval = %s, want %s (one slowdown per burst)", th.interval, minInterval)
}
if want := th.now().Add(2 * time.Second); !th.pauseUntil.Equal(want) {
t.Errorf("pauseUntil = %s, want the longest Retry-After %s", th.pauseUntil, want)
}
}
func TestThrottleBacksOffAndRecovers(t *testing.T) {
th, clk := newFakeThrottle()
for i := 0; i < 20; i++ {
th.rateLimited(0)
_ = clk.sleep(context.Background(), time.Millisecond) // next 429 arrives after the (zero) pause
}
if th.interval != maxInterval {
t.Fatalf("interval = %s, want capped at %s", th.interval, maxInterval)
}
for i := 0; i < 1000 && th.interval > 0; i++ {
th.succeeded()
}
if th.interval != 0 {
t.Errorf("interval = %s after many successes, want 0", th.interval)
}
}
func TestThrottleRespectsCancel(t *testing.T) {
th, _ := newFakeThrottle()
th.rateLimited(time.Hour)
ctx, cancel := context.WithCancel(context.Background())
cancel()
if err := th.acquire(ctx, sleepCtx); err == nil {
t.Error("acquire must return the context error")
}
}
func TestRetryAfter(t *testing.T) {
now := time.Date(2026, 10, 14, 3, 0, 0, 0, time.UTC)
h := http.Header{}
h.Set("Retry-After", "7")
if got := retryAfter(h, 1, now); got != 7*time.Second {
t.Errorf("seconds: got %s", got)
}
h.Set("Retry-After", now.Add(30*time.Second).Format(http.TimeFormat))
if got := retryAfter(h, 1, now); got != 30*time.Second {
t.Errorf("http date: got %s", got)
}
if got := retryAfter(http.Header{}, 2, now); got != 4*time.Second {
t.Errorf("fallback backoff: got %s", got)
}
}
+340
View File
@@ -0,0 +1,340 @@
// Package transport is the HTTP client behind atlassian/jira and
// atlassian/confluence: authentication, TLS/proxy setup, redirect
// hardening, retry with exponential backoff on 5xx and connection errors,
// 429 handling through a shared adaptive throttle that honours
// Retry-After, a fixed pause after every response, startAt/maxResults
// pagination and streamed file downloads. It knows nothing about Jira or
// Confluence payloads.
//
// It merges the three clients that existed before (yabaratla's and
// yareco's internal/jira, yamcp's atlassian/httpclient); see the
// repository's README for which behaviour came from where.
package transport
import (
"bytes"
"context"
"crypto/tls"
"crypto/x509"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"time"
"yetano.dev/yetano/yetano-clients/atlassian"
)
// retryableStatus lists transient HTTP status codes worth retrying.
var retryableStatus = map[int]bool{500: true, 502: true, 503: true, 504: true}
// Client is safe for concurrent use; all goroutines share one throttle.
type Client struct {
http *http.Client
download *http.Client
baseURL string
auth atlassian.Auth
maxRetries int
retry429 bool
apiDelay time.Duration
maxBody int64
throttle *throttle
log *slog.Logger
sleep func(ctx context.Context, d time.Duration) error
}
// New builds a Client. It fails only on a bad CA file or proxy URL; it
// never sends a request.
func New(o atlassian.Options) (*Client, error) {
tlsConfig := &tls.Config{InsecureSkipVerify: o.TLS.InsecureSkipVerify} //nolint:gosec // explicit, caller-controlled opt-in
if o.TLS.CAFile != "" {
pemData, err := os.ReadFile(o.TLS.CAFile)
if err != nil {
return nil, fmt.Errorf("%w: reading CA file %s: %w", atlassian.ErrTLSConfig, o.TLS.CAFile, err)
}
pool := x509.NewCertPool()
if !pool.AppendCertsFromPEM(pemData) {
return nil, fmt.Errorf("%w: CA file %s contains no valid PEM certificates", atlassian.ErrTLSConfig, o.TLS.CAFile)
}
tlsConfig.RootCAs = pool
}
transport := http.DefaultTransport.(*http.Transport).Clone()
transport.TLSClientConfig = tlsConfig
if o.ProxyURL != "" {
proxyURL, err := url.Parse(o.ProxyURL)
if err != nil {
return nil, fmt.Errorf("parsing proxy URL: %w", err)
}
transport.Proxy = http.ProxyURL(proxyURL)
}
if o.MaxRetries < 1 {
o.MaxRetries = 1
}
if o.Logger == nil {
o.Logger = slog.Default()
}
base := strings.TrimRight(o.BaseURL, "/")
return &Client{
http: &http.Client{Transport: transport, Timeout: o.Timeout, CheckRedirect: checkRedirect},
download: &http.Client{Transport: transport, Timeout: o.DownloadTimeout, CheckRedirect: checkRedirect},
baseURL: base,
auth: o.Auth,
maxRetries: o.MaxRetries,
retry429: !o.DisableRateLimitRetry,
apiDelay: o.APIDelay,
maxBody: o.MaxResponseBytes,
throttle: newThrottle(o.Logger),
log: o.Logger,
sleep: sleepCtx,
}, nil
}
// checkRedirect drops credentials on any redirect to another host, so a
// misconfigured or malicious redirect can never carry them to a third
// party (net/http alone keeps them for subdomains). Same-host redirects,
// e.g. http -> https, keep them.
func checkRedirect(req *http.Request, via []*http.Request) error {
if len(via) >= 10 {
return errors.New("stopped after 10 redirects")
}
if req.URL.Host != via[0].URL.Host {
req.Header.Del("Authorization")
req.Header.Del("Cookie")
}
return nil
}
// SetSleep replaces the wait function (backoff, Retry-After, throttle,
// APIDelay) -- for tests that must not really wait.
func (c *Client) SetSleep(f func(ctx context.Context, d time.Duration) error) { c.sleep = f }
// BaseURL is the site root without trailing slash.
func (c *Client) BaseURL() string { return c.baseURL }
// HasCredentials reports whether any credentials are configured.
func (c *Client) HasCredentials() bool { return c.auth.IsSet() }
// Close releases idle connections.
func (c *Client) Close() {
c.http.CloseIdleConnections()
c.download.CloseIdleConnections()
}
// Do executes one logical request against BaseURL+path and returns the
// JSON response body ("{}" for an empty one). body, if non-nil, is sent
// as JSON.
func (c *Client) Do(ctx context.Context, method, path string, query url.Values, body any) (json.RawMessage, error) {
fullURL := c.baseURL + path
if len(query) > 0 {
fullURL += "?" + query.Encode()
}
var bodyBytes []byte
if body != nil {
b, err := json.Marshal(body)
if err != nil {
return nil, fmt.Errorf("%w: encoding request body: %v", atlassian.ErrInvalidArgument, err)
}
bodyBytes = b
}
var lastErr error
rateLimited := 0
for attempt := 1; attempt <= c.maxRetries; attempt++ {
var reader io.Reader
if bodyBytes != nil {
reader = bytes.NewReader(bodyBytes)
}
req, err := http.NewRequestWithContext(ctx, method, fullURL, reader)
if err != nil {
return nil, fmt.Errorf("%w: %v", atlassian.ErrInvalidArgument, err)
}
req.Header.Set("Accept", "application/json")
if bodyBytes != nil {
req.Header.Set("Content-Type", "application/json")
}
c.auth.Apply(req)
if err := c.throttle.acquire(ctx, c.sleep); err != nil {
return nil, err
}
resp, err := c.http.Do(req)
if err != nil {
if ctx.Err() != nil {
return nil, ctx.Err()
}
lastErr = fmt.Errorf("%s %s: %w", method, path, err)
if attempt == c.maxRetries {
return nil, lastErr
}
c.log.Warn("atlassian connection error, retrying", "attempt", attempt, "max", c.maxRetries, "method", method, "path", path, "err", err)
if err := c.sleep(ctx, backoff(attempt, 30)); err != nil {
return nil, err
}
continue
}
data, readErr := c.readBody(resp.Body)
resp.Body.Close()
if errors.Is(readErr, atlassian.ErrResponseTooLarge) {
return nil, fmt.Errorf("%s %s: %w (limit %d bytes)", method, path, readErr, c.maxBody)
}
if err := c.sleep(ctx, c.apiDelay); err != nil {
return nil, err
}
if readErr != nil {
lastErr = fmt.Errorf("%s %s: reading response: %w", method, path, readErr)
if attempt == c.maxRetries {
return nil, lastErr
}
if err := c.sleep(ctx, backoff(attempt, 30)); err != nil {
return nil, err
}
continue
}
switch {
case resp.StatusCode >= 200 && resp.StatusCode < 300:
c.throttle.succeeded()
if len(bytes.TrimSpace(data)) == 0 {
return json.RawMessage("{}"), nil
}
if !json.Valid(data) {
return nil, fmt.Errorf("%s %s: HTTP %d, Content-Type %q: %w", method, path, resp.StatusCode, resp.Header.Get("Content-Type"), atlassian.ErrNotJSON)
}
return json.RawMessage(data), nil
case resp.StatusCode == http.StatusTooManyRequests && c.retry429:
// Being throttled is not a failure: it doesn't use up
// MaxRetries, only the separate maxRateLimitRetries budget.
rateLimited++
if rateLimited > maxRateLimitRetries {
return nil, &atlassian.APIError{StatusCode: resp.StatusCode, Method: method, Path: path, Body: fmt.Sprintf("still rate limited after %d retries", maxRateLimitRetries)}
}
c.throttle.rateLimited(retryAfter(resp.Header, rateLimited, time.Now()))
attempt--
continue
case retryableStatus[resp.StatusCode]:
lastErr = &atlassian.APIError{StatusCode: resp.StatusCode, Method: method, Path: path, Body: string(data)}
if attempt == c.maxRetries {
return nil, lastErr
}
c.log.Warn("atlassian server error, retrying", "attempt", attempt, "max", c.maxRetries, "method", method, "path", path, "status", resp.StatusCode)
if err := c.sleep(ctx, backoff(attempt, 30)); err != nil {
return nil, err
}
continue
default:
return nil, &atlassian.APIError{StatusCode: resp.StatusCode, Method: method, Path: path, Body: string(data)}
}
}
if lastErr != nil {
return nil, lastErr
}
return nil, fmt.Errorf("%s %s: max retries exceeded", method, path)
}
func (c *Client) readBody(r io.Reader) ([]byte, error) {
if c.maxBody <= 0 {
return io.ReadAll(r)
}
data, err := io.ReadAll(io.LimitReader(r, c.maxBody+1))
if err != nil {
return nil, err
}
if int64(len(data)) > c.maxBody {
return nil, atlassian.ErrResponseTooLarge
}
return data, nil
}
// backoff returns min(2^attempt, capSeconds) seconds.
func backoff(attempt, capSeconds int) time.Duration {
d := time.Duration(1) << uint(attempt) * time.Second
if limit := time.Duration(capSeconds) * time.Second; d > limit {
d = limit
}
return d
}
func sleepCtx(ctx context.Context, d time.Duration) error {
if d <= 0 {
return ctx.Err()
}
t := time.NewTimer(d)
defer t.Stop()
select {
case <-ctx.Done():
return ctx.Err()
case <-t.C:
return nil
}
}
// Paginate walks a classic startAt/maxResults/{isLast|total} listing and
// returns every element of the itemsKey array ("values" for most
// endpoints, "comments" for issue comments) across all pages. It advances
// by the number of items actually returned, because Jira may cap
// maxResults below what was asked for.
func (c *Client) Paginate(ctx context.Context, path string, params url.Values, itemsKey string, pageSize int) ([]json.RawMessage, error) {
var all []json.RawMessage
start := 0
for {
p := CloneValues(params)
p.Set("startAt", strconv.Itoa(start))
p.Set("maxResults", strconv.Itoa(pageSize))
raw, err := c.Do(ctx, http.MethodGet, path, p, nil)
if err != nil {
return all, err
}
var page map[string]json.RawMessage
if err := json.Unmarshal(raw, &page); err != nil {
return all, fmt.Errorf("GET %s: %w", path, err)
}
var items []json.RawMessage
if v, ok := page[itemsKey]; ok {
if err := json.Unmarshal(v, &items); err != nil {
return all, fmt.Errorf("GET %s: %s: %w", path, itemsKey, err)
}
}
all = append(all, items...)
var isLast *bool
var total *int
if v, ok := page["isLast"]; ok {
_ = json.Unmarshal(v, &isLast)
}
if v, ok := page["total"]; ok {
_ = json.Unmarshal(v, &total)
}
if isLast != nil && *isLast {
return all, nil
}
start += len(items)
if (total != nil && start >= *total) || len(items) == 0 {
return all, nil
}
}
}
// CloneValues deep-copies v (nil gives an empty map).
func CloneValues(v url.Values) url.Values {
out := url.Values{}
for k, vs := range v {
out[k] = append([]string(nil), vs...)
}
return out
}
@@ -0,0 +1,403 @@
package transport
import (
"context"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"yetano.dev/yetano/yetano-clients/atlassian"
)
func quietLogger() *slog.Logger { return slog.New(slog.NewTextHandler(io.Discard, nil)) }
// testClient starts h and returns a client against it that records
// (instead of doing) every wait.
func testClient(t *testing.T, h http.HandlerFunc, mod func(*atlassian.Options)) (*Client, *[]time.Duration) {
t.Helper()
srv := httptest.NewServer(h)
t.Cleanup(srv.Close)
o := atlassian.Options{BaseURL: srv.URL + "/", MaxRetries: 3, Logger: quietLogger(),
Auth: atlassian.Auth{Type: atlassian.AuthAPIToken, Username: "e@example.com", Password: "secret-token"}}
if mod != nil {
mod(&o)
}
c, err := New(o)
if err != nil {
t.Fatal(err)
}
var mu sync.Mutex
var slept []time.Duration
c.SetSleep(func(ctx context.Context, d time.Duration) error {
if d > 0 {
mu.Lock()
slept = append(slept, d)
mu.Unlock()
}
return ctx.Err()
})
return c, &slept
}
func get(c *Client, path string) error {
_, err := c.Do(context.Background(), http.MethodGet, path, nil, nil)
return err
}
func TestRetryOn5xxThenSuccess(t *testing.T) {
var calls atomic.Int32
c, slept := testClient(t, func(w http.ResponseWriter, r *http.Request) {
if calls.Add(1) < 3 {
w.WriteHeader(http.StatusBadGateway)
return
}
fmt.Fprint(w, `{"displayName":"Ada"}`)
}, nil)
raw, err := c.Do(context.Background(), http.MethodGet, "/rest/api/3/myself", nil, nil)
if err != nil || !strings.Contains(string(raw), "Ada") || calls.Load() != 3 {
t.Fatalf("got %s, %v after %d calls", raw, err, calls.Load())
}
if len(*slept) != 2 || (*slept)[0] != 2*time.Second || (*slept)[1] != 4*time.Second {
t.Errorf("backoff = %v, want [2s 4s]", *slept)
}
}
func TestRetryExhaustedReturnsAPIError(t *testing.T) {
c, _ := testClient(t, func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusServiceUnavailable)
fmt.Fprint(w, "down")
}, nil)
err := get(c, "/x")
if atlassian.StatusOf(err) != http.StatusServiceUnavailable {
t.Fatalf("err = %v, want APIError 503", err)
}
}
func TestStatusHandling(t *testing.T) {
cases := []struct {
status int
body string
wantErr bool
want string
}{
{200, `{"a":1}`, false, `{"a":1}`},
{201, `{"id":"1"}`, false, `{"id":"1"}`},
{204, ``, false, `{}`},
{200, ``, false, `{}`},
{200, `<html>login</html>`, true, ""},
{400, `{"errorMessages":["bad jql"]}`, true, ""},
{404, ``, true, ""},
}
for _, tc := range cases {
var calls atomic.Int32
c, _ := testClient(t, func(w http.ResponseWriter, r *http.Request) {
calls.Add(1)
w.WriteHeader(tc.status)
fmt.Fprint(w, tc.body)
}, nil)
raw, err := c.Do(context.Background(), http.MethodGet, "/x", nil, nil)
if (err != nil) != tc.wantErr || (!tc.wantErr && string(raw) != tc.want) {
t.Errorf("HTTP %d %q: got %s, %v", tc.status, tc.body, raw, err)
}
if tc.status >= 400 && calls.Load() != 1 {
t.Errorf("HTTP %d retried %d times", tc.status, calls.Load())
}
}
}
func TestNonJSONSuccessIsAnError(t *testing.T) {
c, _ := testClient(t, func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
fmt.Fprint(w, "<html>SSO</html>")
}, nil)
if err := get(c, "/x"); !errors.Is(err, atlassian.ErrNotJSON) {
t.Fatalf("err = %v, want ErrNotJSON", err)
}
}
func TestAPIErrorMessage(t *testing.T) {
cases := map[string]string{
`{"errorMessages":["Issue does not exist"]}`: "Issue does not exist",
`{"message":"No space"}`: "No space",
`{"errors":{"summary":"required"}}`: "summary: required",
``: "no additional detail from upstream",
`plain text`: "plain text",
}
for body, want := range cases {
if got := (&atlassian.APIError{StatusCode: 400, Body: body}).Message(); got != want {
t.Errorf("Message(%q) = %q, want %q", body, got, want)
}
}
}
func TestRateLimitDoesNotUseRetriesAndHonoursRetryAfter(t *testing.T) {
var calls atomic.Int32
c, slept := testClient(t, func(w http.ResponseWriter, r *http.Request) {
// four 429s in a row -- more than MaxRetries (3)
if calls.Add(1) <= 4 {
w.Header().Set("Retry-After", "7")
w.WriteHeader(http.StatusTooManyRequests)
return
}
fmt.Fprint(w, `{}`)
}, nil)
if err := get(c, "/x"); err != nil {
t.Fatalf("429s must not exhaust MaxRetries: %v", err)
}
if calls.Load() != 5 || len(*slept) == 0 || (*slept)[0] < 6*time.Second {
t.Errorf("calls = %d, waits = %v; want 5 calls, first wait about 7s (Retry-After)", calls.Load(), *slept)
}
}
func TestRateLimitBudget(t *testing.T) {
var calls atomic.Int32
c, _ := testClient(t, func(w http.ResponseWriter, r *http.Request) {
calls.Add(1)
w.Header().Set("Retry-After", "0")
w.WriteHeader(http.StatusTooManyRequests)
}, nil)
if err := get(c, "/x"); atlassian.StatusOf(err) != 429 {
t.Fatalf("err = %v, want 429 after the budget", err)
}
if got := calls.Load(); got != maxRateLimitRetries+1 {
t.Errorf("calls = %d, want %d", got, maxRateLimitRetries+1)
}
}
func TestDisableRateLimitRetry(t *testing.T) {
var calls atomic.Int32
c, _ := testClient(t, func(w http.ResponseWriter, r *http.Request) {
calls.Add(1)
w.WriteHeader(http.StatusTooManyRequests)
}, func(o *atlassian.Options) { o.DisableRateLimitRetry = true })
if err := get(c, "/x"); atlassian.StatusOf(err) != 429 || calls.Load() != 1 {
t.Fatalf("err = %v after %d calls, want one 429", err, calls.Load())
}
}
func TestAuthApplied(t *testing.T) {
cases := []struct {
name string
auth atlassian.Auth
check func(r *http.Request) bool
}{
{"api token", atlassian.Auth{Type: atlassian.AuthAPIToken, Username: "e@x", Password: "tok"}, func(r *http.Request) bool {
u, p, ok := r.BasicAuth()
return ok && u == "e@x" && p == "tok"
}},
{"basic", atlassian.Auth{Type: atlassian.AuthBasic, Username: "u", Password: "p"}, func(r *http.Request) bool {
u, p, ok := r.BasicAuth()
return ok && u == "u" && p == "p"
}},
{"pat", atlassian.Auth{Type: atlassian.AuthPAT, Token: "pat"}, func(r *http.Request) bool {
return r.Header.Get("Authorization") == "Bearer pat"
}},
{"bearer", atlassian.Auth{Type: atlassian.AuthBearer, Token: "b"}, func(r *http.Request) bool {
return r.Header.Get("Authorization") == "Bearer b"
}},
{"cookie", atlassian.Auth{Type: atlassian.AuthCookie, Cookie: "s=1"}, func(r *http.Request) bool {
return r.Header.Get("Cookie") == "s=1" && r.Header.Get("Authorization") == ""
}},
{"auto prefers basic over cookie", atlassian.Auth{Username: "u", Password: "p", Cookie: "s=1"}, func(r *http.Request) bool {
_, _, ok := r.BasicAuth()
return ok && r.Header.Get("Cookie") == ""
}},
{"api token without e-mail sends nothing", atlassian.Auth{Type: atlassian.AuthAPIToken, Password: "tok"}, func(r *http.Request) bool {
return r.Header.Get("Authorization") == ""
}},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
c, _ := testClient(t, func(w http.ResponseWriter, r *http.Request) {
if !tc.check(r) {
t.Errorf("headers = %v", r.Header)
}
fmt.Fprint(w, `{}`)
}, func(o *atlassian.Options) { o.Auth = tc.auth })
if err := get(c, "/x"); err != nil {
t.Fatal(err)
}
})
}
}
func TestCrossHostRedirectDropsCredentials(t *testing.T) {
other := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Authorization") != "" || r.Header.Get("Cookie") != "" {
t.Error("credentials followed a cross-host redirect")
}
fmt.Fprint(w, `{}`)
}))
defer other.Close()
c, _ := testClient(t, func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, other.URL+"/elsewhere", http.StatusFound)
}, nil)
if err := get(c, "/x"); err != nil {
t.Fatal(err)
}
}
func TestNewRejectsBadCAFile(t *testing.T) {
bad := filepath.Join(t.TempDir(), "ca.pem")
if err := os.WriteFile(bad, []byte("not a certificate"), 0o600); err != nil {
t.Fatal(err)
}
for _, f := range []string{bad, filepath.Join(t.TempDir(), "missing.pem")} {
if _, err := New(atlassian.Options{TLS: atlassian.TLS{CAFile: f}}); !errors.Is(err, atlassian.ErrTLSConfig) {
t.Errorf("CA file %s: err = %v, want ErrTLSConfig", f, err)
}
}
if _, err := New(atlassian.Options{ProxyURL: "://bad"}); err == nil {
t.Error("bad proxy URL must be an error")
}
}
func TestMaxResponseBytes(t *testing.T) {
c, _ := testClient(t, func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"a":"`+strings.Repeat("x", 100)+`"}`)
}, func(o *atlassian.Options) { o.MaxResponseBytes = 50 })
if err := get(c, "/x"); !errors.Is(err, atlassian.ErrResponseTooLarge) {
t.Fatalf("err = %v, want ErrResponseTooLarge", err)
}
}
func TestTokenNeverInError(t *testing.T) {
c, _ := testClient(t, func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusUnauthorized)
}, nil)
err := get(c, "/x")
if atlassian.StatusOf(err) != 401 || strings.Contains(err.Error(), "secret-token") {
t.Fatalf("err = %v", err)
}
}
func TestContextCancelStopsBackoff(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
}))
defer srv.Close()
c, err := New(atlassian.Options{BaseURL: srv.URL, MaxRetries: 5, Logger: quietLogger()})
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
defer cancel()
start := time.Now()
_, err = c.Do(ctx, http.MethodGet, "/x", nil, nil)
if !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("err = %v, want deadline exceeded", err)
}
if time.Since(start) > 2*time.Second {
t.Errorf("backoff ignored the context: %s", time.Since(start))
}
}
func TestPaginateAdvancesByItemsReturned(t *testing.T) {
var starts []string
c, _ := testClient(t, func(w http.ResponseWriter, r *http.Request) {
start := r.URL.Query().Get("startAt")
starts = append(starts, start)
switch start {
case "0":
fmt.Fprint(w, `{"total":3,"values":[{"key":"A"},{"key":"B"}]}`) // server capped at 2
case "2":
fmt.Fprint(w, `{"total":3,"values":[{"key":"C"}]}`)
default:
t.Errorf("unexpected startAt %s", start)
}
}, nil)
items, err := c.Paginate(context.Background(), "/x", nil, "values", 50)
if err != nil || len(items) != 3 {
t.Fatalf("items = %d, err = %v", len(items), err)
}
if strings.Join(starts, ",") != "0,2" {
t.Errorf("startAt sequence = %v", starts)
}
}
func TestPaginateStopsOnIsLast(t *testing.T) {
var calls atomic.Int32
c, _ := testClient(t, func(w http.ResponseWriter, r *http.Request) {
if calls.Add(1) == 1 {
fmt.Fprint(w, `{"isLast":false,"values":[{"id":"1"}]}`)
return
}
fmt.Fprint(w, `{"isLast":true,"values":[{"id":"2"}]}`)
}, nil)
items, err := c.Paginate(context.Background(), "/x", nil, "values", 1)
if err != nil || len(items) != 2 || calls.Load() != 2 {
t.Fatalf("items = %d after %d calls, err = %v", len(items), calls.Load(), err)
}
}
func TestDownloadFile(t *testing.T) {
var calls atomic.Int32
c, _ := testClient(t, func(w http.ResponseWriter, r *http.Request) {
switch calls.Add(1) {
case 1:
w.Header().Set("Retry-After", "0")
w.WriteHeader(http.StatusTooManyRequests)
case 2:
w.WriteHeader(http.StatusBadGateway)
default:
if _, _, ok := r.BasicAuth(); !ok {
t.Error("same-host download without credentials")
}
fmt.Fprint(w, "payload")
}
}, func(o *atlassian.Options) { o.MaxRetries = 2 })
dest := filepath.Join(t.TempDir(), "sub", "f")
if err := c.DownloadFile(context.Background(), "/att/1", dest); err != nil {
t.Fatal(err)
}
if b, _ := os.ReadFile(dest); string(b) != "payload" {
t.Errorf("downloaded %q", b)
}
}
func TestDownloadFileRedirectToOtherHostDropsCredentials(t *testing.T) {
other := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Authorization") != "" {
t.Error("credentials followed a redirect to a foreign host")
}
fmt.Fprint(w, "x")
}))
defer other.Close()
c, _ := testClient(t, func(w http.ResponseWriter, r *http.Request) {
if _, _, ok := r.BasicAuth(); !ok {
t.Error("site request without credentials")
}
http.Redirect(w, r, other.URL+"/media?token=s", http.StatusFound)
}, nil)
dest := filepath.Join(t.TempDir(), "f")
if err := c.DownloadFile(context.Background(), "/rest/api/3/attachment/content/1", dest); err != nil {
t.Fatal(err)
}
if b, _ := os.ReadFile(dest); string(b) != "x" {
t.Errorf("downloaded %q", b)
}
}
func TestDownloadFileFailureRemovesPartial(t *testing.T) {
c, _ := testClient(t, func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
}, nil)
dest := filepath.Join(t.TempDir(), "f")
err := c.DownloadFile(context.Background(), "/att/1?sig=secret", dest)
if err == nil || strings.Contains(err.Error(), "secret") {
t.Fatalf("err = %v (want an error without the query)", err)
}
if _, statErr := os.Stat(dest); !os.IsNotExist(statErr) {
t.Error("partial file left behind")
}
}
+137
View File
@@ -0,0 +1,137 @@
// Package jira is a Jira REST API client for Atlassian Cloud (REST API
// v3, Atlassian Document Format bodies) and Server/Data Center (REST API
// v2, plain-text/wiki-markup bodies).
//
// It offers typed calls for what the yetano programs use (projects,
// versions, fields, JQL search, issues, comments, changelog, edit
// metadata, transitions, issue writes) and the raw Get/Post/Put/Delete/
// Paginate/DownloadFile underneath for everything else (the Agile API,
// worklogs, attachments, ...). Every call takes a context; retries,
// rate-limit handling and authentication are described on
// atlassian.Options.
package jira
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
"time"
"yetano.dev/yetano/yetano-clients/atlassian"
"yetano.dev/yetano/yetano-clients/atlassian/internal/transport"
)
// Client is a Jira client. It is safe for concurrent use.
type Client struct {
t *transport.Client
cloud bool
}
// New builds a Client. It sends no request; a bad TLS CA file or proxy
// URL is the only error.
func New(o atlassian.Options) (*Client, error) {
t, err := transport.New(o)
if err != nil {
return nil, err
}
return &Client{t: t, cloud: o.Deployment.IsCloud()}, nil
}
// BaseURL is the site root without trailing slash.
func (c *Client) BaseURL() string { return c.t.BaseURL() }
// HasCredentials reports whether any credentials are configured.
func (c *Client) HasCredentials() bool { return c.t.HasCredentials() }
// IsCloud reports whether the client talks to Atlassian Cloud.
func (c *Client) IsCloud() bool { return c.cloud }
// APIPrefix is /rest/api/3 on Cloud and /rest/api/2 on Server/Data
// Center.
func (c *Client) APIPrefix() string {
if c.cloud {
return "/rest/api/3"
}
return "/rest/api/2"
}
func (c *Client) api(suffix string) string { return c.APIPrefix() + suffix }
// IssueURL is the browser URL of an issue.
func (c *Client) IssueURL(key string) string {
return fmt.Sprintf("%s/browse/%s", c.BaseURL(), key)
}
// Close releases idle connections.
func (c *Client) Close() { c.t.Close() }
// SetSleep replaces every wait (backoff, Retry-After, throttle,
// APIDelay) -- for tests that must not really wait.
func (c *Client) SetSleep(f func(ctx context.Context, d time.Duration) error) { c.t.SetSleep(f) }
// Get issues a GET against BaseURL+path and returns the JSON body.
func (c *Client) Get(ctx context.Context, path string, params url.Values) (json.RawMessage, error) {
return c.t.Do(ctx, http.MethodGet, path, params, nil)
}
// Post issues a POST with a JSON body.
func (c *Client) Post(ctx context.Context, path string, body any) (json.RawMessage, error) {
return c.t.Do(ctx, http.MethodPost, path, nil, body)
}
// Put issues a PUT with a JSON body.
func (c *Client) Put(ctx context.Context, path string, body any) (json.RawMessage, error) {
return c.t.Do(ctx, http.MethodPut, path, nil, body)
}
// Delete issues a DELETE.
func (c *Client) Delete(ctx context.Context, path string, params url.Values) (json.RawMessage, error) {
return c.t.Do(ctx, http.MethodDelete, path, params, nil)
}
// Paginate walks a startAt/maxResults listing and returns every element
// of the itemsKey array ("values" for most endpoints, "comments" for
// issue comments) across all pages.
func (c *Client) Paginate(ctx context.Context, path string, params url.Values, itemsKey string, pageSize int) ([]json.RawMessage, error) {
return c.t.Paginate(ctx, path, params, itemsKey, pageSize)
}
// DownloadFile streams fileURL (absolute, or a path starting with "/")
// to dest, retrying and removing partial files; see
// atlassian.Options.DownloadTimeout. Credentials are not sent along a
// redirect to another host.
func (c *Client) DownloadFile(ctx context.Context, fileURL, dest string) error {
return c.t.DownloadFile(ctx, fileURL, dest)
}
func decodeAll[T any](raw []json.RawMessage) ([]T, error) {
out := make([]T, 0, len(raw))
for _, r := range raw {
var v T
if err := json.Unmarshal(r, &v); err != nil {
return nil, err
}
out = append(out, v)
}
return out, nil
}
func (c *Client) getInto(ctx context.Context, path string, params url.Values, out any) error {
raw, err := c.Get(ctx, path, params)
if err != nil {
return err
}
if err := json.Unmarshal(raw, out); err != nil {
return fmt.Errorf("GET %s: decoding response: %w", path, err)
}
return nil
}
func requireKey(what, v string) error {
if v == "" {
return fmt.Errorf("%w: %s must not be empty", atlassian.ErrInvalidArgument, what)
}
return nil
}
+143
View File
@@ -0,0 +1,143 @@
package jira
import (
"encoding/json"
"fmt"
"regexp"
"strings"
)
// Names returns the names of a list of Named/Version values.
func Names[T Named | Version](items []T) []string {
out := make([]string, 0, len(items))
for _, it := range items {
switch v := any(it).(type) {
case Named:
out = append(out, v.Name)
case Version:
out = append(out, v.Name)
}
}
return out
}
// OptionValues reads a select/multi-select/label-like field value as a
// list of strings: null, a string, a list of strings, an option object
// {"value": ...} (or {"name": ...}) or a list of those. A value of any
// other shape is an error, never silently empty -- a field mapped to the
// wrong field ID must be noticed.
func OptionValues(raw json.RawMessage) ([]string, error) {
s := strings.TrimSpace(string(raw))
if len(raw) == 0 || s == "null" {
return nil, nil
}
var str string
if json.Unmarshal(raw, &str) == nil {
return nonEmpty(str), nil
}
if strings.HasPrefix(s, "{") {
var opt struct {
Value *string `json:"value"`
Name *string `json:"name"`
}
if err := json.Unmarshal(raw, &opt); err != nil {
return nil, err
}
switch {
case opt.Value != nil:
return nonEmpty(*opt.Value), nil
case opt.Name != nil:
return nonEmpty(*opt.Name), nil
}
return nil, fmt.Errorf("unexpected field value %s", abbreviate(s))
}
var list []json.RawMessage
if err := json.Unmarshal(raw, &list); err != nil {
return nil, fmt.Errorf("unexpected field value %s", abbreviate(s))
}
var out []string
for _, item := range list {
vals, err := OptionValues(item)
if err != nil {
return nil, err
}
out = append(out, vals...)
}
return out, nil
}
// Sprint is one entry of the Jira Software sprint field.
type Sprint struct {
Name string `json:"name"`
State string `json:"state"` // active, future or closed
}
var rxLegacySprint = regexp.MustCompile(`(?:^|[\[,])(state|name)=([^,\]]*)`)
// SprintValues reads the sprint field: null, a list of sprint objects
// (Cloud) or a list of the legacy
// "com.atlassian.greenhopper.service.sprint.Sprint@…[state=…,name=…]"
// strings (older Data Center). States are lower-cased. Like
// OptionValues, any other shape is an error, never silently "no sprint".
func SprintValues(raw json.RawMessage) ([]Sprint, error) {
s := strings.TrimSpace(string(raw))
if len(raw) == 0 || s == "null" {
return nil, nil
}
var list []json.RawMessage
if err := json.Unmarshal(raw, &list); err != nil {
return nil, fmt.Errorf("unexpected sprint value %s", abbreviate(s))
}
var out []Sprint
for _, item := range list {
var legacy string
if json.Unmarshal(item, &legacy) == nil {
var sp Sprint
for _, m := range rxLegacySprint.FindAllStringSubmatch(legacy, -1) {
if m[1] == "name" {
sp.Name = m[2]
} else {
sp.State = strings.ToLower(m[2])
}
}
if sp.Name == "" {
return nil, fmt.Errorf("unexpected sprint value %s", abbreviate(legacy))
}
out = append(out, sp)
continue
}
var sp Sprint
if err := json.Unmarshal(item, &sp); err != nil || sp.Name == "" {
return nil, fmt.Errorf("unexpected sprint value %s", abbreviate(string(item)))
}
sp.State = strings.ToLower(sp.State)
out = append(out, sp)
}
return out, nil
}
func nonEmpty(s string) []string {
if s = strings.TrimSpace(s); s == "" {
return nil
}
return []string{s}
}
func abbreviate(s string) string {
if len(s) > 80 {
return s[:80] + "…"
}
return s
}
var rxCustomField = regexp.MustCompile(`^customfield_(\d+)$`)
// CustomFieldNumber returns "11411" for "customfield_11411" (the cf[N]
// JQL form), ok=false for a system field.
func CustomFieldNumber(id string) (string, bool) {
m := rxCustomField.FindStringSubmatch(id)
if m == nil {
return "", false
}
return m[1], true
}
+358
View File
@@ -0,0 +1,358 @@
package jira
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"yetano.dev/yetano/yetano-clients/atlassian"
)
func newTestClient(t *testing.T, h http.HandlerFunc, dep atlassian.Deployment) *Client {
t.Helper()
srv := httptest.NewServer(h)
t.Cleanup(srv.Close)
c, err := New(atlassian.Options{BaseURL: srv.URL + "/", Deployment: dep, MaxRetries: 1,
Auth: atlassian.Auth{Type: atlassian.AuthAPIToken, Username: "e@example.com", Password: "t"},
Logger: slog.New(slog.NewTextHandler(io.Discard, nil))})
if err != nil {
t.Fatal(err)
}
c.SetSleep(func(ctx context.Context, _ time.Duration) error { return ctx.Err() })
return c
}
func TestAPIPrefixByDeployment(t *testing.T) {
noop := func(http.ResponseWriter, *http.Request) {}
if p := newTestClient(t, noop, "").APIPrefix(); p != "/rest/api/3" {
t.Errorf("zero deployment prefix = %q, want Cloud's /rest/api/3", p)
}
if p := newTestClient(t, noop, atlassian.DataCenter).APIPrefix(); p != "/rest/api/2" {
t.Errorf("datacenter prefix = %q", p)
}
}
func TestSearchCloudFollowsNextPageToken(t *testing.T) {
var bodies []map[string]any
c := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost || r.URL.Path != "/rest/api/3/search/jql" {
t.Errorf("unexpected %s %s", r.Method, r.URL.Path)
}
var body map[string]any
_ = json.NewDecoder(r.Body).Decode(&body)
bodies = append(bodies, body)
if body["nextPageToken"] == nil {
fmt.Fprint(w, `{"issues":[{"key":"DEV-1","fields":{"summary":"a","customfield_1":[{"value":"PI28.15"}]}}],"nextPageToken":"p2"}`)
return
}
fmt.Fprint(w, `{"issues":[{"key":"DEV-2","fields":{"summary":"b"}}],"isLast":true}`)
}, atlassian.Cloud)
issues, err := c.SearchAll(context.Background(), SearchQuery{JQL: "project = DEV", Fields: []string{"summary", "customfield_1"}, PageSize: 1})
if err != nil {
t.Fatal(err)
}
if len(issues) != 2 || issues[0].Key != "DEV-1" || issues[1].Key != "DEV-2" {
t.Fatalf("issues = %+v", issues)
}
if bodies[1]["nextPageToken"] != "p2" || bodies[0]["maxResults"].(float64) != 1 {
t.Errorf("request bodies = %v", bodies)
}
pis, err := OptionValues(issues[0].Fields.Raw["customfield_1"])
if err != nil || len(pis) != 1 || pis[0] != "PI28.15" {
t.Errorf("custom field = %v, %v", pis, err)
}
}
func TestSearchDataCenterUsesOffsets(t *testing.T) {
var starts []float64
c := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/rest/api/2/search" {
t.Errorf("unexpected path %s", r.URL.Path)
}
var body map[string]any
_ = json.NewDecoder(r.Body).Decode(&body)
start := body["startAt"].(float64)
starts = append(starts, start)
if exp, _ := body["expand"].([]any); len(exp) != 2 {
t.Errorf("expand = %v, want a list of 2", body["expand"])
}
fmt.Fprintf(w, `{"startAt":%v,"total":3,"issues":[{"key":"OPS-%v"},{"key":"OPS-x"}]}`, start, start)
}, atlassian.DataCenter)
issues, err := c.SearchAll(context.Background(), SearchQuery{JQL: "project = OPS", PageSize: 2, Expand: "renderedFields, changelog"})
if err != nil {
t.Fatal(err)
}
if len(issues) != 4 || len(starts) != 2 || starts[1] != 2 {
t.Errorf("issues = %d, starts = %v", len(issues), starts)
}
}
func TestSearchPageClassic(t *testing.T) {
c := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/rest/api/3/search" {
t.Errorf("unexpected path %s", r.URL.Path)
}
var body PageQuery
_ = json.NewDecoder(r.Body).Decode(&body)
if body.JQL != "project = OPS" || body.MaxResults != 25 || body.StartAt != 25 {
t.Errorf("body = %+v", body)
}
fmt.Fprint(w, `{"startAt":25,"maxResults":25,"total":100,"issues":[{"key":"OPS-1","fields":{"summary":"first"}}]}`)
}, atlassian.Cloud)
res, err := c.SearchPage(context.Background(), PageQuery{JQL: "project = OPS", StartAt: 25, MaxResults: 25})
if err != nil || res.Total != 100 || len(res.Issues) != 1 || res.Issues[0].Fields.Summary != "first" {
t.Fatalf("res = %+v, %v", res, err)
}
}
func TestEmptyArgumentsSendNothing(t *testing.T) {
c := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
t.Errorf("request sent: %s %s", r.Method, r.URL.Path)
}, atlassian.Cloud)
ctx := context.Background()
checks := map[string]error{}
_, checks["Issue"] = c.Issue(ctx, "", nil)
_, checks["Project"] = c.Project(ctx, "")
_, checks["SearchPage"] = c.SearchPage(ctx, PageQuery{})
checks["Search"] = c.Search(ctx, SearchQuery{JQL: " "}, func([]Issue) error { return nil })
checks["EditIssue"] = c.EditIssue(ctx, "", IssueEdit{})
for name, err := range checks {
if !errors.Is(err, atlassian.ErrInvalidArgument) {
t.Errorf("%s: err = %v, want ErrInvalidArgument", name, err)
}
}
}
func TestListProjectsPerDeployment(t *testing.T) {
var paths []string
cloud := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
paths = append(paths, r.URL.Path+"?"+r.URL.Query().Get("orderBy")+"@"+r.URL.Query().Get("startAt"))
if r.URL.Query().Get("startAt") == "0" {
fmt.Fprint(w, `{"isLast":false,"values":[{"id":"1","key":"DEV","name":"Development","projectTypeKey":"software"}]}`)
return
}
fmt.Fprint(w, `{"isLast":true,"values":[{"id":"2","key":"OPS","projectTypeKey":"service_desk"}]}`)
}, atlassian.Cloud)
got, err := cloud.ListProjects(context.Background())
if err != nil || len(got) != 2 || got[1].ProjectTypeKey != "service_desk" {
t.Fatalf("cloud projects = %+v, %v", got, err)
}
if strings.Join(paths, ",") != "/rest/api/3/project/search?key@0,/rest/api/3/project/search?key@1" {
t.Errorf("cloud requests = %v", paths)
}
dc := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/rest/api/2/project" {
t.Errorf("datacenter path = %s", r.URL.Path)
}
fmt.Fprint(w, `[{"key":"OPS"}]`)
}, atlassian.DataCenter)
if got, err := dc.ListProjects(context.Background()); err != nil || len(got) != 1 {
t.Fatalf("dc projects = %+v, %v", got, err)
}
}
func TestCommentsFromOffset(t *testing.T) {
c := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
if q.Get("startAt") != "2" || q.Get("orderBy") != "created" {
t.Errorf("query = %v", q)
}
fmt.Fprint(w, `{"total":3,"comments":[{"id":"3","created":"2026-05-01T10:00:00.000+0200"}]}`)
}, atlassian.Cloud)
cs, err := c.Comments(context.Background(), "DEV-1", 2)
if err != nil || len(cs) != 1 || cs[0].ID != "3" {
t.Fatalf("comments = %+v, %v", cs, err)
}
}
func TestEditIssueSendsOnlyNonEmptyParts(t *testing.T) {
var got []string
c := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
got = append(got, string(b))
w.WriteHeader(http.StatusNoContent)
}, atlassian.Cloud)
ctx := context.Background()
if err := c.EditIssue(ctx, "DEV-1", IssueEdit{Update: map[string][]map[string]any{"labels": {{"add": "x"}}}}); err != nil {
t.Fatal(err)
}
if err := c.UpdateIssue(ctx, "DEV-1", map[string]any{"summary": "s"}); err != nil {
t.Fatal(err)
}
if got[0] != `{"update":{"labels":[{"add":"x"}]}}` || got[1] != `{"fields":{"summary":"s"}}` {
t.Errorf("bodies = %v", got)
}
}
func TestWritesPerDeployment(t *testing.T) {
for _, dep := range []atlassian.Deployment{atlassian.Cloud, atlassian.DataCenter} {
var bodies = map[string]map[string]any{}
c := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
var body map[string]any
_ = json.NewDecoder(r.Body).Decode(&body)
bodies[r.Method+" "+r.URL.Path] = body
switch {
case strings.HasSuffix(r.URL.Path, "/comment"):
fmt.Fprint(w, `{"id":"77"}`)
case strings.HasSuffix(r.URL.Path, "/issue"):
fmt.Fprint(w, `{"id":"1","key":"OPS-9"}`)
default:
w.WriteHeader(http.StatusNoContent)
}
}, dep)
ctx := context.Background()
key, err := c.CreateIssue(ctx, CreateIssueInput{ProjectKey: "OPS", IssueType: "Task", Summary: "s", Description: "d", ParentKey: "OPS-1"})
if err != nil || key != "OPS-9" {
t.Fatalf("%s: create = %q, %v", dep, key, err)
}
id, err := c.AddComment(ctx, "OPS-9", "hello")
if err != nil || id != "77" {
t.Fatalf("%s: comment = %q, %v", dep, id, err)
}
if err := c.AssignIssue(ctx, "OPS-9", ""); err != nil {
t.Fatal(err)
}
if err := c.DoTransition(ctx, "OPS-9", "31"); err != nil {
t.Fatal(err)
}
if err := c.LinkIssues(ctx, "Blocks", "OPS-1", "OPS-9"); err != nil {
t.Fatal(err)
}
p := c.APIPrefix()
fields := bodies["POST "+p+"/issue"]["fields"].(map[string]any)
desc := fields["description"]
comment := bodies["POST "+p+"/issue/OPS-9/comment"]["body"]
assign := bodies["PUT "+p+"/issue/OPS-9/assignee"]
if dep == atlassian.Cloud {
if m, ok := desc.(map[string]any); !ok || m["type"] != "doc" {
t.Errorf("cloud description = %v, want ADF", desc)
}
if _, ok := comment.(map[string]any); !ok {
t.Errorf("cloud comment = %v, want ADF", comment)
}
if v, ok := assign["accountId"]; !ok || v != nil {
t.Errorf("cloud unassign = %v, want accountId null", assign)
}
} else {
if desc != "d" || comment != "hello" {
t.Errorf("dc description/comment = %v / %v, want plain strings", desc, comment)
}
if v, ok := assign["name"]; !ok || v != nil {
t.Errorf("dc unassign = %v, want name null", assign)
}
}
if fields["parent"].(map[string]any)["key"] != "OPS-1" {
t.Errorf("parent = %v", fields["parent"])
}
if tr := bodies["POST "+p+"/issue/OPS-9/transitions"]["transition"].(map[string]any); tr["id"] != "31" {
t.Errorf("transition = %v", tr)
}
if l := bodies["POST "+p+"/issueLink"]; l["type"].(map[string]any)["name"] != "Blocks" {
t.Errorf("link = %v", l)
}
}
}
func TestEditMetaAndTransitions(t *testing.T) {
c := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/rest/api/3/issue/DEV-1/editmeta":
fmt.Fprint(w, `{"fields":{"components":{"operations":["add","set","remove"]}}}`)
case "/rest/api/3/issue/DEV-1/transitions":
fmt.Fprint(w, `{"transitions":[{"id":"31","name":"Done","to":{"name":"Done"}}]}`)
default:
t.Errorf("unexpected %s", r.URL.Path)
}
}, atlassian.Cloud)
meta, err := c.EditMeta(context.Background(), "DEV-1")
if err != nil || len(meta["components"]) != 3 {
t.Fatalf("editmeta = %v, %v", meta, err)
}
trs, err := c.Transitions(context.Background(), "DEV-1")
if err != nil || len(trs) != 1 || trs[0].To.StatusName() != "Done" {
t.Fatalf("transitions = %+v, %v", trs, err)
}
}
func TestIssueRoundTripKeepsRawFields(t *testing.T) {
in := `{"id":"1","key":"DEV-1","fields":{"summary":"s","customfield_9":{"value":"x"},"parent":{"key":"DEV-0"},"subtasks":[{"key":"DEV-2"}]}}`
var is Issue
if err := json.Unmarshal([]byte(in), &is); err != nil {
t.Fatal(err)
}
if is.Fields.Parent.Key != "DEV-0" || len(is.Fields.Subtasks) != 1 || is.Fields.Raw["customfield_9"] == nil {
t.Fatalf("issue = %+v", is)
}
out, _ := json.Marshal(is)
if !strings.Contains(string(out), `"customfield_9":{"value":"x"}`) {
t.Errorf("round trip lost a custom field: %s", out)
}
}
func TestOptionValuesShapes(t *testing.T) {
cases := map[string][]string{
`null`: nil,
`"PI28.15"`: {"PI28.15"},
`["PI28.15","PI28.22"]`: {"PI28.15", "PI28.22"},
`{"value":"PI29.2"}`: {"PI29.2"},
`{"name":"label"}`: {"label"},
`[{"value":"PI29.2"},{"value":"PI29.3"}]`: {"PI29.2", "PI29.3"},
}
for in, want := range cases {
got, err := OptionValues(json.RawMessage(in))
if err != nil || strings.Join(got, "|") != strings.Join(want, "|") {
t.Errorf("OptionValues(%s) = %v, %v; want %v", in, got, err, want)
}
}
for _, bad := range []string{`{"foo":1}`, `42`} {
if _, err := OptionValues(json.RawMessage(bad)); err == nil {
t.Errorf("OptionValues(%s): unexpected shape must be an error", bad)
}
}
}
func TestSprintValuesShapes(t *testing.T) {
cases := map[string]string{
`null`: "",
`[]`: "",
`[{"id":1,"name":"Sprint 41","state":"closed","boardId":3},{"id":2,"name":"Sprint 42","state":"ACTIVE"}]`: "Sprint 41/closed|Sprint 42/active",
`["com.atlassian.greenhopper.service.sprint.Sprint@1a2b[id=7,rapidViewId=3,state=FUTURE,name=Sprint 43,startDate=<null>]"]`: "Sprint 43/future",
}
for in, want := range cases {
got, err := SprintValues(json.RawMessage(in))
var parts []string
for _, sp := range got {
parts = append(parts, sp.Name+"/"+sp.State)
}
if err != nil || strings.Join(parts, "|") != want {
t.Errorf("SprintValues(%s) = %v, %v; want %s", in, got, err, want)
}
}
for _, bad := range []string{`"Sprint 1"`, `{"name":"Sprint 1"}`, `[{"id":1}]`, `[42]`} {
if _, err := SprintValues(json.RawMessage(bad)); err == nil {
t.Errorf("SprintValues(%s): unexpected shape must be an error", bad)
}
}
}
func TestCustomFieldNumberAndNames(t *testing.T) {
if n, ok := CustomFieldNumber("customfield_11411"); !ok || n != "11411" {
t.Errorf("CustomFieldNumber = %q %v", n, ok)
}
if _, ok := CustomFieldNumber("summary"); ok {
t.Error("system field reported as custom")
}
if got := Names([]Version{{Name: "a"}, {Name: "b"}}); strings.Join(got, ",") != "a,b" {
t.Errorf("Names = %v", got)
}
}
+150
View File
@@ -0,0 +1,150 @@
package jira
import (
"context"
"net/url"
"strconv"
"strings"
)
// Myself returns the authenticated account -- the cheapest call that
// proves URL and credentials work.
func (c *Client) Myself(ctx context.Context) (User, error) {
var u User
return u, c.getInto(ctx, c.api("/myself"), nil, &u)
}
// ServerInfo returns the instance's /serverInfo.
func (c *Client) ServerInfo(ctx context.Context) (ServerInfo, error) {
var si ServerInfo
return si, c.getInto(ctx, c.api("/serverInfo"), nil, &si)
}
// ListProjects returns every project the account can browse, ordered by
// key. On Cloud it walks /project/search (archived and trashed projects
// are not included); Server/Data Center returns all from /project.
func (c *Client) ListProjects(ctx context.Context) ([]Project, error) {
if !c.cloud {
var out []Project
return out, c.getInto(ctx, c.api("/project"), nil, &out)
}
raw, err := c.Paginate(ctx, c.api("/project/search"), url.Values{"orderBy": []string{"key"}}, "values", 50)
if err != nil {
return nil, err
}
return decodeAll[Project](raw)
}
// Project returns one project with description, lead and components.
func (c *Client) Project(ctx context.Context, keyOrID string) (Project, error) {
var p Project
if err := requireKey("project key", keyOrID); err != nil {
return p, err
}
return p, c.getInto(ctx, c.api("/project/"+url.PathEscape(keyOrID)), nil, &p)
}
// ProjectVersions returns all versions of a project (unpaginated on this
// endpoint).
func (c *Client) ProjectVersions(ctx context.Context, keyOrID string) ([]Version, error) {
var out []Version
return out, c.getInto(ctx, c.api("/project/"+url.PathEscape(keyOrID)+"/versions"), nil, &out)
}
// Version returns one version.
func (c *Client) Version(ctx context.Context, id string) (Version, error) {
var v Version
return v, c.getInto(ctx, c.api("/version/"+url.PathEscape(id)), nil, &v)
}
// Fields returns every system and custom field of the site.
func (c *Client) Fields(ctx context.Context) ([]Field, error) {
var out []Field
return out, c.getInto(ctx, c.api("/field"), nil, &out)
}
// Issue returns one issue. fields limits the returned fields (nil: Jira's
// default, all navigable fields); expand is passed on as the expand
// parameter (e.g. "renderedFields", "changelog").
func (c *Client) Issue(ctx context.Context, keyOrID string, fields []string, expand ...string) (Issue, error) {
var is Issue
if err := requireKey("issue key", keyOrID); err != nil {
return is, err
}
params := url.Values{}
if len(fields) > 0 {
params.Set("fields", strings.Join(fields, ","))
}
if len(expand) > 0 {
params.Set("expand", strings.Join(expand, ","))
}
return is, c.getInto(ctx, c.api("/issue/"+url.PathEscape(keyOrID)), params, &is)
}
// CommentPage returns one page of an issue's comments, oldest first.
func (c *Client) CommentPage(ctx context.Context, keyOrID string, startAt, maxResults int) (CommentPage, error) {
var page CommentPage
q := url.Values{
"orderBy": {"created"},
"startAt": {strconv.Itoa(startAt)},
"maxResults": {strconv.Itoa(maxResults)},
}
return page, c.getInto(ctx, c.api("/issue/"+url.PathEscape(keyOrID)+"/comment"), q, &page)
}
// Comments returns an issue's comments from startAt on, oldest first. A
// later start is useful because a search response already embeds the
// first page.
func (c *Client) Comments(ctx context.Context, keyOrID string, startAt int) ([]Comment, error) {
var out []Comment
for {
page, err := c.CommentPage(ctx, keyOrID, startAt, 100)
if err != nil {
return out, err
}
out = append(out, page.Comments...)
startAt += len(page.Comments)
if len(page.Comments) == 0 || startAt >= page.Total {
return out, nil
}
}
}
// Changelog returns an issue's complete change history. The endpoint
// exists on Cloud only; Server/Data Center has the history in an issue
// fetched with expand "changelog".
func (c *Client) Changelog(ctx context.Context, keyOrID string) ([]ChangelogEntry, error) {
raw, err := c.Paginate(ctx, c.api("/issue/"+url.PathEscape(keyOrID)+"/changelog"), nil, "values", 100)
if err != nil {
return nil, err
}
return decodeAll[ChangelogEntry](raw)
}
// EditMeta returns, by field ID, the edit operations ("add", "set",
// "remove") the authenticated user may use on the issue. A missing field
// cannot be edited by this user (screen or permission).
func (c *Client) EditMeta(ctx context.Context, keyOrID string) (map[string][]string, error) {
var meta struct {
Fields map[string]struct {
Operations []string `json:"operations"`
} `json:"fields"`
}
if err := c.getInto(ctx, c.api("/issue/"+url.PathEscape(keyOrID)+"/editmeta"), nil, &meta); err != nil {
return nil, err
}
out := make(map[string][]string, len(meta.Fields))
for id, f := range meta.Fields {
out[id] = f.Operations
}
return out, nil
}
// Transitions returns the workflow transitions currently available on an
// issue.
func (c *Client) Transitions(ctx context.Context, keyOrID string) ([]Transition, error) {
var result struct {
Transitions []Transition `json:"transitions"`
}
return result.Transitions, c.getInto(ctx, c.api("/issue/"+url.PathEscape(keyOrID)+"/transitions"), nil, &result)
}
+147
View File
@@ -0,0 +1,147 @@
package jira
import (
"context"
"encoding/json"
"fmt"
"strings"
"yetano.dev/yetano/yetano-clients/atlassian"
)
// SearchQuery is one JQL search walked to the end by Search/SearchAll.
type SearchQuery struct {
JQL string
Fields []string
Expand string // comma-separated, e.g. "renderedFields,changelog"
PageSize int // default 100
}
// Search runs a JQL query and calls fn once per page, so a caller never
// has to hold more than it needs. On Cloud it uses the enhanced search
// endpoint (/rest/api/3/search/jql, nextPageToken pagination); on
// Server/Data Center POST /rest/api/2/search with startAt/total.
func (c *Client) Search(ctx context.Context, q SearchQuery, fn func([]Issue) error) error {
if strings.TrimSpace(q.JQL) == "" {
return fmt.Errorf("%w: jql must not be empty", atlassian.ErrInvalidArgument)
}
if q.PageSize <= 0 {
q.PageSize = 100
}
if !c.cloud {
return c.searchOffset(ctx, q, fn)
}
next := ""
for {
body := map[string]any{"jql": q.JQL, "fields": q.Fields, "maxResults": q.PageSize}
if q.Expand != "" {
body["expand"] = q.Expand
}
if next != "" {
body["nextPageToken"] = next
}
raw, err := c.Post(ctx, c.api("/search/jql"), body)
if err != nil {
return err
}
var page struct {
Issues []Issue `json:"issues"`
NextPageToken string `json:"nextPageToken"`
IsLast *bool `json:"isLast"`
}
if err := json.Unmarshal(raw, &page); err != nil {
return fmt.Errorf("search: %w", err)
}
if len(page.Issues) > 0 {
if err := fn(page.Issues); err != nil {
return err
}
}
next = page.NextPageToken
if next == "" || len(page.Issues) == 0 || (page.IsLast != nil && *page.IsLast) {
return nil
}
}
}
func (c *Client) searchOffset(ctx context.Context, q SearchQuery, fn func([]Issue) error) error {
start := 0
for {
page, err := c.SearchPage(ctx, PageQuery{JQL: q.JQL, StartAt: start, MaxResults: q.PageSize, Fields: q.Fields, Expand: splitList(q.Expand)})
if err != nil {
return err
}
if len(page.Issues) > 0 {
if err := fn(page.Issues); err != nil {
return err
}
}
start += len(page.Issues)
if len(page.Issues) == 0 || start >= page.Total {
return nil
}
}
}
// SearchAll is Search collecting every issue.
func (c *Client) SearchAll(ctx context.Context, q SearchQuery) ([]Issue, error) {
var all []Issue
err := c.Search(ctx, q, func(page []Issue) error {
all = append(all, page...)
return nil
})
return all, err
}
// PageQuery is one page of a classic offset search.
type PageQuery struct {
JQL string
StartAt int
MaxResults int
Fields []string
Expand []string
}
// SearchResult is one page of a classic offset search.
type SearchResult struct {
StartAt int `json:"startAt"`
MaxResults int `json:"maxResults"`
Total int `json:"total"`
Issues []Issue `json:"issues"`
}
// SearchPage fetches one page through the classic POST {prefix}/search
// endpoint (startAt/maxResults/total). It is what Server/Data Center
// offers; on Cloud Atlassian has deprecated it in favour of
// /rest/api/3/search/jql (Search), so new Cloud code should use Search.
func (c *Client) SearchPage(ctx context.Context, q PageQuery) (SearchResult, error) {
var out SearchResult
if strings.TrimSpace(q.JQL) == "" {
return out, fmt.Errorf("%w: jql must not be empty", atlassian.ErrInvalidArgument)
}
body := struct {
JQL string `json:"jql"`
StartAt int `json:"startAt"`
MaxResults int `json:"maxResults"`
Fields []string `json:"fields,omitempty"`
Expand []string `json:"expand,omitempty"`
}{q.JQL, q.StartAt, q.MaxResults, q.Fields, q.Expand}
raw, err := c.Post(ctx, c.api("/search"), body)
if err != nil {
return out, err
}
if err := json.Unmarshal(raw, &out); err != nil {
return out, fmt.Errorf("search: %w", err)
}
return out, nil
}
func splitList(s string) []string {
var out []string
for _, p := range strings.Split(s, ",") {
if p = strings.TrimSpace(p); p != "" {
out = append(out, p)
}
}
return out
}
+224
View File
@@ -0,0 +1,224 @@
package jira
import "encoding/json"
// Project is a Jira project. Description, Lead and Components are only
// filled by Project (the single-project call), not by ListProjects.
type Project struct {
ID string `json:"id"`
Key string `json:"key"`
Name string `json:"name"`
ProjectTypeKey string `json:"projectTypeKey"`
Description string `json:"description,omitempty"`
Lead *User `json:"lead,omitempty"`
Components []Named `json:"components,omitempty"`
}
// User is a Jira account: AccountID on Cloud, Name/Key on Server/Data
// Center.
type User struct {
AccountID string `json:"accountId"`
Name string `json:"name,omitempty"`
Key string `json:"key,omitempty"`
DisplayName string `json:"displayName"`
EmailAddress string `json:"emailAddress"`
}
// Named is any Jira object identified by id/name (and sometimes key):
// components, issue types, priorities, link types.
type Named struct {
ID string `json:"id"`
Name string `json:"name"`
Key string `json:"key,omitempty"`
}
// Version is a project version ("release").
type Version struct {
ID string `json:"id"`
Name string `json:"name"`
Description string `json:"description,omitempty"`
Released bool `json:"released"`
Archived bool `json:"archived"`
ReleaseDate string `json:"releaseDate,omitempty"`
StartDate string `json:"startDate,omitempty"`
ProjectID int `json:"projectId,omitempty"`
}
// Field is one entry of the field list.
type Field struct {
ID string `json:"id"`
Key string `json:"key"`
Name string `json:"name"`
Custom bool `json:"custom"`
Schema *FieldSchema `json:"schema"`
}
// FieldSchema describes a field's value shape.
type FieldSchema struct {
Type string `json:"type"`
Items string `json:"items,omitempty"`
Custom string `json:"custom,omitempty"`
}
// Issue is a Jira issue. The standard fields are decoded into Fields;
// every field (standard and custom) also stays available raw in
// Fields.Raw, because custom field IDs differ per site and are only known
// at runtime.
type Issue struct {
ID string `json:"id"`
Key string `json:"key"`
Self string `json:"self,omitempty"`
Fields IssueFields `json:"fields"`
}
// IssueFields are the standard fields. Description is ADF (a JSON
// object) on Cloud and a wiki-markup string on Server/Data Center.
type IssueFields struct {
Summary string `json:"summary"`
Status *Status `json:"status"`
IssueType *Named `json:"issuetype"`
Resolutiondate string `json:"resolutiondate"`
Created string `json:"created"`
Updated string `json:"updated"`
Reporter *User `json:"reporter"`
Assignee *User `json:"assignee"`
Priority *Named `json:"priority"`
Components []Named `json:"components"`
Versions []Version `json:"versions"` // affected versions
FixVersions []Version `json:"fixVersions"` // fix versions
Labels []string `json:"labels"`
Comment *CommentPage `json:"comment"`
Description json.RawMessage `json:"description"`
IssueLinks []IssueLink `json:"issuelinks"`
Parent *LinkedIssue `json:"parent"`
Subtasks []LinkedIssue `json:"subtasks"`
Raw map[string]json.RawMessage `json:"-"`
}
// UnmarshalJSON decodes the standard fields and keeps all of them raw.
func (f *IssueFields) UnmarshalJSON(data []byte) error {
type plain IssueFields
var p plain
if err := json.Unmarshal(data, &p); err != nil {
return err
}
var raw map[string]json.RawMessage
if err := json.Unmarshal(data, &raw); err != nil {
return err
}
*f = IssueFields(p)
f.Raw = raw
return nil
}
// MarshalJSON writes the raw fields back, so an Issue round-trips.
func (f IssueFields) MarshalJSON() ([]byte, error) {
if f.Raw != nil {
return json.Marshal(f.Raw)
}
type plain IssueFields
return json.Marshal(plain(f))
}
// Status is an issue status with its category (new, indeterminate, done).
type Status struct {
Name string `json:"name"`
StatusCategory *struct {
Key string `json:"key"`
} `json:"statusCategory"`
}
// CategoryKey is the status category key, "" if unknown.
func (s *Status) CategoryKey() string {
if s == nil || s.StatusCategory == nil {
return ""
}
return s.StatusCategory.Key
}
// StatusName is s.Name, "" for nil.
func (s *Status) StatusName() string {
if s == nil {
return ""
}
return s.Name
}
// CommentPage is one page of comments (also embedded in a search result
// when the comment field is requested).
type CommentPage struct {
Comments []Comment `json:"comments"`
Total int `json:"total"`
MaxResults int `json:"maxResults"`
StartAt int `json:"startAt"`
}
// Comment is one issue comment. Body is ADF on Cloud, a string on
// Server/Data Center.
type Comment struct {
ID string `json:"id"`
Author *User `json:"author"`
Body json.RawMessage `json:"body"`
Created string `json:"created"`
Updated string `json:"updated"`
}
// IssueLinkType names a link type in both directions.
type IssueLinkType struct {
Name string `json:"name"`
Inward string `json:"inward"`
Outward string `json:"outward"`
}
// IssueLink links two issues; exactly one of InwardIssue/OutwardIssue is
// set, the other end is the issue the link belongs to.
type IssueLink struct {
Type *IssueLinkType `json:"type"`
InwardIssue *LinkedIssue `json:"inwardIssue"`
OutwardIssue *LinkedIssue `json:"outwardIssue"`
}
// LinkedIssue is the short form of an issue inside a link, a parent or a
// subtask list.
type LinkedIssue struct {
ID string `json:"id,omitempty"`
Key string `json:"key"`
Fields struct {
Summary string `json:"summary"`
Status *Status `json:"status"`
} `json:"fields"`
}
// ChangelogEntry is one change set of an issue's history.
type ChangelogEntry struct {
ID string `json:"id"`
Author *User `json:"author"`
Created string `json:"created"`
Items []ChangelogItem `json:"items"`
}
// ChangelogItem is one changed field inside a ChangelogEntry.
type ChangelogItem struct {
Field string `json:"field"`
FieldID string `json:"fieldId"`
From string `json:"from"`
FromString string `json:"fromString"`
To string `json:"to"`
ToString string `json:"toString"`
}
// Transition is a workflow transition currently available on an issue.
type Transition struct {
ID string `json:"id"`
Name string `json:"name"`
To *Status `json:"to"`
}
// ServerInfo is /serverInfo.
type ServerInfo struct {
BaseURL string `json:"baseUrl"`
Version string `json:"version"`
DeploymentType string `json:"deploymentType"`
ServerTitle string `json:"serverTitle"`
}
+168
View File
@@ -0,0 +1,168 @@
package jira
import (
"context"
"encoding/json"
"fmt"
"net/url"
)
// TextBody encodes plain text as a description/comment body: a minimal
// Atlassian Document Format document (one paragraph) on Cloud, the plain
// string on Server/Data Center.
func (c *Client) TextBody(text string) any {
if !c.cloud {
return text
}
return map[string]any{
"type": "doc",
"version": 1,
"content": []any{
map[string]any{
"type": "paragraph",
"content": []any{
map[string]any{"type": "text", "text": text},
},
},
},
}
}
// IssueEdit is one PUT on an issue. Fields replaces whole field values
// ({"summary": "x"}); Update applies operations to them
// ({"labels": [{"add": "x"}], "components": [{"remove": {"id": "10"}}]}),
// touching only the named values, so a value someone else added in the
// meantime stays. An empty part is left out of the request.
type IssueEdit struct {
Fields map[string]any
Update map[string][]map[string]any
}
// EditIssue applies e to an issue.
func (c *Client) EditIssue(ctx context.Context, keyOrID string, e IssueEdit) error {
if err := requireKey("issue key", keyOrID); err != nil {
return err
}
body := map[string]any{}
if len(e.Fields) > 0 {
body["fields"] = e.Fields
}
if len(e.Update) > 0 {
body["update"] = e.Update
}
_, err := c.Put(ctx, c.api("/issue/"+url.PathEscape(keyOrID)), body)
return err
}
// UpdateIssue sets whole field values on an issue (EditIssue with
// Fields only).
func (c *Client) UpdateIssue(ctx context.Context, keyOrID string, fields map[string]any) error {
return c.EditIssue(ctx, keyOrID, IssueEdit{Fields: fields})
}
// UpdateVersion changes a version (e.g. {"released": true,
// "releaseDate": "2026-11-01"}).
func (c *Client) UpdateVersion(ctx context.Context, id string, body map[string]any) error {
if err := requireKey("version id", id); err != nil {
return err
}
_, err := c.Put(ctx, c.api("/version/"+url.PathEscape(id)), body)
return err
}
// CreateIssueInput describes a new issue; ParentKey makes it a subtask.
type CreateIssueInput struct {
ProjectKey string
IssueType string // issue type name
Summary string
Description string // plain text, encoded with TextBody
Labels []string
ParentKey string
}
// CreateIssue creates an issue and returns its key.
func (c *Client) CreateIssue(ctx context.Context, in CreateIssueInput) (string, error) {
fields := map[string]any{
"project": map[string]string{"key": in.ProjectKey},
"issuetype": map[string]string{"name": in.IssueType},
"summary": in.Summary,
}
if in.Description != "" {
fields["description"] = c.TextBody(in.Description)
}
if len(in.Labels) > 0 {
fields["labels"] = in.Labels
}
if in.ParentKey != "" {
fields["parent"] = map[string]string{"key": in.ParentKey}
}
raw, err := c.Post(ctx, c.api("/issue"), map[string]any{"fields": fields})
if err != nil {
return "", err
}
var resp struct {
Key string `json:"key"`
}
if err := json.Unmarshal(raw, &resp); err != nil {
return "", fmt.Errorf("create issue: %w", err)
}
return resp.Key, nil
}
// AddComment adds a plain-text comment (encoded with TextBody) and
// returns its ID.
func (c *Client) AddComment(ctx context.Context, keyOrID, text string) (string, error) {
if err := requireKey("issue key", keyOrID); err != nil {
return "", err
}
raw, err := c.Post(ctx, c.api("/issue/"+url.PathEscape(keyOrID)+"/comment"), map[string]any{"body": c.TextBody(text)})
if err != nil {
return "", err
}
var resp struct {
ID string `json:"id"`
}
if err := json.Unmarshal(raw, &resp); err != nil {
return "", fmt.Errorf("add comment: %w", err)
}
return resp.ID, nil
}
// DoTransition moves an issue along the transition with the given ID
// (see Transitions).
func (c *Client) DoTransition(ctx context.Context, keyOrID, transitionID string) error {
_, err := c.Post(ctx, c.api("/issue/"+url.PathEscape(keyOrID)+"/transitions"),
map[string]any{"transition": map[string]string{"id": transitionID}})
return err
}
// AssignIssue assigns an issue to a Cloud accountId or a Server/Data
// Center username; an empty assignee unassigns it.
func (c *Client) AssignIssue(ctx context.Context, keyOrID, assignee string) error {
body := map[string]any{}
switch {
case c.cloud:
body["accountId"] = nilIfEmpty(assignee)
default:
body["name"] = nilIfEmpty(assignee)
}
_, err := c.Put(ctx, c.api("/issue/"+url.PathEscape(keyOrID)+"/assignee"), body)
return err
}
func nilIfEmpty(s string) any {
if s == "" {
return nil
}
return s
}
// LinkIssues links two issues with the named link type.
func (c *Client) LinkIssues(ctx context.Context, linkType, inwardKey, outwardKey string) error {
_, err := c.Post(ctx, c.api("/issueLink"), map[string]any{
"type": map[string]string{"name": linkType},
"inwardIssue": map[string]string{"key": inwardKey},
"outwardIssue": map[string]string{"key": outwardKey},
})
return err
}
+3
View File
@@ -0,0 +1,3 @@
module yetano.dev/yetano/yetano-clients
go 1.25.0