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.



83
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
# File 'lib/dispatch_policy/cursor_pagination.rb', line 83

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. The numeric columns (pending_count, total_admitted)
  # need a Numeric; everything else compares as text (partition_key, or
  # the ISO8601 timestamps emitted by #extract). A mismatch — e.g. a
  # numeric value forged for a timestamp sort — would raise PG error;
  # instead we fall back to the first page.
  numeric_column = %w[pending_count total_admitted].include?(sort[:cursor_sql])
  return scope unless numeric_column ? value.is_a?(Numeric) : value.is_a?(String)

  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



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

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



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

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).



113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
# File 'lib/dispatch_policy/cursor_pagination.rb', line 113

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

.serialize_value(v) ⇒ Object



130
131
132
133
134
135
# File 'lib/dispatch_policy/cursor_pagination.rb', line 130

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

.sort_for(name) ⇒ Object



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

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