Module: DispatchPolicy::CursorPagination

Defined in:
lib/dispatch_policy/cursor_pagination.rb

Overview

Tiny keyset-pagination helper for the engine UI. Each sort mode declares a single sortable column plus the row id as a deterministic tiebreaker so two rows can never share the same cursor. NULLable columns are coalesced to a sentinel (‘1970-01-01’ for timestamps) so the cursor clause stays a simple tuple comparison.

Constant Summary collapse

SENTINEL_TS =
"1970-01-01 00:00:00".freeze
SORTS =

name => { sql_order:, cursor_sql:, direction:, label: } cursor_sql is the expression to extract the sort key for a row (used both in ORDER BY and to build the cursor tuple).

{
  "pending" => {
    sql_order:  "pending_count DESC, id ASC",
    cursor_sql: "pending_count",
    direction:  :desc,
    label:      "pending desc"
  },
  "admitted" => {
    sql_order:  "total_admitted DESC, id ASC",
    cursor_sql: "total_admitted",
    direction:  :desc,
    label:      "lifetime admitted"
  },
  "stale" => {
    sql_order:  "COALESCE(last_checked_at, TIMESTAMP '#{SENTINEL_TS}') ASC, id ASC",
    cursor_sql: "COALESCE(last_checked_at, TIMESTAMP '#{SENTINEL_TS}')",
    direction:  :asc,
    label:      "stalest (round-trip)"
  },
  "recent" => {
    sql_order:  "COALESCE(last_admit_at, TIMESTAMP '#{SENTINEL_TS}') DESC, id ASC",
    cursor_sql: "COALESCE(last_admit_at, TIMESTAMP '#{SENTINEL_TS}')",
    direction:  :desc,
    label:      "recent admit"
  },
  "key" => {
    sql_order:  "partition_key ASC, id ASC",
    cursor_sql: "partition_key",
    direction:  :asc,
    label:      "partition key"
  }
}.freeze
DEFAULT_SORT =
"pending"

Class Method Summary collapse

Class Method Details

.apply(scope, sort_name, cursor) ⇒ Object

Apply a cursor tuple (value, id) to an AR scope under the given sort. The tiebreaker on id is always ASC so id strictly advances forward.



84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
# File 'lib/dispatch_policy/cursor_pagination.rb', line 84

def apply(scope, sort_name, cursor)
  sort = sort_for(sort_name)
  return scope if cursor.nil?

  value, last_id = cursor
  # Ignore a cursor whose value type can't be compared against this
  # sort's column. A mismatch — e.g. a numeric value forged for a
  # timestamp sort — would raise a PG error; instead we fall back to the
  # first page.
  numeric_column   = %w[pending_count total_admitted].include?(sort[:cursor_sql])
  timestamp_column = sort[:cursor_sql].start_with?("COALESCE(")
  if numeric_column
    return scope unless value.is_a?(Numeric)
  elsif timestamp_column
    # Bound against a timestamp column: a non-parseable string (e.g. a
    # hand-forged "zzz") would raise `invalid input syntax for type
    # timestamp` and 500. Require a real ISO8601 value — exactly what
    # #extract emits — or fall back to the first page.
    return scope unless value.is_a?(String) && parseable_timestamp?(value)
  else
    return scope unless value.is_a?(String)
  end

  case sort[:direction]
  when :desc
    scope.where(
      "(#{sort[:cursor_sql]} < ?) OR (#{sort[:cursor_sql]} = ? AND id > ?)",
      value, value, last_id
    )
  when :asc
    scope.where(
      "(#{sort[:cursor_sql]} > ?) OR (#{sort[:cursor_sql]} = ? AND id > ?)",
      value, value, last_id
    )
  end
end

.decode(cursor) ⇒ Object



64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/dispatch_policy/cursor_pagination.rb', line 64

def decode(cursor)
  return nil if cursor.nil? || cursor.empty?

  decoded = JSON.parse(Base64.urlsafe_decode64(cursor))
  return nil unless decoded.is_a?(Array) && decoded.size == 2

  # The cursor is attacker-controllable (a query param). Reject anything
  # that isn't a (scalar value, integer id) tuple so a hostile payload
  # like [[1,2], {}] can't reach the WHERE clause and raise a 500 (or
  # worse). Per-column type compatibility is enforced in #apply.
  value, id = decoded
  return nil unless (value.is_a?(String) || value.is_a?(Numeric)) && id.is_a?(Integer)

  decoded
rescue StandardError
  nil
end

.encode(value, id) ⇒ Object



60
61
62
# File 'lib/dispatch_policy/cursor_pagination.rb', line 60

def encode(value, id)
  Base64.urlsafe_encode64(JSON.dump([value, id]), padding: false)
end

.extract(row, sort_name) ⇒ Object

Read the cursor key from a row using the given sort. Returns the raw value the cursor was built from (for emitting to the next link).



123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
# File 'lib/dispatch_policy/cursor_pagination.rb', line 123

def extract(row, sort_name)
  sort = sort_for(sort_name)
  column = sort[:cursor_sql]
  # cursor_sql may include a COALESCE(...). For row-side extraction we
  # mirror that with Ruby. The columns we coalesce are timestamps; we
  # use Time.at(0) as the equivalent sentinel.
  raw = case column
        when "pending_count", "total_admitted", "partition_key"
          row.send(column)
        when /COALESCE\(last_checked_at,/
          row.last_checked_at || Time.at(0)
        when /COALESCE\(last_admit_at,/
          row.last_admit_at   || Time.at(0)
        end
  [serialize_value(raw), row.id]
end

.parseable_timestamp?(str) ⇒ Boolean

Returns:

  • (Boolean)


147
148
149
150
151
152
# File 'lib/dispatch_policy/cursor_pagination.rb', line 147

def parseable_timestamp?(str)
  Time.iso8601(str)
  true
rescue ArgumentError, TypeError
  false
end

.serialize_value(v) ⇒ Object



140
141
142
143
144
145
# File 'lib/dispatch_policy/cursor_pagination.rb', line 140

def serialize_value(v)
  case v
  when Time, ActiveSupport::TimeWithZone then v.utc.iso8601(6)
  else v
  end
end

.sort_for(name) ⇒ Object



56
57
58
# File 'lib/dispatch_policy/cursor_pagination.rb', line 56

def sort_for(name)
  SORTS[name] || SORTS.fetch(DEFAULT_SORT)
end