graphql-armory 0.1.0.pre6 → 0.1.0.pre7

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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 1a108044cb6fe2eeb2557d7d315b3e16e4ff0d31d086b7421a958c3a1d4c664b
4
- data.tar.gz: f756db6daa9fc11ec6b7f1de72757002f75555d9935d1876985aae9f4e6f7690
3
+ metadata.gz: 29e27413e39d1f24ffcc5d1ebf7316170b0ebb935f7d07eb0fd17779358cdbd1
4
+ data.tar.gz: 4db014feb0364b2f67773668f99b961a708a30a142141d96979db7da3fed8321
5
5
  SHA512:
6
- metadata.gz: a4e6bd7f6cb48c4b2a864fbb06a2bf26fdf5a4944478092acfea14769cab1744696759fe930fd35409378f70844aa6a1397c552c3ee2561bf786c3121ddbff53
7
- data.tar.gz: 44fa76ca88941a4ba55b604c04b61e2d5f52b8029e7b97bd918ce8e53f83e692c6f90de7f1bd4b3f4b82cf68f40412abc76cf21e0ddd1e5a9fbf2bf0fb682cb5
6
+ metadata.gz: 3c09fc9ec92e31c68fa01e82fafff46affc1cb2dba224bf0c513d4fb0786904a5bca96ace241a0099cff7b724a80e82738a0cb1361724f3f8c8edb6e2f16165d
7
+ data.tar.gz: 691347bd3ad318eb25bbab16634bf05f03e3587bfc90b8c18e93f75913582aa03ec52435c70c315611f8dc6ea3375a829479b2d8bd84f73d8ac326b7466bffa0
data/CHANGELOG.md CHANGED
@@ -2,6 +2,14 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ## 0.1.0.pre7 (2026-10-30)
6
+
7
+ Keyset connections (roadmap module 5). Docs: `docs/keyset-connections.md`.
8
+
9
+ - Keyset connections: `GraphQL::Armory::Keyset.build(relation)`, returned from a resolver, pages an ActiveRecord relation by its ordering columns instead of OFFSET, so rows inserted or deleted between pages neither skip nor repeat items. The primary key breaks ties. Orderings it cannot page raise `Keyset::ConfigurationError`. A cursor holds the ordering values, so the default Base64 encoder is refused unless `plain_cursors: true`. Types with authorization scope the relation inside the connection. Docs: `docs/keyset-connections.md`.
10
+ - Docs: new section "Clients that change identity" in `docs/rate-limiting.md`. A limit per key does not stop a client that gets a new IP or a new account for every request; the page now says so, shows how to share one bucket among new accounts or put a ceiling on everyone, and lists what belongs before GraphQL (signup limits, verification, network blocking). No code change.
11
+ - Docs: how to count probes against a strict persisted-queries endpoint. Strict mode refuses before validating, so a detector that counts validation errors goes blind; `:operation_refused` with `reason: :raw_query` is the strike to count instead. New section in `docs/persisted-queries.md` and a row in the "What to watch for" table of `docs/telemetry.md`. No code change.
12
+
5
13
  ## 0.1.0.pre6 (2026-10-30)
6
14
 
7
15
  Telemetry for every module, and the processing-time layer of rate limiting. Docs: `docs/telemetry.md`, `docs/rate-limiting.md`.
data/README.md CHANGED
@@ -6,12 +6,12 @@
6
6
 
7
7
  Open-source extensions for [graphql-ruby](https://github.com/rmosolgo/graphql-ruby), built on its public extension points: no fork, no monkey patching. One gem, one module at a time; each module has its own page in [`docs/`](docs) with the problem it solves, how to use it, and its limits.
8
8
 
9
- > **Status: early development.** Prereleases on RubyGems (`0.1.0.pre6`). The API may change before 1.0.
9
+ > **Status: early development.** Prereleases on RubyGems (`0.1.0.pre7`). The API may change before 1.0.
10
10
 
11
11
  ## Install
12
12
 
13
13
  ```ruby
14
- gem "graphql-armory", "~> 0.1.0.pre6" # a prerelease: `gem install graphql-armory --pre`
14
+ gem "graphql-armory", "~> 0.1.0.pre7" # a prerelease: `gem install graphql-armory --pre`
15
15
  gem "pundit" # or "cancancan", for the authorization module
16
16
  ```
17
17
 
@@ -27,7 +27,7 @@ Status: ✅ released, 🚧 in progress, ⬜ not started. Update this table in th
27
27
  | 2 | Encrypted, versioned IDs and cursors | ✅ | [docs/encrypted-ids.md](docs/encrypted-ids.md) | Released in 0.1.0.pre4 (prerelease). `Encoder` (AES-256-GCM), versioned chains and `Legacy`, `Encoder.default` (ENV or Rails), `use GraphQL::Armory::IDs`. Composite primary keys not supported. |
28
28
  | 3 | Persisted queries / operation allowlist | ✅ | [docs/persisted-queries.md](docs/persisted-queries.md) | Released in 0.1.0.pre4 (prerelease). Allowlist from a build manifest (Apollo, Relay), `use GraphQL::Armory::PersistedQueries` with strict mode. A runtime store (database, sync endpoint) is planned for later. |
29
29
  | 4 | Rate limiting | ✅ | [docs/rate-limiting.md](docs/rate-limiting.md) | Released in 0.1.0.pre5 (prerelease); `RateLimits::Time` in 0.1.0.pre6. Points per client (query complexity) and operations at the same time, `MemoryStore` and `RedisStore`, the budget in response extensions and headers. `RateLimits::Time` charges the wall-clock milliseconds operations take. |
30
- | 5 | Stable (keyset) connections | ⬜ | | Research not started. |
30
+ | 5 | Stable (keyset) connections | ✅ | [docs/keyset-connections.md](docs/keyset-connections.md) | Released in 0.1.0.pre7 (prerelease). `Keyset.build(relation)` per resolver, ActiveRecord only, plain non-null columns of the relation's own table. Base64 cursors refused unless `plain_cursors: true`. No total count. |
31
31
  | 6 | Subscriptions over Pusher / Ably | ⬜ | | Research not started. |
32
32
  | 7 | Response caching | ⬜ | | Research not started. |
33
33
  | 8 | API versioning (changesets) | ⬜ | | Research not started. |
@@ -55,7 +55,7 @@ GRAPHQL_VERSION="~> 2.4.0" docker compose run --rm test # another graphq
55
55
  Releases are published from GitHub Actions with RubyGems Trusted Publishing (`.github/workflows/release.yml`): no API key is stored and no OTP is asked. Bump `GraphQL::Armory::VERSION` and the CHANGELOG on `main`, then push the matching tag:
56
56
 
57
57
  ```
58
- git tag v0.1.0.pre6 && git push origin v0.1.0.pre6
58
+ git tag v0.1.0.pre7 && git push origin v0.1.0.pre7
59
59
  ```
60
60
 
61
61
  The workflow checks that the tag matches the version, runs the specs and pushes the gem. It only publishes a tag on a commit of `main`. The `release` environment can require a maintainer's approval first (on a public repository, or a private one on a paid GitHub plan).
@@ -0,0 +1,95 @@
1
+ # Keyset connections
2
+
3
+ Pagination that stays correct while rows come and go.
4
+
5
+ ## The problem
6
+
7
+ graphql-ruby's connection for ActiveRecord pages with `OFFSET`. If a row is inserted or deleted between two pages, every later row moves by one: the client sees a row twice, or never sees it. `OFFSET` also gets slower the deeper the page, because the database still walks the rows it skips.
8
+
9
+ ## The solution
10
+
11
+ `GraphQL::Armory::Keyset` pages by the **values of the ordering columns**. The cursor says "after the row with these values", and the next page is a `WHERE` on them. A row inserted earlier in the list, or the deletion of the cursor's own row, changes nothing.
12
+
13
+ Those values are in the cursor, which creates a risk `OFFSET` cursors do not have. With graphql-ruby's default Base64 cursors, a client could read the value of a column you order by, even one that is not in your schema, and could forge a cursor to search it (`salary > X`, again and again, watching which rows appear). So the default encoder is refused unless you say otherwise.
14
+
15
+ ## How to use it
16
+
17
+ Encrypt your cursors, and return a keyset connection from the resolver of a connection field:
18
+
19
+ ```ruby
20
+ class AppSchema < GraphQL::Schema
21
+ cursor_encoder AppEncoder # a GraphQL::Armory::Encoder subclass
22
+ end
23
+
24
+ class Types::Query < Types::BaseObject
25
+ field :invoices, Types::Invoice.connection_type, null: false
26
+
27
+ def invoices
28
+ GraphQL::Armory::Keyset.build(Invoice.order(created_at: :desc))
29
+ end
30
+ end
31
+ ```
32
+
33
+ graphql-ruby fills in `first`, `after`, `last`, `before` and the page sizes, as for any connection. The rest of your connections keep their `OFFSET`: this is chosen per resolver, and not registered for every relation.
34
+
35
+ If the ordering values are not secret (a public list ordered by id), you can keep readable cursors:
36
+
37
+ ```ruby
38
+ GraphQL::Armory::Keyset.build(Article.order(:id), plain_cursors: true)
39
+ ```
40
+
41
+ ### What it can order by
42
+
43
+ The relation must be ordered by plain, non-null columns of its own table. The primary key is added as the last column, to break ties, so a relation with no order pages by primary key. `build` raises `Keyset::ConfigurationError` for:
44
+
45
+ - a raw SQL or string order (`order("rank ASC")`, `Arel.sql`), an expression, or `nulls_first`;
46
+ - a column of another table;
47
+ - a nullable column: SQL comparisons skip `NULL`, so those rows would be lost;
48
+ - a `float` column: equality on floats is not reliable. Allowed types are integer, string, text, decimal, datetime, date, boolean and uuid;
49
+ - a serialized or encrypted column: the database does not order those by the value a cursor would hold;
50
+ - a relation with `limit`, `offset`, `group` or `select`;
51
+ - a `joins` or `left_joins` without `distinct`, because a join can repeat a row. Add `.distinct`, or filter with a subquery.
52
+
53
+ Add an index on the ordering columns, in that order, ending with the primary key. Without one the database still has to sort.
54
+
55
+ ### With authorization
56
+
57
+ A type that includes `GraphQL::Armory::Authorization::Base` scopes the relation inside the connection, as it does for a plain relation, so the page, `hasNextPage` and `hasPreviousPage` only see rows the user may see. A cursor adds a condition to that scope, so someone else's cursor cannot reach outside it. A scope that answers an Array (CanCanCan's `scope: :in_memory`) has nothing to page and raises `ConfigurationError`.
58
+
59
+ If your own type defines `scope_items`, it receives the `Keyset` object and not a relation. Call `items.rescoped { |relation| ... }` there.
60
+
61
+ ### Testing
62
+
63
+ `Keyset::Controls::Schema.example(base:, cursor_encoder:, max_page_size:)` is a schema with one connection field, `items`, and `Keyset::Controls::Root.example(connection)` is its root value. `IDs::Controls::Encoder.example` is an encoder with a fixed test key. `Keyset.new`, with nothing wired, has no rows, no pages and no cursors.
64
+
65
+ ## Reference
66
+
67
+ `GraphQL::Armory::Keyset.build(relation, plain_cursors: false)`
68
+
69
+ - `relation`: an ActiveRecord relation, checked as above.
70
+ - `plain_cursors:` is `true` or `false`. `true` allows the schema's default Base64 encoder.
71
+
72
+ Errors:
73
+
74
+ | When | What |
75
+ |---|---|
76
+ | Boot or resolver, a relation it cannot page | `Keyset::ConfigurationError` |
77
+ | First page, the schema has the default encoder and no `plain_cursors: true` | `Keyset::ConfigurationError` |
78
+ | A cursor that is tampered, malformed, or made for another ordering | `Invalid ID or cursor`, the same for all |
79
+ | `first` and `last` together | `first and last cannot be used together` |
80
+
81
+ ## Guarantees and limits
82
+
83
+ - Every row present for the whole walk is seen exactly once, whatever is inserted or deleted meanwhile.
84
+ - A row whose ordering value **changes** between pages can be skipped or seen twice: it really moved. Order by columns that do not change (a creation time, an id) when this matters.
85
+ - A row inserted behind the cursor is not seen on the way forward, as in any pagination.
86
+ - The encoder check runs on the first page, not at boot, because the connection reads the encoder from the schema of the query.
87
+ - The check only knows the default Base64 encoder. A custom encoder that does not encrypt passes unnoticed: a keyset cursor is only as private as your `cursor_encoder`.
88
+ - With `plain_cursors: true` a client can read the ordering values and forge a cursor. It stays inside the scope and its values are bound, never interpolated, but it can probe those columns.
89
+ - A forged value on a plain cursor must have the form the column's own cursors have (an Integer, a plain decimal, an ISO 8601 date or time) or it is an invalid cursor. A forged value of the right form is honoured: it pages from there.
90
+ - Encryption keeps length, so the length of an encrypted cursor reveals roughly the length of a string ordering value.
91
+ - A value JSON cannot hold, such as Postgres `infinity` in an ordering column, raises when the cursor is built. Avoid it in columns you order by.
92
+ - A decimal of more than 65 digits on either side of the point, possible only on an unconstrained Postgres `numeric`, gets `Invalid ID or cursor` even on its own cursor. Give the column a precision.
93
+ - On `Execution::Next`, a node type with `reauthorize_scoped_objects(false)` skips `authorized?` even when its scope did not narrow the list. A plain relation does the same: it comes from graphql-ruby. Do not combine that setting with a scope that does not filter.
94
+ - There is no total count. `hasNextPage` costs no extra query going forward without `before`, nor does `hasPreviousPage` going backward without `after`; in the other cases each costs one query, only when the client asks for it.
95
+ - ActiveRecord only. The attributes of the ordering columns must be readable on each row, which is why `select` is refused.
@@ -153,6 +153,22 @@ use GraphQL::Armory::PersistedQueries, store: PERSISTED, sinks: [GraphQL::Armory
153
153
 
154
154
  While you are in `strict: false`, `:raw_query_run` is the traffic still to migrate: turn on `strict: true` when it reaches zero. After a deploy, `:operation_refused` with `:unknown_operation` is a client build whose operations are not in the manifest. Signals never hold the operation id or the query. See [Telemetry](telemetry.md).
155
155
 
156
+ ### Counting probes in strict mode
157
+
158
+ In strict mode a raw query is refused before it is validated, so it never produces a validation error. If your abuse detection counts validation errors (`undefinedField`, `argumentNotAccepted`) to spot someone probing your schema, it sees nothing from a strict endpoint. Count the refusal instead: a legitimate client sends operation ids and never a raw query, so `:operation_refused` with `reason: :raw_query` is a clean strike.
159
+
160
+ ```ruby
161
+ count_probes = lambda do |signal, data|
162
+ next unless signal == :operation_refused && data[:reason] == :raw_query
163
+
164
+ AbuseDetection.strike(Current.client_key) # your detector, with the client from your own request context
165
+ end
166
+
167
+ use GraphQL::Armory::PersistedQueries, store: PERSISTED, strict: true, sinks: [count_probes]
168
+ ```
169
+
170
+ A signal holds only the reason, so the sink reads who sent the request from your own request context, as in [Telemetry](telemetry.md). Do not strike on `:unknown_operation`: after a deploy it is a legitimate client build whose operations are not in the manifest yet. The example has not been run against a live detector.
171
+
156
172
  ### Testing with persisted queries
157
173
 
158
174
  `PersistedQueries::Store::Substitute.new(*queries)` holds the given queries under their SHA-256, like an Apollo manifest, and records the ids it was asked for (`fetched`). `PersistedQueries::Controls::Operations`, `Query.example` and `Root.example` are a small schema and its operations to test against. The decision itself is `PersistedQueries::Gate`: `Gate.build(store:, strict:)` takes the same settings as `use`, and `gate.(context, query_text, document)` answers `[refusal, document]`. `Gate.new`, with nothing wired, refuses every request (`Store::Null`, strict).
@@ -334,6 +334,26 @@ Invalid settings raise `RateLimits::ConfigurationError` at boot.
334
334
  - A query run with its own trace (`context: { trace: ... }`) cannot be charged, so it raises `ConfigurationError`, as with `Concurrency`.
335
335
  - When the store fails, operations run unlimited and `on_store_error` is called; a failed charge never raises into the query (unless your hook does).
336
336
 
337
+ ### Clients that change identity
338
+
339
+ Every key has its own bucket. A client that gets a new key for each request (a new IP from a proxy, or a new disposable account) starts every time with a full bucket, so a limit per key does not stop it. The limiter does not know who owns a key: opening accounts and choosing IPs happens before it, and so does stopping abuse there.
340
+
341
+ What you can do with the gem:
342
+
343
+ - **Share one bucket among the clients you do not trust yet.** Build the key from something that is not free to rotate, such as the age of the account, so every new account draws from the same small budget:
344
+
345
+ ```ruby
346
+ context[:rate_limit_key] = user.created_at > 1.day.ago ? "new-accounts" : "user:#{user.id}"
347
+
348
+ use GraphQL::Armory::RateLimits::Points, store: store, window: 60,
349
+ limit: ->(key, _query) { key == "new-accounts" ? 500 : 1_000 }
350
+ ```
351
+
352
+ The cost is that honest new users share that budget, and a burst from an attacker can use it up for them. Start in soft mode and look at `context[:rate_limit_points]` before you refuse anyone. The example has not been run against a real app.
353
+ - **Put a ceiling on everyone.** A key that is the same for every request (`"all"`) with `Concurrency` or `Time` protects your servers from a flood, whoever sends it. It does not tell clients apart: an attacker can leave honest clients without budget.
354
+
355
+ What this limiter does not do, and you handle before the request reaches GraphQL: limit account creation per IP, subnet or device, verify an email or a phone number before an account can query, block by network reputation, and detect and ban abusive clients. The limiter is the last layer, not a replacement for those.
356
+
337
357
  ## References
338
358
 
339
359
  The same technique, charging queries a calculated cost against a budget per client, is used by large public GraphQL APIs:
data/docs/telemetry.md CHANGED
@@ -107,6 +107,7 @@ The gem does not depend on Datadog or on any other backend. The same shape works
107
107
  | `id_refused` with `reason: :invalid` rising | Someone is sending forged or tampered IDs, or a key rotation left clients with IDs made with a key you dropped | If it follows a deploy, check [Rotating keys](encrypted-ids.md#rotating-keys-and-migrating-from-base64). Otherwise it is probing: nothing leaked, but you can rate limit that client |
108
108
  | `id_refused` with `reason: :not_found` | A record that does not exist, or that is outside the client's scope. The signal is the same for both, as the client's answer is | A few are normal. A burst from one client walking IDs is an enumeration attempt |
109
109
  | `operation_refused` with `reason: :unknown_operation` after a deploy | A client build whose operations are not in the manifest you ship | Deploy the manifest before, or with, the client |
110
+ | `operation_refused` with `reason: :raw_query` from one client | A client sending raw queries to a strict endpoint: a probe, or a client not migrated yet. Strict mode refuses before validating, so a detector that counts validation errors does not see it | Count it as a strike. See [Counting probes in strict mode](persisted-queries.md#counting-probes-in-strict-mode) |
110
111
  | `raw_query_run` while you are in `strict: false` | Traffic that does not use persisted queries yet | When it reaches zero, turn on `strict: true` |
111
112
  | `denied` rising for one `type` | A new or changed policy for that type | Compare with the release; the [audit](authorization.md#the-audit) lists the types and actions the rules cover |
112
113
 
@@ -41,6 +41,8 @@ module GraphQL
41
41
 
42
42
  # Runs before pagination, so connections page and count the scoped list.
43
43
  def scope_items(items, context)
44
+ return items.rescoped { |relation| scope_items(relation, context) } if items.is_a?(Keyset)
45
+
44
46
  super(Integration.scoped(items, armory_rule, context), context)
45
47
  end
46
48
 
@@ -0,0 +1,36 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GraphQL
4
+ module Armory
5
+ class Keyset
6
+ # Test data for keyset connections, reusable by apps and other gems.
7
+ module Controls
8
+ # A schema with one connection field, `items`, that answers what the root value holds.
9
+ module Schema
10
+ def self.example(base: GraphQL::Schema, cursor_encoder: nil, max_page_size: nil)
11
+ item = Class.new(GraphQL::Schema::Object) do
12
+ graphql_name "Item"
13
+ field :id, String, null: false
14
+ end
15
+ root = Class.new(GraphQL::Schema::Object) do
16
+ graphql_name "Query"
17
+ field :items, item.connection_type, null: false
18
+ end
19
+ Class.new(base) do
20
+ query(root)
21
+ cursor_encoder(cursor_encoder) if cursor_encoder
22
+ default_max_page_size(max_page_size) if max_page_size
23
+ end
24
+ end
25
+ end
26
+
27
+ # The root value `Schema.example` reads its connection from.
28
+ module Root
29
+ def self.example(connection)
30
+ Struct.new(:items).new(connection)
31
+ end
32
+ end
33
+ end
34
+ end
35
+ end
36
+ end
@@ -0,0 +1,279 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ module GraphQL
6
+ module Armory
7
+ # A connection that pages an ActiveRecord relation by the values of its ordering columns instead of OFFSET,
8
+ # so rows inserted or deleted between pages neither skip nor repeat items. Return it from a resolver:
9
+ #
10
+ # def invoices
11
+ # GraphQL::Armory::Keyset.build(Invoice.order(created_at: :desc))
12
+ # end
13
+ #
14
+ # A cursor holds the row's ordering values. Base64 cursors would let a client read them and forge them to
15
+ # search a column it cannot see, so the schema's default encoder is refused unless `plain_cursors: true`.
16
+ class Keyset < GraphQL::Pagination::Connection
17
+ class ConfigurationError < Armory::Error; end
18
+
19
+ CURSOR_VERSION = 1
20
+ PAGEABLE_TYPES = %i[integer string text decimal datetime date boolean uuid].freeze
21
+
22
+ # The forms this connection's own cursors have. A forged decimal like 1e99999999999 would exhaust memory.
23
+ DECIMAL_FORM = /\A-?\d{1,65}(\.\d{1,65})?\z/
24
+ DATE_FORM = /\A\d{4}-\d{2}-\d{2}\z/
25
+ DATETIME_FORM = /\A\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,9})?(Z|[+-]\d{2}:\d{2})\z/
26
+
27
+ Column = Struct.new(:name, :direction, :attribute, :type, keyword_init: true)
28
+
29
+ # Reads what a relation is ordered by, adds the primary key as the tie-breaker, and refuses what it cannot page.
30
+ module Ordering
31
+ def self.call(relation)
32
+ refuse("a limit") if relation.limit_value
33
+ refuse("an offset") if relation.offset_value
34
+ refuse("a group") if relation.group_values.any?
35
+ refuse("a select") if relation.select_values.any?
36
+ refuse("a join that is not distinct: it can repeat rows") if joined?(relation) && !relation.distinct_value
37
+
38
+ columns = relation.order_values.map { |order| column(relation.klass, order) }.uniq(&:name)
39
+ primary_key = Array(relation.klass.primary_key)
40
+ refuse("a model without a primary key") if primary_key.empty?
41
+
42
+ direction = columns.last&.direction || :asc
43
+ (primary_key - columns.map(&:name)).each { |name| columns << column_named(relation.klass, name, direction) }
44
+ columns.freeze
45
+ end
46
+
47
+ def self.joined?(relation)
48
+ relation.joins_values.any? || relation.left_outer_joins_values.any?
49
+ end
50
+
51
+ def self.column(klass, order)
52
+ direction = { Arel::Nodes::Ascending => :asc, Arel::Nodes::Descending => :desc }[order.class]
53
+ attribute = order.expr if direction
54
+ refuse("an order that is not a plain column: #{order.class}") unless attribute.is_a?(Arel::Attributes::Attribute)
55
+ refuse("an order on another table: #{attribute.relation.name}") unless attribute.relation.name == klass.table_name
56
+
57
+ column_named(klass, attribute.name.to_s, direction)
58
+ end
59
+
60
+ def self.column_named(klass, name, direction)
61
+ definition = klass.columns_hash[name]
62
+ refuse("an order on an unknown column: #{name}") if definition.nil?
63
+ refuse("an order on a nullable column: #{name}") if definition.null && klass.primary_key != name
64
+
65
+ type = klass.type_for_attribute(name)
66
+ refuse("an order on a #{type.type} column: #{name}") unless PAGEABLE_TYPES.include?(type.type)
67
+ refuse("an order on a serialized or encrypted column: #{name}") if transformed?(type)
68
+
69
+ Column.new(name: name, direction: direction, attribute: klass.arel_table[name], type: type)
70
+ end
71
+
72
+ # These report the type they store as, but the database does not order them by the value a cursor holds.
73
+ # `normalizes` wraps the type it is declared over, so the wrapped types count too.
74
+ def self.transformed?(type)
75
+ return true if type.is_a?(ActiveRecord::Type::Serialized) || type.is_a?(ActiveRecord::Encryption::EncryptedAttributeType)
76
+
77
+ type.respond_to?(:cast_type) && transformed?(type.cast_type)
78
+ end
79
+
80
+ def self.refuse(what)
81
+ raise ConfigurationError, "a keyset connection cannot page #{what}"
82
+ end
83
+ end
84
+
85
+ attr_reader :columns
86
+
87
+ # Checks the relation and its ordering; resolvers go through here.
88
+ def self.build(relation, plain_cursors: false)
89
+ raise ConfigurationError, "plain_cursors: must be true or false, got #{plain_cursors.inspect}" unless [true, false].include?(plain_cursors)
90
+ raise ConfigurationError, "a keyset connection needs an ActiveRecord relation, got #{relation.class}" unless relation.respond_to?(:order_values)
91
+
92
+ new(relation, columns: Ordering.(relation), plain_cursors: plain_cursors)
93
+ end
94
+
95
+ # `new` is inert: with no relation it has no rows, no pages and no cursors.
96
+ def initialize(items = nil, columns: [], plain_cursors: false, **options)
97
+ super(columns.empty? ? nil : items, **options)
98
+ @columns = columns
99
+ @plain_cursors = plain_cursors
100
+ end
101
+
102
+ # This connection over the relation the block answers: how a type's scope reaches the rows. A scope that did
103
+ # not change the relation answers the same object, so graphql-ruby does not take the list as narrowed.
104
+ def rescoped
105
+ return self if items.nil?
106
+
107
+ relation = yield(items)
108
+ return self if relation.equal?(items)
109
+
110
+ dup.scope_to(relation, self.class.build(relation, plain_cursors: @plain_cursors).columns)
111
+ end
112
+
113
+ def nodes
114
+ load_page
115
+ @nodes
116
+ end
117
+
118
+ def has_next_page
119
+ return false if items.nil?
120
+
121
+ load_page
122
+ return @more if !@backward && before.nil?
123
+ return false if @backward && before.nil?
124
+
125
+ anchor = @nodes.last
126
+ anchor ? beyond?(key_of(anchor), :after) : beyond?(@before_key, :after, inclusive: true)
127
+ end
128
+
129
+ def has_previous_page
130
+ return false if items.nil?
131
+
132
+ load_page
133
+ return @more if @backward && after.nil?
134
+ return false if !@backward && after.nil?
135
+
136
+ anchor = @nodes.first
137
+ anchor ? beyond?(key_of(anchor), :before) : beyond?(@after_key, :before, inclusive: true)
138
+ end
139
+
140
+ def cursor_for(item)
141
+ return nil if items.nil?
142
+
143
+ refuse_plain_cursors
144
+ values = columns.map { |column| dump(column.type.serialize(item[column.name])) }
145
+ encode(JSON.generate("v" => CURSOR_VERSION, "o" => fingerprint, "k" => values))
146
+ end
147
+
148
+ protected
149
+
150
+ def scope_to(relation, columns)
151
+ @items = relation
152
+ @columns = columns
153
+ self
154
+ end
155
+
156
+ private
157
+
158
+ def load_page
159
+ return if defined?(@nodes)
160
+
161
+ return @nodes = [] if items.nil?
162
+
163
+ refuse_plain_cursors
164
+ raise GraphQL::ExecutionError, "first and last cannot be used together" if first_value && last_value
165
+
166
+ @after_key = after && key_from(after)
167
+ @before_key = before && key_from(before)
168
+ @backward = !last_value.nil?
169
+ limit = @backward ? last : first
170
+
171
+ relation = items
172
+ relation = relation.where(condition(@after_key, :after)) if @after_key
173
+ relation = relation.where(condition(@before_key, :before)) if @before_key
174
+ relation = relation.reorder(columns.map { |column| arel_order(column) })
175
+ relation = relation.limit(limit + 1) if limit
176
+
177
+ rows = relation.to_a
178
+ @more = !limit.nil? && rows.size > limit
179
+ rows = rows.first(limit) if limit
180
+ @nodes = @backward ? rows.reverse : rows
181
+ end
182
+
183
+ def refuse_plain_cursors
184
+ return if @plain_cursors
185
+
186
+ encoder = context&.schema&.cursor_encoder
187
+ return unless encoder.nil? || encoder == GraphQL::Schema::Base64Encoder
188
+
189
+ raise ConfigurationError,
190
+ "a keyset cursor holds the row's ordering values: set an encrypting cursor_encoder on the schema " \
191
+ "(GraphQL::Armory::Encoder), or pass plain_cursors: true if those values are not secret"
192
+ end
193
+
194
+ def arel_order(column)
195
+ forward = column.direction == :asc
196
+ forward = !forward if @backward
197
+ forward ? column.attribute.asc : column.attribute.desc
198
+ end
199
+
200
+ def beyond?(key, side, inclusive: false)
201
+ items.where(condition(key, side, inclusive: inclusive)).exists?
202
+ end
203
+
204
+ # (a > x) OR (a = x AND b > y) OR ...: the rows past `key` on `side`, for any mix of directions.
205
+ def condition(key, side, inclusive: false)
206
+ pairs = columns.zip(key)
207
+ branches = pairs.each_index.map do |index|
208
+ column, value = pairs[index]
209
+ ascending = (column.direction == :asc) == (side == :after)
210
+ past = ascending ? column.attribute.gt(value) : column.attribute.lt(value)
211
+ pairs.first(index).reverse_each.inject(past) { |node, (earlier, equal)| earlier.attribute.eq(equal).and(node) }
212
+ end
213
+ branches << pairs.map { |column, value| column.attribute.eq(value) }.inject(:and) if inclusive
214
+ branches.inject(:or)
215
+ end
216
+
217
+ def key_of(record)
218
+ columns.map { |column| record[column.name] }
219
+ end
220
+
221
+ def fingerprint
222
+ columns.map { |column| "#{column.attribute.relation.name}.#{column.name}:#{column.direction}" }.join(",")
223
+ end
224
+
225
+ def dump(value)
226
+ return value.getutc.iso8601(9) if value.respond_to?(:getutc)
227
+
228
+ case value
229
+ when BigDecimal then value.to_s("F")
230
+ when Date then value.iso8601
231
+ else value
232
+ end
233
+ end
234
+
235
+ # Every cursor that cannot be honoured answers the same error, whatever is wrong with it.
236
+ def key_from(cursor)
237
+ payload = JSON.parse(decoded(cursor))
238
+ raise Encoder::InvalidError unless payload.is_a?(Hash) && payload["v"] == CURSOR_VERSION && payload["o"] == fingerprint
239
+
240
+ values = payload["k"]
241
+ raise Encoder::InvalidError unless values.is_a?(Array) && values.size == columns.size
242
+
243
+ columns.zip(values).map { |column, value| load_value(column, value) }
244
+ rescue JSON::ParserError, EncodingError, ActiveModel::RangeError
245
+ raise Encoder::InvalidError
246
+ end
247
+
248
+ # Anything a custom encoder raises on a bad cursor, or a nil it answers, is one more invalid cursor.
249
+ def decoded(cursor)
250
+ decode(cursor).dup.force_encoding(Encoding::UTF_8).tap { |text| raise Encoder::InvalidError unless text.valid_encoding? }
251
+ rescue StandardError
252
+ raise Encoder::InvalidError
253
+ end
254
+
255
+ def well_formed?(kind, value)
256
+ case kind
257
+ when :integer then value.is_a?(Integer)
258
+ when :boolean then value == true || value == false
259
+ when :decimal then value.is_a?(String) && DECIMAL_FORM.match?(value)
260
+ when :date then value.is_a?(String) && DATE_FORM.match?(value)
261
+ when :datetime then value.is_a?(String) && DATETIME_FORM.match?(value)
262
+ else value.is_a?(String) && !value.include?("\0")
263
+ end
264
+ end
265
+
266
+ def load_value(column, value)
267
+ raise Encoder::InvalidError unless well_formed?(column.type.type, value)
268
+
269
+ cast = column.type.cast(value)
270
+ raise Encoder::InvalidError if cast.nil?
271
+
272
+ column.type.serialize(cast)
273
+ cast
274
+ end
275
+ end
276
+ end
277
+ end
278
+
279
+ require "graphql/armory/keyset/controls"
@@ -2,6 +2,6 @@
2
2
 
3
3
  module GraphQL
4
4
  module Armory
5
- VERSION = "0.1.0.pre6"
5
+ VERSION = "0.1.0.pre7"
6
6
  end
7
7
  end
@@ -16,3 +16,4 @@ require "graphql/armory/authorization"
16
16
  require "graphql/armory/ids"
17
17
  require "graphql/armory/persisted_queries"
18
18
  require "graphql/armory/rate_limits"
19
+ require "graphql/armory/keyset"
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: graphql-armory
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.0.pre6
4
+ version: 0.1.0.pre7
5
5
  platform: ruby
6
6
  authors:
7
7
  - Israel
@@ -43,6 +43,7 @@ files:
43
43
  - README.md
44
44
  - docs/authorization.md
45
45
  - docs/encrypted-ids.md
46
+ - docs/keyset-connections.md
46
47
  - docs/persisted-queries.md
47
48
  - docs/rate-limiting.md
48
49
  - docs/telemetry.md
@@ -84,6 +85,8 @@ files:
84
85
  - lib/graphql/armory/encoder/versioned.rb
85
86
  - lib/graphql/armory/ids.rb
86
87
  - lib/graphql/armory/ids/controls.rb
88
+ - lib/graphql/armory/keyset.rb
89
+ - lib/graphql/armory/keyset/controls.rb
87
90
  - lib/graphql/armory/persisted_queries.rb
88
91
  - lib/graphql/armory/persisted_queries/controls.rb
89
92
  - lib/graphql/armory/persisted_queries/manifest.rb