Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Replace custom cursor encoding with OpaqueCursor #366

Merged
merged 2 commits into from
Dec 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@ Versioning](https://semver.org/spec/v2.0.0.html).

### Changed

- Updated the encoding and decoding method for GraphQL cursors by removing
`graphql::encode_cursor` and `graphql::decode_cursor` methods and replacing
them with the encoding and decoding methods of `OpaqueCursor`.
- The paginated GraphQL queries use different representations for cursors. The
cursor values obtained from earlier versions of the API are not compatible
with the new cursor values.

### Fixed

Expand Down
1 change: 0 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ bincode = "1"
chrono = { version = ">=0.4.35", default-features = false, features = [
"serde",
] }
data-encoding = "2"
futures = "0.3"
futures-util = "0.3"
http = "1"
Expand Down
2 changes: 0 additions & 2 deletions src/graphql.rs
Original file line number Diff line number Diff line change
Expand Up @@ -270,8 +270,6 @@ where

#[derive(Debug, thiserror::Error)]
enum Error {
#[error("Invalid cursor")]
InvalidCursor,
#[error("The value of first and last must be within 0-100")]
InvalidLimitValue,
#[error("You must provide a `first` or `last` value to properly paginate a connection.")]
Expand Down
18 changes: 9 additions & 9 deletions src/graphql/cluster.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::sync::Arc;

use async_graphql::{
connection::{Connection, Edge, EmptyFields},
connection::{Connection, Edge, EmptyFields, OpaqueCursor},
types::ID,
ComplexObject, Context, Object, Result, SimpleObject, StringNumber,
};
Expand All @@ -17,7 +17,7 @@
get_trend,
model::{ModelDigest, TopElementCountsByColumn},
qualifier::Qualifier,
slicing::{self, IndexedKey},
slicing,
status::Status,
Role, RoleGuard, DEFAULT_CUTOFF_RATE, DEFAULT_TRENDI_ORDER,
};
Expand Down Expand Up @@ -46,7 +46,7 @@
before: Option<String>,
first: Option<i32>,
last: Option<i32>,
) -> Result<Connection<IndexedKey<i64>, Cluster, ClusterTotalCount, EmptyFields>> {
) -> Result<Connection<OpaqueCursor<(i32, i64)>, Cluster, ClusterTotalCount, EmptyFields>> {

Check warning on line 49 in src/graphql/cluster.rs

View check run for this annotation

Codecov / codecov/patch

src/graphql/cluster.rs#L49

Added line #L49 was not covered by tests
let model = model.as_str().parse()?;
let categories = try_id_args_into_ints(categories)?;
let detectors = try_id_args_into_ints(detectors)?;
Expand Down Expand Up @@ -357,11 +357,11 @@
detectors: Option<Vec<i32>>,
qualifiers: Option<Vec<i32>>,
statuses: Option<Vec<i32>>,
after: Option<IndexedKey<i64>>,
before: Option<IndexedKey<i64>>,
after: Option<OpaqueCursor<(i32, i64)>>,
before: Option<OpaqueCursor<(i32, i64)>>,

Check warning on line 361 in src/graphql/cluster.rs

View check run for this annotation

Codecov / codecov/patch

src/graphql/cluster.rs#L360-L361

Added lines #L360 - L361 were not covered by tests
first: Option<usize>,
last: Option<usize>,
) -> Result<Connection<IndexedKey<i64>, Cluster, ClusterTotalCount, EmptyFields>> {
) -> Result<Connection<OpaqueCursor<(i32, i64)>, Cluster, ClusterTotalCount, EmptyFields>> {

Check warning on line 364 in src/graphql/cluster.rs

View check run for this annotation

Codecov / codecov/patch

src/graphql/cluster.rs#L364

Added line #L364 was not covered by tests
let is_first = first.is_some();
let limit = slicing::len(first, last)?;
let db = ctx.data::<Database>()?;
Expand All @@ -372,8 +372,8 @@
detectors.as_deref(),
qualifiers.as_deref(),
statuses.as_deref(),
&after.map(Into::into),
&before.map(Into::into),
&after.map(|c| c.0),
&before.map(|c| c.0),

Check warning on line 376 in src/graphql/cluster.rs

View check run for this annotation

Codecov / codecov/patch

src/graphql/cluster.rs#L375-L376

Added lines #L375 - L376 were not covered by tests
is_first,
limit,
)
Expand All @@ -393,7 +393,7 @@
);
connection.edges.extend(rows.into_iter().map(|c| {
Edge::new(
IndexedKey::new(c.id, c.size),
OpaqueCursor((c.id, c.size)),

Check warning on line 396 in src/graphql/cluster.rs

View check run for this annotation

Codecov / codecov/patch

src/graphql/cluster.rs#L396

Added line #L396 was not covered by tests
Cluster {
id: c.id,
name: c.cluster_id,
Expand Down
27 changes: 10 additions & 17 deletions src/graphql/model.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::sync::Arc;

use async_graphql::{
connection::{Connection, Edge, EmptyFields},
connection::{Connection, Edge, EmptyFields, OpaqueCursor},
types::ID,
Context, Object, Result, SimpleObject, StringNumber,
};
Expand All @@ -12,11 +12,8 @@
use tokio::sync::RwLock;

use super::{
cluster::TimeCount,
data_source::DataSource,
fill_vacant_time_slots, get_trend,
slicing::{self, IndexedKey},
Role, RoleGuard, DEFAULT_CUTOFF_RATE, DEFAULT_TRENDI_ORDER,
cluster::TimeCount, data_source::DataSource, fill_vacant_time_slots, get_trend, slicing, Role,
RoleGuard, DEFAULT_CUTOFF_RATE, DEFAULT_TRENDI_ORDER,
};
use crate::graphql::query;

Expand All @@ -40,7 +37,8 @@
before: Option<String>,
first: Option<i32>,
last: Option<i32>,
) -> Result<Connection<IndexedKey<String>, ModelDigest, ModelTotalCount, EmptyFields>> {
) -> Result<Connection<OpaqueCursor<(i32, String)>, ModelDigest, ModelTotalCount, EmptyFields>>
{

Check warning on line 41 in src/graphql/model.rs

View check run for this annotation

Codecov / codecov/patch

src/graphql/model.rs#L40-L41

Added lines #L40 - L41 were not covered by tests
query(
after,
before,
Expand Down Expand Up @@ -902,29 +900,24 @@

async fn load(
ctx: &Context<'_>,
after: Option<IndexedKey<String>>,
before: Option<IndexedKey<String>>,
after: Option<OpaqueCursor<(i32, String)>>,
before: Option<OpaqueCursor<(i32, String)>>,

Check warning on line 904 in src/graphql/model.rs

View check run for this annotation

Codecov / codecov/patch

src/graphql/model.rs#L903-L904

Added lines #L903 - L904 were not covered by tests
first: Option<usize>,
last: Option<usize>,
) -> Result<Connection<IndexedKey<String>, ModelDigest, ModelTotalCount, EmptyFields>> {
) -> Result<Connection<OpaqueCursor<(i32, String)>, ModelDigest, ModelTotalCount, EmptyFields>> {

Check warning on line 907 in src/graphql/model.rs

View check run for this annotation

Codecov / codecov/patch

src/graphql/model.rs#L907

Added line #L907 was not covered by tests
let is_first = first.is_some();
let limit = slicing::len(first, last)?;
let db = ctx.data::<Database>()?;
let rows = db
.load_models(
&after.map(Into::into),
&before.map(Into::into),
is_first,
limit,
)
.load_models(&after.map(|c| c.0), &before.map(|c| c.0), is_first, limit)

Check warning on line 912 in src/graphql/model.rs

View check run for this annotation

Codecov / codecov/patch

src/graphql/model.rs#L912

Added line #L912 was not covered by tests
.await?;

let (rows, has_previous, has_next) = slicing::page_info(is_first, limit, rows);
let mut connection =
Connection::with_additional_fields(has_previous, has_next, ModelTotalCount);
connection.edges.extend(
rows.into_iter()
.map(|model| Edge::new(IndexedKey::new(model.id, model.name.clone()), model.into())),
.map(|model| Edge::new(OpaqueCursor((model.id, model.name.clone())), model.into())),

Check warning on line 920 in src/graphql/model.rs

View check run for this annotation

Codecov / codecov/patch

src/graphql/model.rs#L920

Added line #L920 was not covered by tests
);
Ok(connection)
}
43 changes: 0 additions & 43 deletions src/graphql/slicing.rs
Original file line number Diff line number Diff line change
@@ -1,48 +1,5 @@
use std::{fmt, str::FromStr};

use async_graphql::connection::CursorType;
use data_encoding::BASE64;

use super::Error;

pub(super) struct IndexedKey<T> {
pub(crate) id: i32,
pub(crate) value: T,
}

impl<T> IndexedKey<T> {
pub fn new(id: i32, value: T) -> Self {
Self { id, value }
}
}

impl<T> From<IndexedKey<T>> for (i32, T) {
fn from(key: IndexedKey<T>) -> Self {
(key.id, key.value)
}
}

impl<T: FromStr + fmt::Display> CursorType for IndexedKey<T> {
type Error = super::Error;

fn decode_cursor(s: &str) -> Result<Self, Self::Error> {
let decoded = String::from_utf8(
BASE64
.decode(s.as_bytes())
.map_err(|_| Error::InvalidCursor)?,
)
.map_err(|_| Error::InvalidCursor)?;
let (id, value) = decoded.split_once(':').ok_or(Error::InvalidCursor)?;
let id = id.parse().map_err(|_| Error::InvalidCursor)?;
let value = value.parse::<T>().map_err(|_| Error::InvalidCursor)?;
Ok(Self { id, value })
}

fn encode_cursor(&self) -> String {
BASE64.encode(format!("{}:{}", self.id, self.value).as_bytes())
}
}

// This internal method should be called after validating pagination paramerters by either
// `grapqhl::query` or `grapqhl::query_with_constraints`.
pub(crate) fn len(first: Option<usize>, last: Option<usize>) -> Result<usize, Error> {
Expand Down
19 changes: 8 additions & 11 deletions src/graphql/statistics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,7 @@
use review_database::{BatchInfo, Database};
use serde_json::Value as JsonValue;

use super::{
slicing::{self, IndexedKey},
Role, RoleGuard,
};
use super::{slicing, Role, RoleGuard};
use crate::graphql::{query, query_with_constraints};

#[derive(Default)]
Expand Down Expand Up @@ -50,7 +47,7 @@
last: Option<i32>,
) -> Result<
Connection<
IndexedKey<i64>,
OpaqueCursor<(i32, i64)>,

Check warning on line 50 in src/graphql/statistics.rs

View check run for this annotation

Codecov / codecov/patch

src/graphql/statistics.rs#L50

Added line #L50 was not covered by tests
Round,
TotalCountByCluster,
EmptyFields,
Expand Down Expand Up @@ -172,13 +169,13 @@
async fn load_rounds_by_cluster(
ctx: &Context<'_>,
cluster: i32,
after: Option<IndexedKey<i64>>,
before: Option<IndexedKey<i64>>,
after: Option<OpaqueCursor<(i32, i64)>>,
before: Option<OpaqueCursor<(i32, i64)>>,

Check warning on line 173 in src/graphql/statistics.rs

View check run for this annotation

Codecov / codecov/patch

src/graphql/statistics.rs#L172-L173

Added lines #L172 - L173 were not covered by tests
first: Option<usize>,
last: Option<usize>,
) -> Result<
Connection<
IndexedKey<i64>,
OpaqueCursor<(i32, i64)>,

Check warning on line 178 in src/graphql/statistics.rs

View check run for this annotation

Codecov / codecov/patch

src/graphql/statistics.rs#L178

Added line #L178 was not covered by tests
Round,
TotalCountByCluster,
EmptyFields,
Expand All @@ -192,8 +189,8 @@
let (model, batches) = db
.load_rounds_by_cluster(
cluster,
&after.map(|k| i64_to_naive_date_time(k.value)),
&before.map(|k| i64_to_naive_date_time(k.value)),
&after.map(|k| i64_to_naive_date_time(k.0 .1)),
&before.map(|k| i64_to_naive_date_time(k.0 .1)),

Check warning on line 193 in src/graphql/statistics.rs

View check run for this annotation

Codecov / codecov/patch

src/graphql/statistics.rs#L192-L193

Added lines #L192 - L193 were not covered by tests
is_first,
limit + 1,
)
Expand Down Expand Up @@ -222,7 +219,7 @@
connection.edges.extend(
batch_infos
.into_iter()
.map(|row| Edge::new(IndexedKey::new(cluster, row.inner.id), row.into())),
.map(|row| Edge::new(OpaqueCursor((cluster, row.inner.id)), row.into())),

Check warning on line 222 in src/graphql/statistics.rs

View check run for this annotation

Codecov / codecov/patch

src/graphql/statistics.rs#L222

Added line #L222 was not covered by tests
);
Ok(connection)
}
Expand Down
Loading