ruby-jira 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/lib/jira/client.rb CHANGED
@@ -4,9 +4,19 @@ module Jira
4
4
  class Client < API
5
5
  Dir[File.expand_path("client/*.rb", __dir__)].each { |file| require file }
6
6
 
7
+ include AgileIssues
8
+ include Boards
9
+ include Epics
10
+ include IssueComments
11
+ include IssueSearch
7
12
  include Issues
13
+ include IssueWorklogs
14
+ include ProjectCategories
8
15
  include ProjectPermissionSchemes
16
+ include ProjectProperties
9
17
  include Projects
18
+ include Sprints
19
+ include TimeTracking
10
20
 
11
21
  # Text representation of the client, masking auth secrets.
12
22
  #
@@ -21,6 +21,7 @@ module Jira
21
21
  ratelimit_retries
22
22
  ratelimit_base_delay
23
23
  ratelimit_max_delay
24
+ logger
24
25
  ].freeze
25
26
 
26
27
  DEFAULT_USER_AGENT = "Ruby Jira Gem #{Jira::VERSION}".freeze
@@ -63,6 +64,7 @@ module Jira
63
64
  self.ratelimit_max_delay = float_env("JIRA_RATELIMIT_MAX_DELAY", DEFAULT_RATELIMIT_MAX_DELAY)
64
65
  self.httparty = get_httparty_config(ENV.fetch("JIRA_HTTPARTY_OPTIONS", nil))
65
66
  self.user_agent = DEFAULT_USER_AGENT
67
+ self.logger = nil
66
68
  end
67
69
 
68
70
  private
data/lib/jira/error.rb CHANGED
@@ -11,6 +11,9 @@ module Jira
11
11
  # Raised when impossible to parse response body.
12
12
  class Parsing < Base; end
13
13
 
14
+ # Raised when pagination cannot continue safely.
15
+ class Pagination < Base; end
16
+
14
17
  # Custom error class for rescuing from HTTP response errors.
15
18
  class ResponseError < Base
16
19
  POSSIBLE_MESSAGE_KEYS = %i[message error_description error].freeze
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Jira
4
+ # Provides a #log helper that delegates to the configured logger.
5
+ # Mixed into Request and pagination classes to emit debug information.
6
+ #
7
+ # @example Enable logging
8
+ # require "logger"
9
+ # Jira.configure { |c| c.logger = Logger.new($stdout) }
10
+ module Logging
11
+ def log(message)
12
+ Jira.logger&.debug("[ruby-jira] #{message}")
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,72 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Jira
4
+ module Pagination
5
+ # Shared behavior for paginated collection wrappers.
6
+ module CollectionBehavior
7
+ def inspect
8
+ @array.inspect
9
+ end
10
+
11
+ def method_missing(name, *, &)
12
+ return @array.send(name, *, &) if @array.respond_to?(name)
13
+
14
+ super
15
+ end
16
+
17
+ def respond_to_missing?(method_name, include_private = false)
18
+ super || @array.respond_to?(method_name, include_private)
19
+ end
20
+
21
+ def each_page # rubocop:disable Metrics/MethodLength
22
+ return enum_for(:each_page) unless block_given?
23
+
24
+ current = self
25
+ seen_markers = {}
26
+ loop do
27
+ yield current
28
+ break unless current.has_next_page?
29
+
30
+ marker = current.pagination_progress_marker
31
+ check_repeated_marker!(seen_markers, marker)
32
+ seen_markers[marker] = true if marker
33
+ current = next_page_with_progress_check(current, marker)
34
+ end
35
+ end
36
+
37
+ def lazy_paginate
38
+ to_enum(:each_page).lazy.flat_map(&:to_ary)
39
+ end
40
+
41
+ def auto_paginate(&block)
42
+ return lazy_paginate.to_a unless block
43
+
44
+ lazy_paginate.each(&block)
45
+ end
46
+
47
+ def paginate_with_limit(limit, &block)
48
+ return lazy_paginate.take(limit).to_a unless block
49
+
50
+ lazy_paginate.take(limit).each(&block)
51
+ end
52
+
53
+ private
54
+
55
+ def check_repeated_marker!(seen_markers, marker)
56
+ return unless marker
57
+ return unless seen_markers.key?(marker)
58
+
59
+ raise Error::Pagination, "pagination cursor repeated: #{marker.inspect}"
60
+ end
61
+
62
+ def next_page_with_progress_check(current, marker)
63
+ next_page = current.next_page
64
+ raise Error::Pagination, "pagination returned nil page" unless next_page
65
+ return next_page unless marker
66
+ return next_page unless next_page.pagination_progress_marker == marker
67
+
68
+ raise Error::Pagination, "pagination did not advance from #{marker.inspect}"
69
+ end
70
+ end
71
+ end
72
+ end
@@ -1,10 +1,16 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "uri"
4
+
3
5
  module Jira
4
- # Wrapper for Jira cursor-paginated responses (nextPageToken style).
6
+ # Wrapper for Jira cursor-paginated responses.
5
7
  #
6
8
  # Endpoints like POST /search/jql return a body of:
7
9
  # { nextPageToken: "token", total: int, <items_key>: [...] }
10
+ # Some Jira APIs use alternative cursor fields:
11
+ # { nextPageCursor: "cursor", ... } or { cursor: "...", nextPageCursor: "...", last: false, ... }
12
+ # Other APIs use URL-based cursor fields:
13
+ # { nextPage: "https://...", lastPage: false, ... }
8
14
  #
9
15
  # The items array key varies by endpoint (e.g. "issues", "worklogs").
10
16
  # This class detects it automatically as the first non-metadata Array value.
@@ -12,77 +18,87 @@ module Jira
12
18
  # Pagination is driven by a +next_page_fetcher+ proc set by the Request layer,
13
19
  # which re-issues the original request with +nextPageToken+ injected.
14
20
  class CursorPaginatedResponse
15
- METADATA_KEYS = %i[nextPageToken total self].freeze
21
+ include Logging
22
+ include Pagination::CollectionBehavior
23
+
24
+ METADATA_KEYS = %i[
25
+ nextPageToken nextPageCursor cursor nextPage total self isLast last lastPage expand warningMessages maxResults
26
+ startAt size
27
+ ].freeze
16
28
 
17
29
  attr_accessor :client, :next_page_fetcher
18
- attr_reader :next_page_token, :total
30
+ attr_reader :next_page_token, :next_page_cursor, :next_page_url, :total
19
31
 
20
- def initialize(body)
21
- @body = body
32
+ def initialize(body) # rubocop:disable Metrics/AbcSize
22
33
  @next_page_token = body[:nextPageToken]
34
+ @next_page_cursor = body[:nextPageCursor] || body[:cursor]
35
+ @next_page_url = body[:nextPage]
36
+ @is_last = body[:isLast]
37
+ @last = body[:last]
38
+ @last_page = body[:lastPage]
23
39
  @total = body.fetch(:total, 0).to_i
24
- @array = wrap_items(detect_items_array(body))
40
+ items_key, items = detect_items_array(body)
41
+ log "CursorPaginatedResponse: items_key=#{items_key.inspect} count=#{items.length}"
42
+ @array = wrap_items(items)
25
43
  end
26
44
 
27
- def inspect
28
- @array.inspect
45
+ def next_page?
46
+ return false if @is_last == true || @last == true || @last_page == true
47
+
48
+ !next_page_locator.to_s.empty?
29
49
  end
50
+ alias has_next_page? next_page?
30
51
 
31
- def method_missing(name, *, &)
32
- return @array.send(name, *, &) if @array.respond_to?(name)
52
+ def next_page
53
+ return nil unless has_next_page?
54
+ return next_page_by_link unless @next_page_url.to_s.empty?
55
+ raise Error::MissingCredentials, "next_page_fetcher not set on CursorPaginatedResponse" unless @next_page_fetcher
33
56
 
34
- super
57
+ @next_page_fetcher.call(next_page_locator)
35
58
  end
36
59
 
37
- def respond_to_missing?(method_name, include_private = false)
38
- super || @array.respond_to?(method_name, include_private)
39
- end
60
+ def cursor_parameter_key
61
+ return :nextPageToken unless @next_page_token.to_s.empty?
62
+ return :cursor unless @next_page_cursor.to_s.empty?
40
63
 
41
- def each_page
42
- current = self
43
- yield current
44
- while current.has_next_page?
45
- current = current.next_page
46
- yield current
47
- end
64
+ nil
48
65
  end
49
66
 
50
- def lazy_paginate
51
- to_enum(:each_page).lazy.flat_map(&:to_ary)
67
+ def fetcher_based_pagination?
68
+ @next_page_url.to_s.empty?
52
69
  end
53
70
 
54
- def auto_paginate(&block)
55
- return lazy_paginate.to_a unless block
56
-
57
- lazy_paginate.each(&block)
71
+ def pagination_progress_marker
72
+ next_page_locator
58
73
  end
59
74
 
60
- def paginate_with_limit(limit, &block)
61
- return lazy_paginate.take(limit).to_a unless block
75
+ private
62
76
 
63
- lazy_paginate.take(limit).each(&block)
64
- end
77
+ def next_page_locator
78
+ return @next_page_token unless @next_page_token.to_s.empty?
79
+ return @next_page_cursor unless @next_page_cursor.to_s.empty?
80
+ return @next_page_url unless @next_page_url.to_s.empty?
65
81
 
66
- def next_page?
67
- !@next_page_token.to_s.empty?
82
+ nil
68
83
  end
69
- alias has_next_page? next_page?
70
84
 
71
- def next_page
72
- return nil unless has_next_page?
73
- raise Error::MissingCredentials, "next_page_fetcher not set on CursorPaginatedResponse" unless @next_page_fetcher
85
+ def next_page_by_link
86
+ raise Error::MissingCredentials, "client not set on CursorPaginatedResponse" unless @client
74
87
 
75
- @next_page_fetcher.call(@next_page_token)
88
+ @client.get(client_relative_path(@next_page_url))
76
89
  end
77
90
 
78
- private
91
+ def client_relative_path(link)
92
+ client_endpoint_path = @client.api_request_path
93
+ URI.parse(link).request_uri.sub(client_endpoint_path, "")
94
+ end
79
95
 
80
96
  def detect_items_array(body)
81
97
  body.each do |key, value|
82
98
  next if METADATA_KEYS.include?(key)
83
- return value if value.is_a?(Array)
99
+ return [key, value] if value.is_a?(Array)
84
100
  end
85
- []
101
+ [nil, []]
86
102
  end
87
103
 
88
104
  def wrap_items(items)
@@ -3,64 +3,41 @@
3
3
  require "uri"
4
4
 
5
5
  module Jira
6
- # Wrapper for Jira offset-paginated responses (values/isLast style).
6
+ # Wrapper for Jira offset-paginated responses.
7
7
  #
8
- # Endpoints like GET /project/search and GET /workflow/search return a body of:
9
- # { values: [...], isLast: bool, total: int, nextPage: url, startAt: int, maxResults: int }
8
+ # Supports two formats:
9
+ # - Classic: { values: [...], isLast: bool, nextPage: url, startAt: int, maxResults: int, total: int }
10
+ # (GET /project/search, GET /issue/{key}/changelog, POST /comment/list)
11
+ # - Legacy: { <items_key>: [...], startAt: int, maxResults: int, total: int }
12
+ # (GET /issue/{key}/comment, GET /issue/{key}/worklog)
13
+ #
14
+ # For legacy format, items key is auto-detected (first non-metadata Array value).
15
+ # When nextPage URL is absent, a next_page_fetcher proc set by the Request layer
16
+ # drives pagination by incrementing startAt.
10
17
  class PaginatedResponse
11
- attr_accessor :client
18
+ include Logging
19
+ include Pagination::CollectionBehavior
20
+
21
+ METADATA_KEYS = %i[
22
+ isLast maxResults nextPage self startAt total pageSize nextPageToken expand warningMessages
23
+ ].freeze
24
+
25
+ attr_accessor :client, :next_page_fetcher
12
26
  attr_reader :total, :max_results, :start_at, :self_url
13
27
 
14
- def initialize(body)
28
+ def initialize(body) # rubocop:disable Metrics/AbcSize
15
29
  @body = body
16
- @array = wrap_items(body.fetch(:values, []))
17
- @is_last = body.fetch(:isLast, false)
18
- @max_results = body.fetch(:maxResults, 0).to_i
30
+ items_key, items = detect_items(body)
31
+ log "PaginatedResponse: items_key=#{items_key.inspect} count=#{items.length}"
32
+ @array = wrap_items(items)
33
+ @is_last = body.key?(:isLast) ? body[:isLast] : (@array.length + body.fetch(:startAt, 0) >= body.fetch(:total, 0))
34
+ @max_results = (body[:maxResults] || body[:pageSize] || items.length).to_i
19
35
  @next_page = body.fetch(:nextPage, "")
20
36
  @self_url = body.fetch(:self, "")
21
37
  @start_at = body.fetch(:startAt, 0).to_i
22
38
  @total = body.fetch(:total, 0).to_i
23
39
  end
24
40
 
25
- def inspect
26
- @array.inspect
27
- end
28
-
29
- def method_missing(name, *, &)
30
- return @array.send(name, *, &) if @array.respond_to?(name)
31
-
32
- super
33
- end
34
-
35
- def respond_to_missing?(method_name, include_private = false)
36
- super || @array.respond_to?(method_name, include_private)
37
- end
38
-
39
- def each_page
40
- current = self
41
- yield current
42
- while current.has_next_page?
43
- current = current.next_page
44
- yield current
45
- end
46
- end
47
-
48
- def lazy_paginate
49
- to_enum(:each_page).lazy.flat_map(&:to_ary)
50
- end
51
-
52
- def auto_paginate(&block)
53
- return lazy_paginate.to_a unless block
54
-
55
- lazy_paginate.each(&block)
56
- end
57
-
58
- def paginate_with_limit(limit, &block)
59
- return lazy_paginate.take(limit).to_a unless block
60
-
61
- lazy_paginate.take(limit).each(&block)
62
- end
63
-
64
41
  def last_page?
65
42
  @is_last == true
66
43
  end
@@ -72,14 +49,20 @@ module Jira
72
49
  alias has_first_page? first_page?
73
50
 
74
51
  def next_page?
75
- @is_last == false && !@next_page.to_s.empty?
52
+ !last_page? && (!@next_page.to_s.empty? || !@next_page_fetcher.nil?)
76
53
  end
77
54
  alias has_next_page? next_page?
78
55
 
79
56
  def next_page
80
- return nil unless has_next_page?
57
+ return nil unless next_page?
58
+ return next_page_by_link unless @next_page.to_s.empty?
59
+ raise Error::MissingCredentials, "next_page_fetcher not set on PaginatedResponse" unless @next_page_fetcher
81
60
 
82
- @client.get(client_relative_path(@next_page))
61
+ @next_page_fetcher.call(@start_at + @max_results)
62
+ end
63
+
64
+ def pagination_progress_marker
65
+ [@start_at, @next_page.to_s]
83
66
  end
84
67
 
85
68
  def client_relative_path(link)
@@ -89,6 +72,19 @@ module Jira
89
72
 
90
73
  private
91
74
 
75
+ def next_page_by_link
76
+ raise Error::MissingCredentials, "client not set on PaginatedResponse" unless @client
77
+
78
+ @client.get(client_relative_path(@next_page))
79
+ end
80
+
81
+ def detect_items(body)
82
+ return [:values, body[:values]] if body.key?(:values)
83
+
84
+ body.each { |k, v| return [k, v] if !METADATA_KEYS.include?(k) && v.is_a?(Array) }
85
+ [nil, []]
86
+ end
87
+
92
88
  def wrap_items(items)
93
89
  items.map { |item| item.is_a?(Hash) ? ObjectifiedHash.new(item) : item }
94
90
  end
@@ -8,12 +8,12 @@ module Jira
8
8
  # https://developer.atlassian.com/cloud/jira/platform/rate-limiting/
9
9
  #
10
10
  # Supported response headers (enforced by Jira Cloud):
11
- # Retry-After — seconds to wait before retrying (429 and some 503)
12
- # X-RateLimit-Reset — ISO 8601 timestamp when the window resets (429 only)
13
- # X-RateLimit-Limit — max request rate for the current scope
14
- # X-RateLimit-Remaining — remaining capacity in the current window
15
- # X-RateLimit-NearLimit — "true" when < 20% capacity remains
16
- # RateLimit-Reason — which limit was exceeded (burst/quota/per-issue)
11
+ # Retry-After - seconds to wait before retrying (429 and some 503)
12
+ # X-RateLimit-Reset - ISO 8601 timestamp when the window resets (429 only)
13
+ # X-RateLimit-Limit - max request rate for the current scope
14
+ # X-RateLimit-Remaining - remaining capacity in the current window
15
+ # X-RateLimit-NearLimit - "true" when < 20% capacity remains
16
+ # RateLimit-Reason - which limit was exceeded (burst/quota/per-issue)
17
17
  class RetryPolicy
18
18
  IDEMPOTENT_HTTP_METHODS = %w[get head put delete options].freeze
19
19
 
@@ -5,28 +5,29 @@ module Jira
5
5
  class UrlBuilder
6
6
  OAUTH_API_BASE = "https://api.atlassian.com/ex/jira"
7
7
  PLATFORM_API_PATH = "/rest/api/3"
8
+ AGILE_API_PATH = "/rest/agile/1.0"
8
9
 
9
10
  def initialize(request:, authenticator:)
10
11
  @request = request
11
12
  @authenticator = authenticator
12
13
  end
13
14
 
14
- def build(path)
15
- "#{api_base_url}#{normalize_path(path)}"
15
+ def build(path, api_path: PLATFORM_API_PATH)
16
+ "#{base_url_for(api_path)}#{normalize_path(path)}"
16
17
  end
17
18
 
18
19
  def api_request_path
19
- URI.parse(api_base_url).request_uri
20
+ URI.parse(base_url_for(PLATFORM_API_PATH)).request_uri
20
21
  end
21
22
 
22
23
  private
23
24
 
24
- def api_base_url
25
+ def base_url_for(api_path)
25
26
  case @authenticator.auth_type
26
27
  when :basic
27
- "#{normalized_endpoint}#{PLATFORM_API_PATH}"
28
+ "#{normalized_endpoint}#{api_path}"
28
29
  when :oauth2
29
- "#{OAUTH_API_BASE}/#{@request.cloud_id}#{PLATFORM_API_PATH}"
30
+ "#{OAUTH_API_BASE}/#{@request.cloud_id}#{api_path}"
30
31
  end
31
32
  end
32
33
 
@@ -4,16 +4,12 @@ module Jira
4
4
  class Request
5
5
  class ResponseParser
6
6
  class << self
7
- def parse(body) # rubocop:disable Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
7
+ def parse(body)
8
8
  decoded = decode(body)
9
- return PaginatedResponse.new(decoded) if offset_paginated?(decoded)
10
- return CursorPaginatedResponse.new(decoded) if cursor_paginated?(decoded)
11
- return ObjectifiedHash.new(decoded) if decoded.is_a?(Hash)
12
- return decoded.map { |item| item.is_a?(Hash) ? ObjectifiedHash.new(item) : item } if decoded.is_a?(Array)
13
- return true if decoded
14
- return false unless decoded
9
+ paginated = parse_paginated(decoded)
10
+ return paginated if paginated
15
11
 
16
- raise Error::Parsing, "Couldn't parse a response body"
12
+ parse_non_paginated(decoded)
17
13
  end
18
14
 
19
15
  def decode(response)
@@ -26,18 +22,88 @@ module Jira
26
22
 
27
23
  private
28
24
 
29
- # Offset-based pagination: GET /project/search, GET /workflow/search, etc.
30
- # Requires :values and at least one offset-pagination hint.
25
+ def parse_paginated(decoded)
26
+ case pagination_model(decoded)
27
+ when :cursor
28
+ CursorPaginatedResponse.new(decoded)
29
+ when :offset
30
+ PaginatedResponse.new(decoded)
31
+ end
32
+ end
33
+
34
+ def parse_non_paginated(decoded)
35
+ return ObjectifiedHash.new(decoded) if decoded.is_a?(Hash)
36
+ return decoded.map { |item| item.is_a?(Hash) ? ObjectifiedHash.new(item) : item } if decoded.is_a?(Array)
37
+ return true if decoded
38
+ return false unless decoded
39
+
40
+ raise Error::Parsing, "Couldn't parse a response body"
41
+ end
42
+
43
+ def pagination_model(body)
44
+ return nil unless body.is_a?(Hash)
45
+ return :cursor if cursor_paginated?(body)
46
+ return :offset if offset_paginated?(body)
47
+
48
+ nil
49
+ end
50
+
51
+ # Offset-based pagination:
52
+ # - PageBean responses: startAt/maxResults/total/isLast/nextPage + values
53
+ # - Legacy page responses: startAt/maxResults/total + endpoint-specific items key
31
54
  def offset_paginated?(body)
32
- body.is_a?(Hash) &&
33
- body.key?(:values) &&
34
- (body.key?(:isLast) || body.key?(:nextPage) || body.key?(:startAt))
55
+ return false unless body.is_a?(Hash)
56
+ return false if cursor_signature?(body)
57
+
58
+ offset_values_signature?(body) || offset_generic_signature?(body)
35
59
  end
36
60
 
37
- # Cursor-based pagination: POST /search/jql, etc.
38
- # The token drives the next request; items live under a variable key.
61
+ # Cursor-based pagination:
62
+ # - Token: nextPageToken (search/jql and similar)
63
+ # - Cursor: nextPageCursor/cursor (plans-like)
64
+ # - URL cursor: nextPage + lastPage without startAt (changed-worklogs style)
65
+ # - Last page marker in token-based APIs: isLast + array without startAt
39
66
  def cursor_paginated?(body)
40
- body.is_a?(Hash) && body.key?(:nextPageToken)
67
+ return false unless body.is_a?(Hash)
68
+
69
+ cursor_by_token?(body) ||
70
+ cursor_by_cursor?(body) ||
71
+ cursor_by_link?(body) ||
72
+ cursor_last_page_without_token?(body)
73
+ end
74
+
75
+ def cursor_by_token?(body)
76
+ body.key?(:nextPageToken)
77
+ end
78
+
79
+ def cursor_by_cursor?(body)
80
+ body.key?(:nextPageCursor) || body.key?(:cursor)
81
+ end
82
+
83
+ def cursor_by_link?(body)
84
+ body.key?(:nextPage) && body.key?(:lastPage) && !body.key?(:startAt)
85
+ end
86
+
87
+ def cursor_last_page_without_token?(body)
88
+ body.key?(:isLast) && !body.key?(:startAt) && !body.key?(:values) && body.values.any?(Array)
89
+ end
90
+
91
+ def cursor_signature?(body)
92
+ cursor_by_token?(body) || cursor_by_cursor?(body) || cursor_by_link?(body)
93
+ end
94
+
95
+ def offset_values_signature?(body)
96
+ body.key?(:values) && (body.key?(:isLast) || body.key?(:nextPage) || body.key?(:startAt))
97
+ end
98
+
99
+ def offset_generic_signature?(body)
100
+ markers_present = body.key?(:maxResults) ||
101
+ body.key?(:pageSize) ||
102
+ body.key?(:total) ||
103
+ body.key?(:isLast) ||
104
+ body.key?(:nextPage)
105
+
106
+ body.key?(:startAt) && markers_present && body.values.any?(Array)
41
107
  end
42
108
  end
43
109
  end