Skip to content
Open
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
39 changes: 39 additions & 0 deletions .callstack.yml
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
pr_review:
# Default: true
auto_run: true
modules:
# Automatically create a description summarizing the changes in pull request.
description:
enabled: true
diagram: false

# Find potential bugs in pull request changes or related files.
bug_hunter:
enabled: true
# Include fixes to possible bugs.
suggestions: true

# Suggest improvements to added code.
code_suggestions:
enabled: true

# Suggest changes to follow defined code conventions.
code_conventions:
enabled: false
# Describe your code conventions in plain text.
conventions: |
E.g. Exported variables, functions, classes and methods should be defined before private.


# Point out any typos or grammatical errors in variable names, texts, comments.
grammar:
enabled: false

# Suggest performance improvements to added code.
performance:
enabled: true

# Find potential security issues in added code.
security:
enabled: true

29 changes: 29 additions & 0 deletions .github/workflows/callstack-reviewer.yml
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
name: Callstack.ai PR Review

on:
workflow_dispatch:
inputs:
config:
type: string
description: "config for reviewer"
required: true
head:
type: string
description: "head commit sha"
required: true
base:
type: string
description: "base commit sha"
required: false

jobs:
callstack_pr_review_job:
runs-on: ubuntu-latest
steps:
- name: Review PR
uses: callstackai/action@main
with:
config: ${{ inputs.config }}
head: ${{ inputs.head }}
export: /code/chats.json

4 changes: 2 additions & 2 deletions cli/crates/federated-dev/src/dev/gateway_nanny.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -108,7 +108,7 @@ pub struct CliRuntime {

impl engine_v2::Runtime for CliRuntime {
type Hooks = ();
type CacheFactory = ();
type OperationCacheFactory = ();

fn fetcher(&self) -> &runtime::fetch::Fetcher {
&self.fetcher
Expand All@@ -130,7 +130,7 @@ impl engine_v2::Runtime for CliRuntime {
&()
}

fn cache_factory(&self) -> &() {
fn operation_cache_factory(&self) -> &() {
&()
}

Expand Down
37 changes: 11 additions & 26 deletions engine/crates/engine-v2/src/engine.rs
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
use ::runtime::{
auth::AccessToken,
hooks::Hooks,
hot_cache::{CachedDataKind, HotCache, HotCacheFactory},
operation_cache::{OperationCache, OperationCacheFactory},
rate_limiting::RateLimitKey,
};
use async_runtime::stream::StreamExt as _;
Expand All@@ -27,7 +27,7 @@ use web_time::Instant;

use crate::{
execution::{ExecutableOperation, PreExecutionContext},
http_response::{HttpGraphqlResponse, HttpGraphqlResponseExtraMetadata},
http_response::HttpGraphqlResponse,
operation::{Operation, PreparedOperation, Variables},
response::{ErrorCode, GraphqlError, Response},
websocket,
Expand DownExpand Up@@ -59,8 +59,7 @@ pub struct Engine<R: Runtime> {
operation_metrics: GraphqlOperationMetrics,
auth: AuthService,
retry_budgets: RetryBudgets,
trusted_documents_cache: <R::CacheFactory as HotCacheFactory>::Cache<String>,
operation_cache: <R::CacheFactory as HotCacheFactory>::Cache<Arc<PreparedOperation>>,
operation_cache: <R::OperationCacheFactory as OperationCacheFactory>::Cache<Arc<PreparedOperation>>,
}

impl<R: Runtime> Engine<R> {
Expand DownExpand Up@@ -90,8 +89,7 @@ impl<R: Runtime> Engine<R> {
auth,
retry_budgets: RetryBudgets::build(&schema),
operation_metrics: GraphqlOperationMetrics::build(runtime.meter()),
trusted_documents_cache: runtime.cache_factory().create(CachedDataKind::TrustedDocument).await,
operation_cache: runtime.cache_factory().create(CachedDataKind::Operation).await,
operation_cache: runtime.operation_cache_factory().create().await,
schema,
runtime,
}
Expand All@@ -107,14 +105,13 @@ impl<R: Runtime> Engine<R> {
let format = headers.typed_get::<StreamingFormat>();
let request_context = match self.create_request_context(headers).await {
Ok(context) => context,
Err(response) => return HttpGraphqlResponse::build(response, format, Default::default()),
Err(response) => return HttpGraphqlResponse::build(response, format),
};

if let Err(err) = self.runtime.rate_limiter().limit(&RateLimitKey::Global).await {
return HttpGraphqlResponse::build(
Response::pre_execution_error(GraphqlError::new(err.to_string(), ErrorCode::RateLimited)),
format,
Default::default(),
);
}

Expand All@@ -128,7 +125,6 @@ impl<R: Runtime> Engine<R> {
HttpGraphqlResponse::build(
Response::execution_error(GraphqlError::new("Gateway timeout", ErrorCode::GatewayTimeout)),
format,
Default::default(),
)
}
.boxed(),
Expand DownExpand Up@@ -239,22 +235,11 @@ impl<R: Runtime> Engine<R> {
let (operation_metrics_attributes, response) = ctx.execute_single(request).await;
let status = response.status();

let mut response_metadata = HttpGraphqlResponseExtraMetadata {
operation_name: None,
operation_type: None,
has_errors: !status.is_success(),
};

let elapsed = start.elapsed();

if let Some(operation_metrics_attributes) = operation_metrics_attributes {
tracing::Span::current().record_gql_request((&operation_metrics_attributes).into());

response_metadata
.operation_name
.clone_from(&operation_metrics_attributes.name);
response_metadata.operation_type = Some(operation_metrics_attributes.ty.as_str());

self.operation_metrics.record(
GraphqlRequestMetricsAttributes {
operation: operation_metrics_attributes,
Expand All@@ -279,7 +264,7 @@ impl<R: Runtime> Engine<R> {
tracing::debug!(target: GRAFBASE_TARGET, "{message}")
}

HttpGraphqlResponse::build(response, None, response_metadata)
HttpGraphqlResponse::build(response, None)
}
.instrument(span)
.await
Expand DownExpand Up@@ -428,9 +413,9 @@ impl<'ctx, R: Runtime> PreExecutionContext<'ctx, R> {

if let Some(operation) = self.operation_cache.get(&cache_key).await {
Ok(operation)
} else if let Some(persisted_query) = document_fut {
match persisted_query.await {
Ok(query) => Err((cache_key, Some(query))),
} else if let Some(document_fut) = document_fut {
match document_fut.await {
Ok(document) => Err((cache_key, Some(document))),
Err(err) => return Err((None, Response::pre_execution_error(err))),
}
} else {
Expand All@@ -440,8 +425,8 @@ impl<'ctx, R: Runtime> PreExecutionContext<'ctx, R> {

let operation = match result {
Ok(operation) => operation,
Err((cache_key, query)) => {
if let Some(query) = query {
Err((cache_key, document)) => {
if let Some(query) = document {
request.query = query
}
let operation = Operation::build(&self.schema, &request)
Expand Down
45 changes: 12 additions & 33 deletions engine/crates/engine-v2/src/engine/cache.rs
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
use std::borrow::Cow;

use base64::{display::Base64Display, engine::general_purpose::URL_SAFE_NO_PAD};
use engine::PersistedQueryRequestExtension;
use schema::Schema;
Expand All@@ -6,8 +8,6 @@ use super::SchemaVersion;

mod namespaces {
pub const OPERATION: &str = "op";
pub const TRUSTED_DOCUMENT: &str = "tdoc";
pub const APQ: &str = "apq";
}

/// Unique cache key that generates a URL-safe string.
Expand All@@ -18,18 +18,11 @@ pub(super) enum Key<'a> {
schema_version: &'a SchemaVersion,
document: Document<'a>,
},
TrustedDocument {
client_name: &'a str,
document_id: &'a str,
},
Apq {
ext: &'a PersistedQueryRequestExtension,
},
}

pub(super) enum Document<'a> {
PersistedQueryExt(&'a PersistedQueryRequestExtension),
Id(&'a str),
AutomaticallyPersistedQuery(&'a PersistedQueryRequestExtension),
TrustedDocumentId { client_name: &'a str, doc_id: Cow<'a, str> },
Text(&'a str),
}

Expand All@@ -56,21 +49,24 @@ impl std::fmt::Display for Key<'_> {
// operation name.
hasher.update(&[0x00]);
match document {
Document::PersistedQueryExt(ext) => {
Document::AutomaticallyPersistedQuery(ext) => {
hasher.update(b"apq");
hasher.update(&[0x00]);
hasher.update(&ext.version.to_ne_bytes());
hasher.update(&ext.sha256_hash);
}
Document::Id(doc_id) => {
Document::TrustedDocumentId { client_name, doc_id } => {
hasher.update(b"docid");
hasher.update(&[0x00]);
hasher.update(&client_name.len().to_ne_bytes());
hasher.update(client_name.as_bytes());
hasher.update(&doc_id.len().to_ne_bytes());
hasher.update(doc_id.as_bytes());
}
Document::Text(query) => {
hasher.update(b"query");
Document::Text(document) => {
hasher.update(b"doc");
hasher.update(&[0x00]);
hasher.update(query.as_bytes());
hasher.update(document.as_bytes());
}
}
let hash = hasher.finalize();
Expand All@@ -81,23 +77,6 @@ impl std::fmt::Display for Key<'_> {
Base64Display::new(hash.as_bytes(), &URL_SAFE_NO_PAD)
))
}
Key::TrustedDocument {
client_name,
document_id,
} => f.write_fmt(format_args!(
"{}.{}.{}",
namespaces::TRUSTED_DOCUMENT,
Base64Display::new(client_name.as_bytes(), &URL_SAFE_NO_PAD),
Base64Display::new(document_id.as_bytes(), &URL_SAFE_NO_PAD)
)),
Key::Apq {
ext: PersistedQueryRequestExtension { version, sha256_hash },
} => f.write_fmt(format_args!(
"{}.{}.{}",
namespaces::APQ,
version,
Base64Display::new(sha256_hash, &URL_SAFE_NO_PAD)
)),
}
}
}
4 changes: 2 additions & 2 deletions engine/crates/engine-v2/src/engine/runtime.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,14 +4,14 @@ use runtime::{entity_cache::EntityCache, fetch::Fetcher, kv::KvStore, rate_limit

pub trait Runtime: Send + Sync + 'static {
type Hooks: runtime::hooks::Hooks;
type CacheFactory: runtime::hot_cache::HotCacheFactory;
type OperationCacheFactory: runtime::operation_cache::OperationCacheFactory;

fn fetcher(&self) -> &Fetcher;
fn kv(&self) -> &KvStore;
fn trusted_documents(&self) -> &runtime::trusted_documents_client::Client;
fn meter(&self) -> &Meter;
fn hooks(&self) -> &Self::Hooks;
fn cache_factory(&self) -> &Self::CacheFactory;
fn operation_cache_factory(&self) -> &Self::OperationCacheFactory;
fn rate_limiter(&self) -> &RateLimiter;
fn sleep(&self, duration: std::time::Duration) -> BoxFuture<'static, ()>;
fn entity_cache(&self) -> &dyn EntityCache;
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Gb 7247 remove now useless response metadata simplify operation by hackal · Pull Request #9 · CallstackAI/grafbase-clone · GitHub
Skip to content
Open
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
39 changes: 39 additions & 0 deletions .callstack.yml
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
pr_review:
# Default: true
auto_run: true
modules:
# Automatically create a description summarizing the changes in pull request.
description:
enabled: true
diagram: false

# Find potential bugs in pull request changes or related files.
bug_hunter:
enabled: true
# Include fixes to possible bugs.
suggestions: true

# Suggest improvements to added code.
code_suggestions:
enabled: true

# Suggest changes to follow defined code conventions.
code_conventions:
enabled: false
# Describe your code conventions in plain text.
conventions: |
E.g. Exported variables, functions, classes and methods should be defined before private.


# Point out any typos or grammatical errors in variable names, texts, comments.
grammar:
enabled: false

# Suggest performance improvements to added code.
performance:
enabled: true

# Find potential security issues in added code.
security:
enabled: true

29 changes: 29 additions & 0 deletions .github/workflows/callstack-reviewer.yml
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
name: Callstack.ai PR Review

on:
workflow_dispatch:
inputs:
config:
type: string
description: "config for reviewer"
required: true
head:
type: string
description: "head commit sha"
required: true
base:
type: string
description: "base commit sha"
required: false

jobs:
callstack_pr_review_job:
runs-on: ubuntu-latest
steps:
- name: Review PR
uses: callstackai/action@main
with:
config: ${{ inputs.config }}
head: ${{ inputs.head }}
export: /code/chats.json

4 changes: 2 additions & 2 deletions cli/crates/federated-dev/src/dev/gateway_nanny.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -108,7 +108,7 @@ pub struct CliRuntime {

impl engine_v2::Runtime for CliRuntime {
type Hooks = ();
type CacheFactory = ();
type OperationCacheFactory = ();

fn fetcher(&self) -> &runtime::fetch::Fetcher {
&self.fetcher
Expand All@@ -130,7 +130,7 @@ impl engine_v2::Runtime for CliRuntime {
&()
}

fn cache_factory(&self) -> &() {
fn operation_cache_factory(&self) -> &() {
&()
}

Expand Down
37 changes: 11 additions & 26 deletions engine/crates/engine-v2/src/engine.rs
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
use ::runtime::{
auth::AccessToken,
hooks::Hooks,
hot_cache::{CachedDataKind, HotCache, HotCacheFactory},
operation_cache::{OperationCache, OperationCacheFactory},
rate_limiting::RateLimitKey,
};
use async_runtime::stream::StreamExt as _;
Expand All@@ -27,7 +27,7 @@ use web_time::Instant;

use crate::{
execution::{ExecutableOperation, PreExecutionContext},
http_response::{HttpGraphqlResponse, HttpGraphqlResponseExtraMetadata},
http_response::HttpGraphqlResponse,
operation::{Operation, PreparedOperation, Variables},
response::{ErrorCode, GraphqlError, Response},
websocket,
Expand DownExpand Up@@ -59,8 +59,7 @@ pub struct Engine<R: Runtime> {
operation_metrics: GraphqlOperationMetrics,
auth: AuthService,
retry_budgets: RetryBudgets,
trusted_documents_cache: <R::CacheFactory as HotCacheFactory>::Cache<String>,
operation_cache: <R::CacheFactory as HotCacheFactory>::Cache<Arc<PreparedOperation>>,
operation_cache: <R::OperationCacheFactory as OperationCacheFactory>::Cache<Arc<PreparedOperation>>,
}

impl<R: Runtime> Engine<R> {
Expand DownExpand Up@@ -90,8 +89,7 @@ impl<R: Runtime> Engine<R> {
auth,
retry_budgets: RetryBudgets::build(&schema),
operation_metrics: GraphqlOperationMetrics::build(runtime.meter()),
trusted_documents_cache: runtime.cache_factory().create(CachedDataKind::TrustedDocument).await,
operation_cache: runtime.cache_factory().create(CachedDataKind::Operation).await,
operation_cache: runtime.operation_cache_factory().create().await,
schema,
runtime,
}
Expand All@@ -107,14 +105,13 @@ impl<R: Runtime> Engine<R> {
let format = headers.typed_get::<StreamingFormat>();
let request_context = match self.create_request_context(headers).await {
Ok(context) => context,
Err(response) => return HttpGraphqlResponse::build(response, format, Default::default()),
Err(response) => return HttpGraphqlResponse::build(response, format),
};

if let Err(err) = self.runtime.rate_limiter().limit(&RateLimitKey::Global).await {
return HttpGraphqlResponse::build(
Response::pre_execution_error(GraphqlError::new(err.to_string(), ErrorCode::RateLimited)),
format,
Default::default(),
);
}

Expand All@@ -128,7 +125,6 @@ impl<R: Runtime> Engine<R> {
HttpGraphqlResponse::build(
Response::execution_error(GraphqlError::new("Gateway timeout", ErrorCode::GatewayTimeout)),
format,
Default::default(),
)
}
.boxed(),
Expand DownExpand Up@@ -239,22 +235,11 @@ impl<R: Runtime> Engine<R> {
let (operation_metrics_attributes, response) = ctx.execute_single(request).await;
let status = response.status();

let mut response_metadata = HttpGraphqlResponseExtraMetadata {
operation_name: None,
operation_type: None,
has_errors: !status.is_success(),
};

let elapsed = start.elapsed();

if let Some(operation_metrics_attributes) = operation_metrics_attributes {
tracing::Span::current().record_gql_request((&operation_metrics_attributes).into());

response_metadata
.operation_name
.clone_from(&operation_metrics_attributes.name);
response_metadata.operation_type = Some(operation_metrics_attributes.ty.as_str());

self.operation_metrics.record(
GraphqlRequestMetricsAttributes {
operation: operation_metrics_attributes,
Expand All@@ -279,7 +264,7 @@ impl<R: Runtime> Engine<R> {
tracing::debug!(target: GRAFBASE_TARGET, "{message}")
}

HttpGraphqlResponse::build(response, None, response_metadata)
HttpGraphqlResponse::build(response, None)
}
.instrument(span)
.await
Expand DownExpand Up@@ -428,9 +413,9 @@ impl<'ctx, R: Runtime> PreExecutionContext<'ctx, R> {

if let Some(operation) = self.operation_cache.get(&cache_key).await {
Ok(operation)
} else if let Some(persisted_query) = document_fut {
match persisted_query.await {
Ok(query) => Err((cache_key, Some(query))),
} else if let Some(document_fut) = document_fut {
match document_fut.await {
Ok(document) => Err((cache_key, Some(document))),
Err(err) => return Err((None, Response::pre_execution_error(err))),
}
} else {
Expand All@@ -440,8 +425,8 @@ impl<'ctx, R: Runtime> PreExecutionContext<'ctx, R> {

let operation = match result {
Ok(operation) => operation,
Err((cache_key, query)) => {
if let Some(query) = query {
Err((cache_key, document)) => {
if let Some(query) = document {
request.query = query
}
let operation = Operation::build(&self.schema, &request)
Expand Down
45 changes: 12 additions & 33 deletions engine/crates/engine-v2/src/engine/cache.rs
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
use std::borrow::Cow;

use base64::{display::Base64Display, engine::general_purpose::URL_SAFE_NO_PAD};
use engine::PersistedQueryRequestExtension;
use schema::Schema;
Expand All@@ -6,8 +8,6 @@ use super::SchemaVersion;

mod namespaces {
pub const OPERATION: &str = "op";
pub const TRUSTED_DOCUMENT: &str = "tdoc";
pub const APQ: &str = "apq";
}

/// Unique cache key that generates a URL-safe string.
Expand All@@ -18,18 +18,11 @@ pub(super) enum Key<'a> {
schema_version: &'a SchemaVersion,
document: Document<'a>,
},
TrustedDocument {
client_name: &'a str,
document_id: &'a str,
},
Apq {
ext: &'a PersistedQueryRequestExtension,
},
}

pub(super) enum Document<'a> {
PersistedQueryExt(&'a PersistedQueryRequestExtension),
Id(&'a str),
AutomaticallyPersistedQuery(&'a PersistedQueryRequestExtension),
TrustedDocumentId { client_name: &'a str, doc_id: Cow<'a, str> },
Text(&'a str),
}

Expand All@@ -56,21 +49,24 @@ impl std::fmt::Display for Key<'_> {
// operation name.
hasher.update(&[0x00]);
match document {
Document::PersistedQueryExt(ext) => {
Document::AutomaticallyPersistedQuery(ext) => {
hasher.update(b"apq");
hasher.update(&[0x00]);
hasher.update(&ext.version.to_ne_bytes());
hasher.update(&ext.sha256_hash);
}
Document::Id(doc_id) => {
Document::TrustedDocumentId { client_name, doc_id } => {
hasher.update(b"docid");
hasher.update(&[0x00]);
hasher.update(&client_name.len().to_ne_bytes());
hasher.update(client_name.as_bytes());
hasher.update(&doc_id.len().to_ne_bytes());
hasher.update(doc_id.as_bytes());
}
Document::Text(query) => {
hasher.update(b"query");
Document::Text(document) => {
hasher.update(b"doc");
hasher.update(&[0x00]);
hasher.update(query.as_bytes());
hasher.update(document.as_bytes());
}
}
let hash = hasher.finalize();
Expand All@@ -81,23 +77,6 @@ impl std::fmt::Display for Key<'_> {
Base64Display::new(hash.as_bytes(), &URL_SAFE_NO_PAD)
))
}
Key::TrustedDocument {
client_name,
document_id,
} => f.write_fmt(format_args!(
"{}.{}.{}",
namespaces::TRUSTED_DOCUMENT,
Base64Display::new(client_name.as_bytes(), &URL_SAFE_NO_PAD),
Base64Display::new(document_id.as_bytes(), &URL_SAFE_NO_PAD)
)),
Key::Apq {
ext: PersistedQueryRequestExtension { version, sha256_hash },
} => f.write_fmt(format_args!(
"{}.{}.{}",
namespaces::APQ,
version,
Base64Display::new(sha256_hash, &URL_SAFE_NO_PAD)
)),
}
}
}
4 changes: 2 additions & 2 deletions engine/crates/engine-v2/src/engine/runtime.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,14 +4,14 @@ use runtime::{entity_cache::EntityCache, fetch::Fetcher, kv::KvStore, rate_limit

pub trait Runtime: Send + Sync + 'static {
type Hooks: runtime::hooks::Hooks;
type CacheFactory: runtime::hot_cache::HotCacheFactory;
type OperationCacheFactory: runtime::operation_cache::OperationCacheFactory;

fn fetcher(&self) -> &Fetcher;
fn kv(&self) -> &KvStore;
fn trusted_documents(&self) -> &runtime::trusted_documents_client::Client;
fn meter(&self) -> &Meter;
fn hooks(&self) -> &Self::Hooks;
fn cache_factory(&self) -> &Self::CacheFactory;
fn operation_cache_factory(&self) -> &Self::OperationCacheFactory;
fn rate_limiter(&self) -> &RateLimiter;
fn sleep(&self, duration: std::time::Duration) -> BoxFuture<'static, ()>;
fn entity_cache(&self) -> &dyn EntityCache;
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Gb 7247 remove now useless response metadata simplify operation by hackal · Pull Request #9 · CallstackAI/grafbase-clone · GitHub
Skip to content
Open
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
39 changes: 39 additions & 0 deletions .callstack.yml
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
pr_review:
# Default: true
auto_run: true
modules:
# Automatically create a description summarizing the changes in pull request.
description:
enabled: true
diagram: false

# Find potential bugs in pull request changes or related files.
bug_hunter:
enabled: true
# Include fixes to possible bugs.
suggestions: true

# Suggest improvements to added code.
code_suggestions:
enabled: true

# Suggest changes to follow defined code conventions.
code_conventions:
enabled: false
# Describe your code conventions in plain text.
conventions: |
E.g. Exported variables, functions, classes and methods should be defined before private.


# Point out any typos or grammatical errors in variable names, texts, comments.
grammar:
enabled: false

# Suggest performance improvements to added code.
performance:
enabled: true

# Find potential security issues in added code.
security:
enabled: true

29 changes: 29 additions & 0 deletions .github/workflows/callstack-reviewer.yml
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
name: Callstack.ai PR Review

on:
workflow_dispatch:
inputs:
config:
type: string
description: "config for reviewer"
required: true
head:
type: string
description: "head commit sha"
required: true
base:
type: string
description: "base commit sha"
required: false

jobs:
callstack_pr_review_job:
runs-on: ubuntu-latest
steps:
- name: Review PR
uses: callstackai/action@main
with:
config: ${{ inputs.config }}
head: ${{ inputs.head }}
export: /code/chats.json

4 changes: 2 additions & 2 deletions cli/crates/federated-dev/src/dev/gateway_nanny.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -108,7 +108,7 @@ pub struct CliRuntime {

impl engine_v2::Runtime for CliRuntime {
type Hooks = ();
type CacheFactory = ();
type OperationCacheFactory = ();

fn fetcher(&self) -> &runtime::fetch::Fetcher {
&self.fetcher
Expand All@@ -130,7 +130,7 @@ impl engine_v2::Runtime for CliRuntime {
&()
}

fn cache_factory(&self) -> &() {
fn operation_cache_factory(&self) -> &() {
&()
}

Expand Down
37 changes: 11 additions & 26 deletions engine/crates/engine-v2/src/engine.rs
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
use ::runtime::{
auth::AccessToken,
hooks::Hooks,
hot_cache::{CachedDataKind, HotCache, HotCacheFactory},
operation_cache::{OperationCache, OperationCacheFactory},
rate_limiting::RateLimitKey,
};
use async_runtime::stream::StreamExt as _;
Expand All@@ -27,7 +27,7 @@ use web_time::Instant;

use crate::{
execution::{ExecutableOperation, PreExecutionContext},
http_response::{HttpGraphqlResponse, HttpGraphqlResponseExtraMetadata},
http_response::HttpGraphqlResponse,
operation::{Operation, PreparedOperation, Variables},
response::{ErrorCode, GraphqlError, Response},
websocket,
Expand DownExpand Up@@ -59,8 +59,7 @@ pub struct Engine<R: Runtime> {
operation_metrics: GraphqlOperationMetrics,
auth: AuthService,
retry_budgets: RetryBudgets,
trusted_documents_cache: <R::CacheFactory as HotCacheFactory>::Cache<String>,
operation_cache: <R::CacheFactory as HotCacheFactory>::Cache<Arc<PreparedOperation>>,
operation_cache: <R::OperationCacheFactory as OperationCacheFactory>::Cache<Arc<PreparedOperation>>,
}

impl<R: Runtime> Engine<R> {
Expand DownExpand Up@@ -90,8 +89,7 @@ impl<R: Runtime> Engine<R> {
auth,
retry_budgets: RetryBudgets::build(&schema),
operation_metrics: GraphqlOperationMetrics::build(runtime.meter()),
trusted_documents_cache: runtime.cache_factory().create(CachedDataKind::TrustedDocument).await,
operation_cache: runtime.cache_factory().create(CachedDataKind::Operation).await,
operation_cache: runtime.operation_cache_factory().create().await,
schema,
runtime,
}
Expand All@@ -107,14 +105,13 @@ impl<R: Runtime> Engine<R> {
let format = headers.typed_get::<StreamingFormat>();
let request_context = match self.create_request_context(headers).await {
Ok(context) => context,
Err(response) => return HttpGraphqlResponse::build(response, format, Default::default()),
Err(response) => return HttpGraphqlResponse::build(response, format),
};

if let Err(err) = self.runtime.rate_limiter().limit(&RateLimitKey::Global).await {
return HttpGraphqlResponse::build(
Response::pre_execution_error(GraphqlError::new(err.to_string(), ErrorCode::RateLimited)),
format,
Default::default(),
);
}

Expand All@@ -128,7 +125,6 @@ impl<R: Runtime> Engine<R> {
HttpGraphqlResponse::build(
Response::execution_error(GraphqlError::new("Gateway timeout", ErrorCode::GatewayTimeout)),
format,
Default::default(),
)
}
.boxed(),
Expand DownExpand Up@@ -239,22 +235,11 @@ impl<R: Runtime> Engine<R> {
let (operation_metrics_attributes, response) = ctx.execute_single(request).await;
let status = response.status();

let mut response_metadata = HttpGraphqlResponseExtraMetadata {
operation_name: None,
operation_type: None,
has_errors: !status.is_success(),
};

let elapsed = start.elapsed();

if let Some(operation_metrics_attributes) = operation_metrics_attributes {
tracing::Span::current().record_gql_request((&operation_metrics_attributes).into());

response_metadata
.operation_name
.clone_from(&operation_metrics_attributes.name);
response_metadata.operation_type = Some(operation_metrics_attributes.ty.as_str());

self.operation_metrics.record(
GraphqlRequestMetricsAttributes {
operation: operation_metrics_attributes,
Expand All@@ -279,7 +264,7 @@ impl<R: Runtime> Engine<R> {
tracing::debug!(target: GRAFBASE_TARGET, "{message}")
}

HttpGraphqlResponse::build(response, None, response_metadata)
HttpGraphqlResponse::build(response, None)
}
.instrument(span)
.await
Expand DownExpand Up@@ -428,9 +413,9 @@ impl<'ctx, R: Runtime> PreExecutionContext<'ctx, R> {

if let Some(operation) = self.operation_cache.get(&cache_key).await {
Ok(operation)
} else if let Some(persisted_query) = document_fut {
match persisted_query.await {
Ok(query) => Err((cache_key, Some(query))),
} else if let Some(document_fut) = document_fut {
match document_fut.await {
Ok(document) => Err((cache_key, Some(document))),
Err(err) => return Err((None, Response::pre_execution_error(err))),
}
} else {
Expand All@@ -440,8 +425,8 @@ impl<'ctx, R: Runtime> PreExecutionContext<'ctx, R> {

let operation = match result {
Ok(operation) => operation,
Err((cache_key, query)) => {
if let Some(query) = query {
Err((cache_key, document)) => {
if let Some(query) = document {
request.query = query
}
let operation = Operation::build(&self.schema, &request)
Expand Down
45 changes: 12 additions & 33 deletions engine/crates/engine-v2/src/engine/cache.rs
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
use std::borrow::Cow;

use base64::{display::Base64Display, engine::general_purpose::URL_SAFE_NO_PAD};
use engine::PersistedQueryRequestExtension;
use schema::Schema;
Expand All@@ -6,8 +8,6 @@ use super::SchemaVersion;

mod namespaces {
pub const OPERATION: &str = "op";
pub const TRUSTED_DOCUMENT: &str = "tdoc";
pub const APQ: &str = "apq";
}

/// Unique cache key that generates a URL-safe string.
Expand All@@ -18,18 +18,11 @@ pub(super) enum Key<'a> {
schema_version: &'a SchemaVersion,
document: Document<'a>,
},
TrustedDocument {
client_name: &'a str,
document_id: &'a str,
},
Apq {
ext: &'a PersistedQueryRequestExtension,
},
}

pub(super) enum Document<'a> {
PersistedQueryExt(&'a PersistedQueryRequestExtension),
Id(&'a str),
AutomaticallyPersistedQuery(&'a PersistedQueryRequestExtension),
TrustedDocumentId { client_name: &'a str, doc_id: Cow<'a, str> },
Text(&'a str),
}

Expand All@@ -56,21 +49,24 @@ impl std::fmt::Display for Key<'_> {
// operation name.
hasher.update(&[0x00]);
match document {
Document::PersistedQueryExt(ext) => {
Document::AutomaticallyPersistedQuery(ext) => {
hasher.update(b"apq");
hasher.update(&[0x00]);
hasher.update(&ext.version.to_ne_bytes());
hasher.update(&ext.sha256_hash);
}
Document::Id(doc_id) => {
Document::TrustedDocumentId { client_name, doc_id } => {
hasher.update(b"docid");
hasher.update(&[0x00]);
hasher.update(&client_name.len().to_ne_bytes());
hasher.update(client_name.as_bytes());
hasher.update(&doc_id.len().to_ne_bytes());
hasher.update(doc_id.as_bytes());
}
Document::Text(query) => {
hasher.update(b"query");
Document::Text(document) => {
hasher.update(b"doc");
hasher.update(&[0x00]);
hasher.update(query.as_bytes());
hasher.update(document.as_bytes());
}
}
let hash = hasher.finalize();
Expand All@@ -81,23 +77,6 @@ impl std::fmt::Display for Key<'_> {
Base64Display::new(hash.as_bytes(), &URL_SAFE_NO_PAD)
))
}
Key::TrustedDocument {
client_name,
document_id,
} => f.write_fmt(format_args!(
"{}.{}.{}",
namespaces::TRUSTED_DOCUMENT,
Base64Display::new(client_name.as_bytes(), &URL_SAFE_NO_PAD),
Base64Display::new(document_id.as_bytes(), &URL_SAFE_NO_PAD)
)),
Key::Apq {
ext: PersistedQueryRequestExtension { version, sha256_hash },
} => f.write_fmt(format_args!(
"{}.{}.{}",
namespaces::APQ,
version,
Base64Display::new(sha256_hash, &URL_SAFE_NO_PAD)
)),
}
}
}
4 changes: 2 additions & 2 deletions engine/crates/engine-v2/src/engine/runtime.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,14 +4,14 @@ use runtime::{entity_cache::EntityCache, fetch::Fetcher, kv::KvStore, rate_limit

pub trait Runtime: Send + Sync + 'static {
type Hooks: runtime::hooks::Hooks;
type CacheFactory: runtime::hot_cache::HotCacheFactory;
type OperationCacheFactory: runtime::operation_cache::OperationCacheFactory;

fn fetcher(&self) -> &Fetcher;
fn kv(&self) -> &KvStore;
fn trusted_documents(&self) -> &runtime::trusted_documents_client::Client;
fn meter(&self) -> &Meter;
fn hooks(&self) -> &Self::Hooks;
fn cache_factory(&self) -> &Self::CacheFactory;
fn operation_cache_factory(&self) -> &Self::OperationCacheFactory;
fn rate_limiter(&self) -> &RateLimiter;
fn sleep(&self, duration: std::time::Duration) -> BoxFuture<'static, ()>;
fn entity_cache(&self) -> &dyn EntityCache;
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Gb 7247 remove now useless response metadata simplify operation by hackal · Pull Request #9 · CallstackAI/grafbase-clone · GitHub
Skip to content
Open
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
39 changes: 39 additions & 0 deletions .callstack.yml
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
pr_review:
# Default: true
auto_run: true
modules:
# Automatically create a description summarizing the changes in pull request.
description:
enabled: true
diagram: false

# Find potential bugs in pull request changes or related files.
bug_hunter:
enabled: true
# Include fixes to possible bugs.
suggestions: true

# Suggest improvements to added code.
code_suggestions:
enabled: true

# Suggest changes to follow defined code conventions.
code_conventions:
enabled: false
# Describe your code conventions in plain text.
conventions: |
E.g. Exported variables, functions, classes and methods should be defined before private.


# Point out any typos or grammatical errors in variable names, texts, comments.
grammar:
enabled: false

# Suggest performance improvements to added code.
performance:
enabled: true

# Find potential security issues in added code.
security:
enabled: true

29 changes: 29 additions & 0 deletions .github/workflows/callstack-reviewer.yml
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
name: Callstack.ai PR Review

on:
workflow_dispatch:
inputs:
config:
type: string
description: "config for reviewer"
required: true
head:
type: string
description: "head commit sha"
required: true
base:
type: string
description: "base commit sha"
required: false

jobs:
callstack_pr_review_job:
runs-on: ubuntu-latest
steps:
- name: Review PR
uses: callstackai/action@main
with:
config: ${{ inputs.config }}
head: ${{ inputs.head }}
export: /code/chats.json

4 changes: 2 additions & 2 deletions cli/crates/federated-dev/src/dev/gateway_nanny.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -108,7 +108,7 @@ pub struct CliRuntime {

impl engine_v2::Runtime for CliRuntime {
type Hooks = ();
type CacheFactory = ();
type OperationCacheFactory = ();

fn fetcher(&self) -> &runtime::fetch::Fetcher {
&self.fetcher
Expand All@@ -130,7 +130,7 @@ impl engine_v2::Runtime for CliRuntime {
&()
}

fn cache_factory(&self) -> &() {
fn operation_cache_factory(&self) -> &() {
&()
}

Expand Down
37 changes: 11 additions & 26 deletions engine/crates/engine-v2/src/engine.rs
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
use ::runtime::{
auth::AccessToken,
hooks::Hooks,
hot_cache::{CachedDataKind, HotCache, HotCacheFactory},
operation_cache::{OperationCache, OperationCacheFactory},
rate_limiting::RateLimitKey,
};
use async_runtime::stream::StreamExt as _;
Expand All@@ -27,7 +27,7 @@ use web_time::Instant;

use crate::{
execution::{ExecutableOperation, PreExecutionContext},
http_response::{HttpGraphqlResponse, HttpGraphqlResponseExtraMetadata},
http_response::HttpGraphqlResponse,
operation::{Operation, PreparedOperation, Variables},
response::{ErrorCode, GraphqlError, Response},
websocket,
Expand DownExpand Up@@ -59,8 +59,7 @@ pub struct Engine<R: Runtime> {
operation_metrics: GraphqlOperationMetrics,
auth: AuthService,
retry_budgets: RetryBudgets,
trusted_documents_cache: <R::CacheFactory as HotCacheFactory>::Cache<String>,
operation_cache: <R::CacheFactory as HotCacheFactory>::Cache<Arc<PreparedOperation>>,
operation_cache: <R::OperationCacheFactory as OperationCacheFactory>::Cache<Arc<PreparedOperation>>,
}

impl<R: Runtime> Engine<R> {
Expand DownExpand Up@@ -90,8 +89,7 @@ impl<R: Runtime> Engine<R> {
auth,
retry_budgets: RetryBudgets::build(&schema),
operation_metrics: GraphqlOperationMetrics::build(runtime.meter()),
trusted_documents_cache: runtime.cache_factory().create(CachedDataKind::TrustedDocument).await,
operation_cache: runtime.cache_factory().create(CachedDataKind::Operation).await,
operation_cache: runtime.operation_cache_factory().create().await,
schema,
runtime,
}
Expand All@@ -107,14 +105,13 @@ impl<R: Runtime> Engine<R> {
let format = headers.typed_get::<StreamingFormat>();
let request_context = match self.create_request_context(headers).await {
Ok(context) => context,
Err(response) => return HttpGraphqlResponse::build(response, format, Default::default()),
Err(response) => return HttpGraphqlResponse::build(response, format),
};

if let Err(err) = self.runtime.rate_limiter().limit(&RateLimitKey::Global).await {
return HttpGraphqlResponse::build(
Response::pre_execution_error(GraphqlError::new(err.to_string(), ErrorCode::RateLimited)),
format,
Default::default(),
);
}

Expand All@@ -128,7 +125,6 @@ impl<R: Runtime> Engine<R> {
HttpGraphqlResponse::build(
Response::execution_error(GraphqlError::new("Gateway timeout", ErrorCode::GatewayTimeout)),
format,
Default::default(),
)
}
.boxed(),
Expand DownExpand Up@@ -239,22 +235,11 @@ impl<R: Runtime> Engine<R> {
let (operation_metrics_attributes, response) = ctx.execute_single(request).await;
let status = response.status();

let mut response_metadata = HttpGraphqlResponseExtraMetadata {
operation_name: None,
operation_type: None,
has_errors: !status.is_success(),
};

let elapsed = start.elapsed();

if let Some(operation_metrics_attributes) = operation_metrics_attributes {
tracing::Span::current().record_gql_request((&operation_metrics_attributes).into());

response_metadata
.operation_name
.clone_from(&operation_metrics_attributes.name);
response_metadata.operation_type = Some(operation_metrics_attributes.ty.as_str());

self.operation_metrics.record(
GraphqlRequestMetricsAttributes {
operation: operation_metrics_attributes,
Expand All@@ -279,7 +264,7 @@ impl<R: Runtime> Engine<R> {
tracing::debug!(target: GRAFBASE_TARGET, "{message}")
}

HttpGraphqlResponse::build(response, None, response_metadata)
HttpGraphqlResponse::build(response, None)
}
.instrument(span)
.await
Expand DownExpand Up@@ -428,9 +413,9 @@ impl<'ctx, R: Runtime> PreExecutionContext<'ctx, R> {

if let Some(operation) = self.operation_cache.get(&cache_key).await {
Ok(operation)
} else if let Some(persisted_query) = document_fut {
match persisted_query.await {
Ok(query) => Err((cache_key, Some(query))),
} else if let Some(document_fut) = document_fut {
match document_fut.await {
Ok(document) => Err((cache_key, Some(document))),
Err(err) => return Err((None, Response::pre_execution_error(err))),
}
} else {
Expand All@@ -440,8 +425,8 @@ impl<'ctx, R: Runtime> PreExecutionContext<'ctx, R> {

let operation = match result {
Ok(operation) => operation,
Err((cache_key, query)) => {
if let Some(query) = query {
Err((cache_key, document)) => {
if let Some(query) = document {
request.query = query
}
let operation = Operation::build(&self.schema, &request)
Expand Down
45 changes: 12 additions & 33 deletions engine/crates/engine-v2/src/engine/cache.rs
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
use std::borrow::Cow;

use base64::{display::Base64Display, engine::general_purpose::URL_SAFE_NO_PAD};
use engine::PersistedQueryRequestExtension;
use schema::Schema;
Expand All@@ -6,8 +8,6 @@ use super::SchemaVersion;

mod namespaces {
pub const OPERATION: &str = "op";
pub const TRUSTED_DOCUMENT: &str = "tdoc";
pub const APQ: &str = "apq";
}

/// Unique cache key that generates a URL-safe string.
Expand All@@ -18,18 +18,11 @@ pub(super) enum Key<'a> {
schema_version: &'a SchemaVersion,
document: Document<'a>,
},
TrustedDocument {
client_name: &'a str,
document_id: &'a str,
},
Apq {
ext: &'a PersistedQueryRequestExtension,
},
}

pub(super) enum Document<'a> {
PersistedQueryExt(&'a PersistedQueryRequestExtension),
Id(&'a str),
AutomaticallyPersistedQuery(&'a PersistedQueryRequestExtension),
TrustedDocumentId { client_name: &'a str, doc_id: Cow<'a, str> },
Text(&'a str),
}

Expand All@@ -56,21 +49,24 @@ impl std::fmt::Display for Key<'_> {
// operation name.
hasher.update(&[0x00]);
match document {
Document::PersistedQueryExt(ext) => {
Document::AutomaticallyPersistedQuery(ext) => {
hasher.update(b"apq");
hasher.update(&[0x00]);
hasher.update(&ext.version.to_ne_bytes());
hasher.update(&ext.sha256_hash);
}
Document::Id(doc_id) => {
Document::TrustedDocumentId { client_name, doc_id } => {
hasher.update(b"docid");
hasher.update(&[0x00]);
hasher.update(&client_name.len().to_ne_bytes());
hasher.update(client_name.as_bytes());
hasher.update(&doc_id.len().to_ne_bytes());
hasher.update(doc_id.as_bytes());
}
Document::Text(query) => {
hasher.update(b"query");
Document::Text(document) => {
hasher.update(b"doc");
hasher.update(&[0x00]);
hasher.update(query.as_bytes());
hasher.update(document.as_bytes());
}
}
let hash = hasher.finalize();
Expand All@@ -81,23 +77,6 @@ impl std::fmt::Display for Key<'_> {
Base64Display::new(hash.as_bytes(), &URL_SAFE_NO_PAD)
))
}
Key::TrustedDocument {
client_name,
document_id,
} => f.write_fmt(format_args!(
"{}.{}.{}",
namespaces::TRUSTED_DOCUMENT,
Base64Display::new(client_name.as_bytes(), &URL_SAFE_NO_PAD),
Base64Display::new(document_id.as_bytes(), &URL_SAFE_NO_PAD)
)),
Key::Apq {
ext: PersistedQueryRequestExtension { version, sha256_hash },
} => f.write_fmt(format_args!(
"{}.{}.{}",
namespaces::APQ,
version,
Base64Display::new(sha256_hash, &URL_SAFE_NO_PAD)
)),
}
}
}
4 changes: 2 additions & 2 deletions engine/crates/engine-v2/src/engine/runtime.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,14 +4,14 @@ use runtime::{entity_cache::EntityCache, fetch::Fetcher, kv::KvStore, rate_limit

pub trait Runtime: Send + Sync + 'static {
type Hooks: runtime::hooks::Hooks;
type CacheFactory: runtime::hot_cache::HotCacheFactory;
type OperationCacheFactory: runtime::operation_cache::OperationCacheFactory;

fn fetcher(&self) -> &Fetcher;
fn kv(&self) -> &KvStore;
fn trusted_documents(&self) -> &runtime::trusted_documents_client::Client;
fn meter(&self) -> &Meter;
fn hooks(&self) -> &Self::Hooks;
fn cache_factory(&self) -> &Self::CacheFactory;
fn operation_cache_factory(&self) -> &Self::OperationCacheFactory;
fn rate_limiter(&self) -> &RateLimiter;
fn sleep(&self, duration: std::time::Duration) -> BoxFuture<'static, ()>;
fn entity_cache(&self) -> &dyn EntityCache;
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' Gb 7247 remove now useless response metadata simplify operation by hackal · Pull Request #9 · CallstackAI/grafbase-clone · GitHub
Skip to content
Open
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
39 changes: 39 additions & 0 deletions .callstack.yml
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
pr_review:
# Default: true
auto_run: true
modules:
# Automatically create a description summarizing the changes in pull request.
description:
enabled: true
diagram: false

# Find potential bugs in pull request changes or related files.
bug_hunter:
enabled: true
# Include fixes to possible bugs.
suggestions: true

# Suggest improvements to added code.
code_suggestions:
enabled: true

# Suggest changes to follow defined code conventions.
code_conventions:
enabled: false
# Describe your code conventions in plain text.
conventions: |
E.g. Exported variables, functions, classes and methods should be defined before private.


# Point out any typos or grammatical errors in variable names, texts, comments.
grammar:
enabled: false

# Suggest performance improvements to added code.
performance:
enabled: true

# Find potential security issues in added code.
security:
enabled: true

29 changes: 29 additions & 0 deletions .github/workflows/callstack-reviewer.yml
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
name: Callstack.ai PR Review

on:
workflow_dispatch:
inputs:
config:
type: string
description: "config for reviewer"
required: true
head:
type: string
description: "head commit sha"
required: true
base:
type: string
description: "base commit sha"
required: false

jobs:
callstack_pr_review_job:
runs-on: ubuntu-latest
steps:
- name: Review PR
uses: callstackai/action@main
with:
config: ${{ inputs.config }}
head: ${{ inputs.head }}
export: /code/chats.json

4 changes: 2 additions & 2 deletions cli/crates/federated-dev/src/dev/gateway_nanny.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -108,7 +108,7 @@ pub struct CliRuntime {

impl engine_v2::Runtime for CliRuntime {
type Hooks = ();
type CacheFactory = ();
type OperationCacheFactory = ();

fn fetcher(&self) -> &runtime::fetch::Fetcher {
&self.fetcher
Expand All@@ -130,7 +130,7 @@ impl engine_v2::Runtime for CliRuntime {
&()
}

fn cache_factory(&self) -> &() {
fn operation_cache_factory(&self) -> &() {
&()
}

Expand Down
37 changes: 11 additions & 26 deletions engine/crates/engine-v2/src/engine.rs
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
use ::runtime::{
auth::AccessToken,
hooks::Hooks,
hot_cache::{CachedDataKind, HotCache, HotCacheFactory},
operation_cache::{OperationCache, OperationCacheFactory},
rate_limiting::RateLimitKey,
};
use async_runtime::stream::StreamExt as _;
Expand All@@ -27,7 +27,7 @@ use web_time::Instant;

use crate::{
execution::{ExecutableOperation, PreExecutionContext},
http_response::{HttpGraphqlResponse, HttpGraphqlResponseExtraMetadata},
http_response::HttpGraphqlResponse,
operation::{Operation, PreparedOperation, Variables},
response::{ErrorCode, GraphqlError, Response},
websocket,
Expand DownExpand Up@@ -59,8 +59,7 @@ pub struct Engine<R: Runtime> {
operation_metrics: GraphqlOperationMetrics,
auth: AuthService,
retry_budgets: RetryBudgets,
trusted_documents_cache: <R::CacheFactory as HotCacheFactory>::Cache<String>,
operation_cache: <R::CacheFactory as HotCacheFactory>::Cache<Arc<PreparedOperation>>,
operation_cache: <R::OperationCacheFactory as OperationCacheFactory>::Cache<Arc<PreparedOperation>>,
}

impl<R: Runtime> Engine<R> {
Expand DownExpand Up@@ -90,8 +89,7 @@ impl<R: Runtime> Engine<R> {
auth,
retry_budgets: RetryBudgets::build(&schema),
operation_metrics: GraphqlOperationMetrics::build(runtime.meter()),
trusted_documents_cache: runtime.cache_factory().create(CachedDataKind::TrustedDocument).await,
operation_cache: runtime.cache_factory().create(CachedDataKind::Operation).await,
operation_cache: runtime.operation_cache_factory().create().await,
schema,
runtime,
}
Expand All@@ -107,14 +105,13 @@ impl<R: Runtime> Engine<R> {
let format = headers.typed_get::<StreamingFormat>();
let request_context = match self.create_request_context(headers).await {
Ok(context) => context,
Err(response) => return HttpGraphqlResponse::build(response, format, Default::default()),
Err(response) => return HttpGraphqlResponse::build(response, format),
};

if let Err(err) = self.runtime.rate_limiter().limit(&RateLimitKey::Global).await {
return HttpGraphqlResponse::build(
Response::pre_execution_error(GraphqlError::new(err.to_string(), ErrorCode::RateLimited)),
format,
Default::default(),
);
}

Expand All@@ -128,7 +125,6 @@ impl<R: Runtime> Engine<R> {
HttpGraphqlResponse::build(
Response::execution_error(GraphqlError::new("Gateway timeout", ErrorCode::GatewayTimeout)),
format,
Default::default(),
)
}
.boxed(),
Expand DownExpand Up@@ -239,22 +235,11 @@ impl<R: Runtime> Engine<R> {
let (operation_metrics_attributes, response) = ctx.execute_single(request).await;
let status = response.status();

let mut response_metadata = HttpGraphqlResponseExtraMetadata {
operation_name: None,
operation_type: None,
has_errors: !status.is_success(),
};

let elapsed = start.elapsed();

if let Some(operation_metrics_attributes) = operation_metrics_attributes {
tracing::Span::current().record_gql_request((&operation_metrics_attributes).into());

response_metadata
.operation_name
.clone_from(&operation_metrics_attributes.name);
response_metadata.operation_type = Some(operation_metrics_attributes.ty.as_str());

self.operation_metrics.record(
GraphqlRequestMetricsAttributes {
operation: operation_metrics_attributes,
Expand All@@ -279,7 +264,7 @@ impl<R: Runtime> Engine<R> {
tracing::debug!(target: GRAFBASE_TARGET, "{message}")
}

HttpGraphqlResponse::build(response, None, response_metadata)
HttpGraphqlResponse::build(response, None)
}
.instrument(span)
.await
Expand DownExpand Up@@ -428,9 +413,9 @@ impl<'ctx, R: Runtime> PreExecutionContext<'ctx, R> {

if let Some(operation) = self.operation_cache.get(&cache_key).await {
Ok(operation)
} else if let Some(persisted_query) = document_fut {
match persisted_query.await {
Ok(query) => Err((cache_key, Some(query))),
} else if let Some(document_fut) = document_fut {
match document_fut.await {
Ok(document) => Err((cache_key, Some(document))),
Err(err) => return Err((None, Response::pre_execution_error(err))),
}
} else {
Expand All@@ -440,8 +425,8 @@ impl<'ctx, R: Runtime> PreExecutionContext<'ctx, R> {

let operation = match result {
Ok(operation) => operation,
Err((cache_key, query)) => {
if let Some(query) = query {
Err((cache_key, document)) => {
if let Some(query) = document {
request.query = query
}
let operation = Operation::build(&self.schema, &request)
Expand Down
45 changes: 12 additions & 33 deletions engine/crates/engine-v2/src/engine/cache.rs
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
use std::borrow::Cow;

use base64::{display::Base64Display, engine::general_purpose::URL_SAFE_NO_PAD};
use engine::PersistedQueryRequestExtension;
use schema::Schema;
Expand All@@ -6,8 +8,6 @@ use super::SchemaVersion;

mod namespaces {
pub const OPERATION: &str = "op";
pub const TRUSTED_DOCUMENT: &str = "tdoc";
pub const APQ: &str = "apq";
}

/// Unique cache key that generates a URL-safe string.
Expand All@@ -18,18 +18,11 @@ pub(super) enum Key<'a> {
schema_version: &'a SchemaVersion,
document: Document<'a>,
},
TrustedDocument {
client_name: &'a str,
document_id: &'a str,
},
Apq {
ext: &'a PersistedQueryRequestExtension,
},
}

pub(super) enum Document<'a> {
PersistedQueryExt(&'a PersistedQueryRequestExtension),
Id(&'a str),
AutomaticallyPersistedQuery(&'a PersistedQueryRequestExtension),
TrustedDocumentId { client_name: &'a str, doc_id: Cow<'a, str> },
Text(&'a str),
}

Expand All@@ -56,21 +49,24 @@ impl std::fmt::Display for Key<'_> {
// operation name.
hasher.update(&[0x00]);
match document {
Document::PersistedQueryExt(ext) => {
Document::AutomaticallyPersistedQuery(ext) => {
hasher.update(b"apq");
hasher.update(&[0x00]);
hasher.update(&ext.version.to_ne_bytes());
hasher.update(&ext.sha256_hash);
}
Document::Id(doc_id) => {
Document::TrustedDocumentId { client_name, doc_id } => {
hasher.update(b"docid");
hasher.update(&[0x00]);
hasher.update(&client_name.len().to_ne_bytes());
hasher.update(client_name.as_bytes());
hasher.update(&doc_id.len().to_ne_bytes());
hasher.update(doc_id.as_bytes());
}
Document::Text(query) => {
hasher.update(b"query");
Document::Text(document) => {
hasher.update(b"doc");
hasher.update(&[0x00]);
hasher.update(query.as_bytes());
hasher.update(document.as_bytes());
}
}
let hash = hasher.finalize();
Expand All@@ -81,23 +77,6 @@ impl std::fmt::Display for Key<'_> {
Base64Display::new(hash.as_bytes(), &URL_SAFE_NO_PAD)
))
}
Key::TrustedDocument {
client_name,
document_id,
} => f.write_fmt(format_args!(
"{}.{}.{}",
namespaces::TRUSTED_DOCUMENT,
Base64Display::new(client_name.as_bytes(), &URL_SAFE_NO_PAD),
Base64Display::new(document_id.as_bytes(), &URL_SAFE_NO_PAD)
)),
Key::Apq {
ext: PersistedQueryRequestExtension { version, sha256_hash },
} => f.write_fmt(format_args!(
"{}.{}.{}",
namespaces::APQ,
version,
Base64Display::new(sha256_hash, &URL_SAFE_NO_PAD)
)),
}
}
}
4 changes: 2 additions & 2 deletions engine/crates/engine-v2/src/engine/runtime.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,14 +4,14 @@ use runtime::{entity_cache::EntityCache, fetch::Fetcher, kv::KvStore, rate_limit

pub trait Runtime: Send + Sync + 'static {
type Hooks: runtime::hooks::Hooks;
type CacheFactory: runtime::hot_cache::HotCacheFactory;
type OperationCacheFactory: runtime::operation_cache::OperationCacheFactory;

fn fetcher(&self) -> &Fetcher;
fn kv(&self) -> &KvStore;
fn trusted_documents(&self) -> &runtime::trusted_documents_client::Client;
fn meter(&self) -> &Meter;
fn hooks(&self) -> &Self::Hooks;
fn cache_factory(&self) -> &Self::CacheFactory;
fn operation_cache_factory(&self) -> &Self::OperationCacheFactory;
fn rate_limiter(&self) -> &RateLimiter;
fn sleep(&self, duration: std::time::Duration) -> BoxFuture<'static, ()>;
fn entity_cache(&self) -> &dyn EntityCache;
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Gb 7247 remove now useless response metadata simplify operation by hackal · Pull Request #9 · CallstackAI/grafbase-clone · GitHub
Skip to content
Open
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
39 changes: 39 additions & 0 deletions .callstack.yml
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
pr_review:
# Default: true
auto_run: true
modules:
# Automatically create a description summarizing the changes in pull request.
description:
enabled: true
diagram: false

# Find potential bugs in pull request changes or related files.
bug_hunter:
enabled: true
# Include fixes to possible bugs.
suggestions: true

# Suggest improvements to added code.
code_suggestions:
enabled: true

# Suggest changes to follow defined code conventions.
code_conventions:
enabled: false
# Describe your code conventions in plain text.
conventions: |
E.g. Exported variables, functions, classes and methods should be defined before private.


# Point out any typos or grammatical errors in variable names, texts, comments.
grammar:
enabled: false

# Suggest performance improvements to added code.
performance:
enabled: true

# Find potential security issues in added code.
security:
enabled: true

29 changes: 29 additions & 0 deletions .github/workflows/callstack-reviewer.yml
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
name: Callstack.ai PR Review

on:
workflow_dispatch:
inputs:
config:
type: string
description: "config for reviewer"
required: true
head:
type: string
description: "head commit sha"
required: true
base:
type: string
description: "base commit sha"
required: false

jobs:
callstack_pr_review_job:
runs-on: ubuntu-latest
steps:
- name: Review PR
uses: callstackai/action@main
with:
config: ${{ inputs.config }}
head: ${{ inputs.head }}
export: /code/chats.json

4 changes: 2 additions & 2 deletions cli/crates/federated-dev/src/dev/gateway_nanny.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -108,7 +108,7 @@ pub struct CliRuntime {

impl engine_v2::Runtime for CliRuntime {
type Hooks = ();
type CacheFactory = ();
type OperationCacheFactory = ();

fn fetcher(&self) -> &runtime::fetch::Fetcher {
&self.fetcher
Expand All@@ -130,7 +130,7 @@ impl engine_v2::Runtime for CliRuntime {
&()
}

fn cache_factory(&self) -> &() {
fn operation_cache_factory(&self) -> &() {
&()
}

Expand Down
37 changes: 11 additions & 26 deletions engine/crates/engine-v2/src/engine.rs
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
use ::runtime::{
auth::AccessToken,
hooks::Hooks,
hot_cache::{CachedDataKind, HotCache, HotCacheFactory},
operation_cache::{OperationCache, OperationCacheFactory},
rate_limiting::RateLimitKey,
};
use async_runtime::stream::StreamExt as _;
Expand All@@ -27,7 +27,7 @@ use web_time::Instant;

use crate::{
execution::{ExecutableOperation, PreExecutionContext},
http_response::{HttpGraphqlResponse, HttpGraphqlResponseExtraMetadata},
http_response::HttpGraphqlResponse,
operation::{Operation, PreparedOperation, Variables},
response::{ErrorCode, GraphqlError, Response},
websocket,
Expand DownExpand Up@@ -59,8 +59,7 @@ pub struct Engine<R: Runtime> {
operation_metrics: GraphqlOperationMetrics,
auth: AuthService,
retry_budgets: RetryBudgets,
trusted_documents_cache: <R::CacheFactory as HotCacheFactory>::Cache<String>,
operation_cache: <R::CacheFactory as HotCacheFactory>::Cache<Arc<PreparedOperation>>,
operation_cache: <R::OperationCacheFactory as OperationCacheFactory>::Cache<Arc<PreparedOperation>>,
}

impl<R: Runtime> Engine<R> {
Expand DownExpand Up@@ -90,8 +89,7 @@ impl<R: Runtime> Engine<R> {
auth,
retry_budgets: RetryBudgets::build(&schema),
operation_metrics: GraphqlOperationMetrics::build(runtime.meter()),
trusted_documents_cache: runtime.cache_factory().create(CachedDataKind::TrustedDocument).await,
operation_cache: runtime.cache_factory().create(CachedDataKind::Operation).await,
operation_cache: runtime.operation_cache_factory().create().await,
schema,
runtime,
}
Expand All@@ -107,14 +105,13 @@ impl<R: Runtime> Engine<R> {
let format = headers.typed_get::<StreamingFormat>();
let request_context = match self.create_request_context(headers).await {
Ok(context) => context,
Err(response) => return HttpGraphqlResponse::build(response, format, Default::default()),
Err(response) => return HttpGraphqlResponse::build(response, format),
};

if let Err(err) = self.runtime.rate_limiter().limit(&RateLimitKey::Global).await {
return HttpGraphqlResponse::build(
Response::pre_execution_error(GraphqlError::new(err.to_string(), ErrorCode::RateLimited)),
format,
Default::default(),
);
}

Expand All@@ -128,7 +125,6 @@ impl<R: Runtime> Engine<R> {
HttpGraphqlResponse::build(
Response::execution_error(GraphqlError::new("Gateway timeout", ErrorCode::GatewayTimeout)),
format,
Default::default(),
)
}
.boxed(),
Expand DownExpand Up@@ -239,22 +235,11 @@ impl<R: Runtime> Engine<R> {
let (operation_metrics_attributes, response) = ctx.execute_single(request).await;
let status = response.status();

let mut response_metadata = HttpGraphqlResponseExtraMetadata {
operation_name: None,
operation_type: None,
has_errors: !status.is_success(),
};

let elapsed = start.elapsed();

if let Some(operation_metrics_attributes) = operation_metrics_attributes {
tracing::Span::current().record_gql_request((&operation_metrics_attributes).into());

response_metadata
.operation_name
.clone_from(&operation_metrics_attributes.name);
response_metadata.operation_type = Some(operation_metrics_attributes.ty.as_str());

self.operation_metrics.record(
GraphqlRequestMetricsAttributes {
operation: operation_metrics_attributes,
Expand All@@ -279,7 +264,7 @@ impl<R: Runtime> Engine<R> {
tracing::debug!(target: GRAFBASE_TARGET, "{message}")
}

HttpGraphqlResponse::build(response, None, response_metadata)
HttpGraphqlResponse::build(response, None)
}
.instrument(span)
.await
Expand DownExpand Up@@ -428,9 +413,9 @@ impl<'ctx, R: Runtime> PreExecutionContext<'ctx, R> {

if let Some(operation) = self.operation_cache.get(&cache_key).await {
Ok(operation)
} else if let Some(persisted_query) = document_fut {
match persisted_query.await {
Ok(query) => Err((cache_key, Some(query))),
} else if let Some(document_fut) = document_fut {
match document_fut.await {
Ok(document) => Err((cache_key, Some(document))),
Err(err) => return Err((None, Response::pre_execution_error(err))),
}
} else {
Expand All@@ -440,8 +425,8 @@ impl<'ctx, R: Runtime> PreExecutionContext<'ctx, R> {

let operation = match result {
Ok(operation) => operation,
Err((cache_key, query)) => {
if let Some(query) = query {
Err((cache_key, document)) => {
if let Some(query) = document {
request.query = query
}
let operation = Operation::build(&self.schema, &request)
Expand Down
45 changes: 12 additions & 33 deletions engine/crates/engine-v2/src/engine/cache.rs
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
use std::borrow::Cow;

use base64::{display::Base64Display, engine::general_purpose::URL_SAFE_NO_PAD};
use engine::PersistedQueryRequestExtension;
use schema::Schema;
Expand All@@ -6,8 +8,6 @@ use super::SchemaVersion;

mod namespaces {
pub const OPERATION: &str = "op";
pub const TRUSTED_DOCUMENT: &str = "tdoc";
pub const APQ: &str = "apq";
}

/// Unique cache key that generates a URL-safe string.
Expand All@@ -18,18 +18,11 @@ pub(super) enum Key<'a> {
schema_version: &'a SchemaVersion,
document: Document<'a>,
},
TrustedDocument {
client_name: &'a str,
document_id: &'a str,
},
Apq {
ext: &'a PersistedQueryRequestExtension,
},
}

pub(super) enum Document<'a> {
PersistedQueryExt(&'a PersistedQueryRequestExtension),
Id(&'a str),
AutomaticallyPersistedQuery(&'a PersistedQueryRequestExtension),
TrustedDocumentId { client_name: &'a str, doc_id: Cow<'a, str> },
Text(&'a str),
}

Expand All@@ -56,21 +49,24 @@ impl std::fmt::Display for Key<'_> {
// operation name.
hasher.update(&[0x00]);
match document {
Document::PersistedQueryExt(ext) => {
Document::AutomaticallyPersistedQuery(ext) => {
hasher.update(b"apq");
hasher.update(&[0x00]);
hasher.update(&ext.version.to_ne_bytes());
hasher.update(&ext.sha256_hash);
}
Document::Id(doc_id) => {
Document::TrustedDocumentId { client_name, doc_id } => {
hasher.update(b"docid");
hasher.update(&[0x00]);
hasher.update(&client_name.len().to_ne_bytes());
hasher.update(client_name.as_bytes());
hasher.update(&doc_id.len().to_ne_bytes());
hasher.update(doc_id.as_bytes());
}
Document::Text(query) => {
hasher.update(b"query");
Document::Text(document) => {
hasher.update(b"doc");
hasher.update(&[0x00]);
hasher.update(query.as_bytes());
hasher.update(document.as_bytes());
}
}
let hash = hasher.finalize();
Expand All@@ -81,23 +77,6 @@ impl std::fmt::Display for Key<'_> {
Base64Display::new(hash.as_bytes(), &URL_SAFE_NO_PAD)
))
}
Key::TrustedDocument {
client_name,
document_id,
} => f.write_fmt(format_args!(
"{}.{}.{}",
namespaces::TRUSTED_DOCUMENT,
Base64Display::new(client_name.as_bytes(), &URL_SAFE_NO_PAD),
Base64Display::new(document_id.as_bytes(), &URL_SAFE_NO_PAD)
)),
Key::Apq {
ext: PersistedQueryRequestExtension { version, sha256_hash },
} => f.write_fmt(format_args!(
"{}.{}.{}",
namespaces::APQ,
version,
Base64Display::new(sha256_hash, &URL_SAFE_NO_PAD)
)),
}
}
}
4 changes: 2 additions & 2 deletions engine/crates/engine-v2/src/engine/runtime.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,14 +4,14 @@ use runtime::{entity_cache::EntityCache, fetch::Fetcher, kv::KvStore, rate_limit

pub trait Runtime: Send + Sync + 'static {
type Hooks: runtime::hooks::Hooks;
type CacheFactory: runtime::hot_cache::HotCacheFactory;
type OperationCacheFactory: runtime::operation_cache::OperationCacheFactory;

fn fetcher(&self) -> &Fetcher;
fn kv(&self) -> &KvStore;
fn trusted_documents(&self) -> &runtime::trusted_documents_client::Client;
fn meter(&self) -> &Meter;
fn hooks(&self) -> &Self::Hooks;
fn cache_factory(&self) -> &Self::CacheFactory;
fn operation_cache_factory(&self) -> &Self::OperationCacheFactory;
fn rate_limiter(&self) -> &RateLimiter;
fn sleep(&self, duration: std::time::Duration) -> BoxFuture<'static, ()>;
fn entity_cache(&self) -> &dyn EntityCache;
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Gb 7247 remove now useless response metadata simplify operation by hackal · Pull Request #9 · CallstackAI/grafbase-clone · GitHub
Skip to content
Open
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
39 changes: 39 additions & 0 deletions .callstack.yml
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
pr_review:
# Default: true
auto_run: true
modules:
# Automatically create a description summarizing the changes in pull request.
description:
enabled: true
diagram: false

# Find potential bugs in pull request changes or related files.
bug_hunter:
enabled: true
# Include fixes to possible bugs.
suggestions: true

# Suggest improvements to added code.
code_suggestions:
enabled: true

# Suggest changes to follow defined code conventions.
code_conventions:
enabled: false
# Describe your code conventions in plain text.
conventions: |
E.g. Exported variables, functions, classes and methods should be defined before private.


# Point out any typos or grammatical errors in variable names, texts, comments.
grammar:
enabled: false

# Suggest performance improvements to added code.
performance:
enabled: true

# Find potential security issues in added code.
security:
enabled: true

29 changes: 29 additions & 0 deletions .github/workflows/callstack-reviewer.yml
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
name: Callstack.ai PR Review

on:
workflow_dispatch:
inputs:
config:
type: string
description: "config for reviewer"
required: true
head:
type: string
description: "head commit sha"
required: true
base:
type: string
description: "base commit sha"
required: false

jobs:
callstack_pr_review_job:
runs-on: ubuntu-latest
steps:
- name: Review PR
uses: callstackai/action@main
with:
config: ${{ inputs.config }}
head: ${{ inputs.head }}
export: /code/chats.json

4 changes: 2 additions & 2 deletions cli/crates/federated-dev/src/dev/gateway_nanny.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -108,7 +108,7 @@ pub struct CliRuntime {

impl engine_v2::Runtime for CliRuntime {
type Hooks = ();
type CacheFactory = ();
type OperationCacheFactory = ();

fn fetcher(&self) -> &runtime::fetch::Fetcher {
&self.fetcher
Expand All@@ -130,7 +130,7 @@ impl engine_v2::Runtime for CliRuntime {
&()
}

fn cache_factory(&self) -> &() {
fn operation_cache_factory(&self) -> &() {
&()
}

Expand Down
37 changes: 11 additions & 26 deletions engine/crates/engine-v2/src/engine.rs
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
use ::runtime::{
auth::AccessToken,
hooks::Hooks,
hot_cache::{CachedDataKind, HotCache, HotCacheFactory},
operation_cache::{OperationCache, OperationCacheFactory},
rate_limiting::RateLimitKey,
};
use async_runtime::stream::StreamExt as _;
Expand All@@ -27,7 +27,7 @@ use web_time::Instant;

use crate::{
execution::{ExecutableOperation, PreExecutionContext},
http_response::{HttpGraphqlResponse, HttpGraphqlResponseExtraMetadata},
http_response::HttpGraphqlResponse,
operation::{Operation, PreparedOperation, Variables},
response::{ErrorCode, GraphqlError, Response},
websocket,
Expand DownExpand Up@@ -59,8 +59,7 @@ pub struct Engine<R: Runtime> {
operation_metrics: GraphqlOperationMetrics,
auth: AuthService,
retry_budgets: RetryBudgets,
trusted_documents_cache: <R::CacheFactory as HotCacheFactory>::Cache<String>,
operation_cache: <R::CacheFactory as HotCacheFactory>::Cache<Arc<PreparedOperation>>,
operation_cache: <R::OperationCacheFactory as OperationCacheFactory>::Cache<Arc<PreparedOperation>>,
}

impl<R: Runtime> Engine<R> {
Expand DownExpand Up@@ -90,8 +89,7 @@ impl<R: Runtime> Engine<R> {
auth,
retry_budgets: RetryBudgets::build(&schema),
operation_metrics: GraphqlOperationMetrics::build(runtime.meter()),
trusted_documents_cache: runtime.cache_factory().create(CachedDataKind::TrustedDocument).await,
operation_cache: runtime.cache_factory().create(CachedDataKind::Operation).await,
operation_cache: runtime.operation_cache_factory().create().await,
schema,
runtime,
}
Expand All@@ -107,14 +105,13 @@ impl<R: Runtime> Engine<R> {
let format = headers.typed_get::<StreamingFormat>();
let request_context = match self.create_request_context(headers).await {
Ok(context) => context,
Err(response) => return HttpGraphqlResponse::build(response, format, Default::default()),
Err(response) => return HttpGraphqlResponse::build(response, format),
};

if let Err(err) = self.runtime.rate_limiter().limit(&RateLimitKey::Global).await {
return HttpGraphqlResponse::build(
Response::pre_execution_error(GraphqlError::new(err.to_string(), ErrorCode::RateLimited)),
format,
Default::default(),
);
}

Expand All@@ -128,7 +125,6 @@ impl<R: Runtime> Engine<R> {
HttpGraphqlResponse::build(
Response::execution_error(GraphqlError::new("Gateway timeout", ErrorCode::GatewayTimeout)),
format,
Default::default(),
)
}
.boxed(),
Expand DownExpand Up@@ -239,22 +235,11 @@ impl<R: Runtime> Engine<R> {
let (operation_metrics_attributes, response) = ctx.execute_single(request).await;
let status = response.status();

let mut response_metadata = HttpGraphqlResponseExtraMetadata {
operation_name: None,
operation_type: None,
has_errors: !status.is_success(),
};

let elapsed = start.elapsed();

if let Some(operation_metrics_attributes) = operation_metrics_attributes {
tracing::Span::current().record_gql_request((&operation_metrics_attributes).into());

response_metadata
.operation_name
.clone_from(&operation_metrics_attributes.name);
response_metadata.operation_type = Some(operation_metrics_attributes.ty.as_str());

self.operation_metrics.record(
GraphqlRequestMetricsAttributes {
operation: operation_metrics_attributes,
Expand All@@ -279,7 +264,7 @@ impl<R: Runtime> Engine<R> {
tracing::debug!(target: GRAFBASE_TARGET, "{message}")
}

HttpGraphqlResponse::build(response, None, response_metadata)
HttpGraphqlResponse::build(response, None)
}
.instrument(span)
.await
Expand DownExpand Up@@ -428,9 +413,9 @@ impl<'ctx, R: Runtime> PreExecutionContext<'ctx, R> {

if let Some(operation) = self.operation_cache.get(&cache_key).await {
Ok(operation)
} else if let Some(persisted_query) = document_fut {
match persisted_query.await {
Ok(query) => Err((cache_key, Some(query))),
} else if let Some(document_fut) = document_fut {
match document_fut.await {
Ok(document) => Err((cache_key, Some(document))),
Err(err) => return Err((None, Response::pre_execution_error(err))),
}
} else {
Expand All@@ -440,8 +425,8 @@ impl<'ctx, R: Runtime> PreExecutionContext<'ctx, R> {

let operation = match result {
Ok(operation) => operation,
Err((cache_key, query)) => {
if let Some(query) = query {
Err((cache_key, document)) => {
if let Some(query) = document {
request.query = query
}
let operation = Operation::build(&self.schema, &request)
Expand Down
45 changes: 12 additions & 33 deletions engine/crates/engine-v2/src/engine/cache.rs
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
use std::borrow::Cow;

use base64::{display::Base64Display, engine::general_purpose::URL_SAFE_NO_PAD};
use engine::PersistedQueryRequestExtension;
use schema::Schema;
Expand All@@ -6,8 +8,6 @@ use super::SchemaVersion;

mod namespaces {
pub const OPERATION: &str = "op";
pub const TRUSTED_DOCUMENT: &str = "tdoc";
pub const APQ: &str = "apq";
}

/// Unique cache key that generates a URL-safe string.
Expand All@@ -18,18 +18,11 @@ pub(super) enum Key<'a> {
schema_version: &'a SchemaVersion,
document: Document<'a>,
},
TrustedDocument {
client_name: &'a str,
document_id: &'a str,
},
Apq {
ext: &'a PersistedQueryRequestExtension,
},
}

pub(super) enum Document<'a> {
PersistedQueryExt(&'a PersistedQueryRequestExtension),
Id(&'a str),
AutomaticallyPersistedQuery(&'a PersistedQueryRequestExtension),
TrustedDocumentId { client_name: &'a str, doc_id: Cow<'a, str> },
Text(&'a str),
}

Expand All@@ -56,21 +49,24 @@ impl std::fmt::Display for Key<'_> {
// operation name.
hasher.update(&[0x00]);
match document {
Document::PersistedQueryExt(ext) => {
Document::AutomaticallyPersistedQuery(ext) => {
hasher.update(b"apq");
hasher.update(&[0x00]);
hasher.update(&ext.version.to_ne_bytes());
hasher.update(&ext.sha256_hash);
}
Document::Id(doc_id) => {
Document::TrustedDocumentId { client_name, doc_id } => {
hasher.update(b"docid");
hasher.update(&[0x00]);
hasher.update(&client_name.len().to_ne_bytes());
hasher.update(client_name.as_bytes());
hasher.update(&doc_id.len().to_ne_bytes());
hasher.update(doc_id.as_bytes());
}
Document::Text(query) => {
hasher.update(b"query");
Document::Text(document) => {
hasher.update(b"doc");
hasher.update(&[0x00]);
hasher.update(query.as_bytes());
hasher.update(document.as_bytes());
}
}
let hash = hasher.finalize();
Expand All@@ -81,23 +77,6 @@ impl std::fmt::Display for Key<'_> {
Base64Display::new(hash.as_bytes(), &URL_SAFE_NO_PAD)
))
}
Key::TrustedDocument {
client_name,
document_id,
} => f.write_fmt(format_args!(
"{}.{}.{}",
namespaces::TRUSTED_DOCUMENT,
Base64Display::new(client_name.as_bytes(), &URL_SAFE_NO_PAD),
Base64Display::new(document_id.as_bytes(), &URL_SAFE_NO_PAD)
)),
Key::Apq {
ext: PersistedQueryRequestExtension { version, sha256_hash },
} => f.write_fmt(format_args!(
"{}.{}.{}",
namespaces::APQ,
version,
Base64Display::new(sha256_hash, &URL_SAFE_NO_PAD)
)),
}
}
}
4 changes: 2 additions & 2 deletions engine/crates/engine-v2/src/engine/runtime.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,14 +4,14 @@ use runtime::{entity_cache::EntityCache, fetch::Fetcher, kv::KvStore, rate_limit

pub trait Runtime: Send + Sync + 'static {
type Hooks: runtime::hooks::Hooks;
type CacheFactory: runtime::hot_cache::HotCacheFactory;
type OperationCacheFactory: runtime::operation_cache::OperationCacheFactory;

fn fetcher(&self) -> &Fetcher;
fn kv(&self) -> &KvStore;
fn trusted_documents(&self) -> &runtime::trusted_documents_client::Client;
fn meter(&self) -> &Meter;
fn hooks(&self) -> &Self::Hooks;
fn cache_factory(&self) -> &Self::CacheFactory;
fn operation_cache_factory(&self) -> &Self::OperationCacheFactory;
fn rate_limiter(&self) -> &RateLimiter;
fn sleep(&self, duration: std::time::Duration) -> BoxFuture<'static, ()>;
fn entity_cache(&self) -> &dyn EntityCache;
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })(); Gb 7247 remove now useless response metadata simplify operation by hackal · Pull Request #9 · CallstackAI/grafbase-clone · GitHub
Skip to content
Open
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
39 changes: 39 additions & 0 deletions .callstack.yml
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
pr_review:
# Default: true
auto_run: true
modules:
# Automatically create a description summarizing the changes in pull request.
description:
enabled: true
diagram: false

# Find potential bugs in pull request changes or related files.
bug_hunter:
enabled: true
# Include fixes to possible bugs.
suggestions: true

# Suggest improvements to added code.
code_suggestions:
enabled: true

# Suggest changes to follow defined code conventions.
code_conventions:
enabled: false
# Describe your code conventions in plain text.
conventions: |
E.g. Exported variables, functions, classes and methods should be defined before private.


# Point out any typos or grammatical errors in variable names, texts, comments.
grammar:
enabled: false

# Suggest performance improvements to added code.
performance:
enabled: true

# Find potential security issues in added code.
security:
enabled: true

29 changes: 29 additions & 0 deletions .github/workflows/callstack-reviewer.yml
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
name: Callstack.ai PR Review

on:
workflow_dispatch:
inputs:
config:
type: string
description: "config for reviewer"
required: true
head:
type: string
description: "head commit sha"
required: true
base:
type: string
description: "base commit sha"
required: false

jobs:
callstack_pr_review_job:
runs-on: ubuntu-latest
steps:
- name: Review PR
uses: callstackai/action@main
with:
config: ${{ inputs.config }}
head: ${{ inputs.head }}
export: /code/chats.json

4 changes: 2 additions & 2 deletions cli/crates/federated-dev/src/dev/gateway_nanny.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -108,7 +108,7 @@ pub struct CliRuntime {

impl engine_v2::Runtime for CliRuntime {
type Hooks = ();
type CacheFactory = ();
type OperationCacheFactory = ();

fn fetcher(&self) -> &runtime::fetch::Fetcher {
&self.fetcher
Expand All@@ -130,7 +130,7 @@ impl engine_v2::Runtime for CliRuntime {
&()
}

fn cache_factory(&self) -> &() {
fn operation_cache_factory(&self) -> &() {
&()
}

Expand Down
37 changes: 11 additions & 26 deletions engine/crates/engine-v2/src/engine.rs
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
use ::runtime::{
auth::AccessToken,
hooks::Hooks,
hot_cache::{CachedDataKind, HotCache, HotCacheFactory},
operation_cache::{OperationCache, OperationCacheFactory},
rate_limiting::RateLimitKey,
};
use async_runtime::stream::StreamExt as _;
Expand All@@ -27,7 +27,7 @@ use web_time::Instant;

use crate::{
execution::{ExecutableOperation, PreExecutionContext},
http_response::{HttpGraphqlResponse, HttpGraphqlResponseExtraMetadata},
http_response::HttpGraphqlResponse,
operation::{Operation, PreparedOperation, Variables},
response::{ErrorCode, GraphqlError, Response},
websocket,
Expand DownExpand Up@@ -59,8 +59,7 @@ pub struct Engine<R: Runtime> {
operation_metrics: GraphqlOperationMetrics,
auth: AuthService,
retry_budgets: RetryBudgets,
trusted_documents_cache: <R::CacheFactory as HotCacheFactory>::Cache<String>,
operation_cache: <R::CacheFactory as HotCacheFactory>::Cache<Arc<PreparedOperation>>,
operation_cache: <R::OperationCacheFactory as OperationCacheFactory>::Cache<Arc<PreparedOperation>>,
}

impl<R: Runtime> Engine<R> {
Expand DownExpand Up@@ -90,8 +89,7 @@ impl<R: Runtime> Engine<R> {
auth,
retry_budgets: RetryBudgets::build(&schema),
operation_metrics: GraphqlOperationMetrics::build(runtime.meter()),
trusted_documents_cache: runtime.cache_factory().create(CachedDataKind::TrustedDocument).await,
operation_cache: runtime.cache_factory().create(CachedDataKind::Operation).await,
operation_cache: runtime.operation_cache_factory().create().await,
schema,
runtime,
}
Expand All@@ -107,14 +105,13 @@ impl<R: Runtime> Engine<R> {
let format = headers.typed_get::<StreamingFormat>();
let request_context = match self.create_request_context(headers).await {
Ok(context) => context,
Err(response) => return HttpGraphqlResponse::build(response, format, Default::default()),
Err(response) => return HttpGraphqlResponse::build(response, format),
};

if let Err(err) = self.runtime.rate_limiter().limit(&RateLimitKey::Global).await {
return HttpGraphqlResponse::build(
Response::pre_execution_error(GraphqlError::new(err.to_string(), ErrorCode::RateLimited)),
format,
Default::default(),
);
}

Expand All@@ -128,7 +125,6 @@ impl<R: Runtime> Engine<R> {
HttpGraphqlResponse::build(
Response::execution_error(GraphqlError::new("Gateway timeout", ErrorCode::GatewayTimeout)),
format,
Default::default(),
)
}
.boxed(),
Expand DownExpand Up@@ -239,22 +235,11 @@ impl<R: Runtime> Engine<R> {
let (operation_metrics_attributes, response) = ctx.execute_single(request).await;
let status = response.status();

let mut response_metadata = HttpGraphqlResponseExtraMetadata {
operation_name: None,
operation_type: None,
has_errors: !status.is_success(),
};

let elapsed = start.elapsed();

if let Some(operation_metrics_attributes) = operation_metrics_attributes {
tracing::Span::current().record_gql_request((&operation_metrics_attributes).into());

response_metadata
.operation_name
.clone_from(&operation_metrics_attributes.name);
response_metadata.operation_type = Some(operation_metrics_attributes.ty.as_str());

self.operation_metrics.record(
GraphqlRequestMetricsAttributes {
operation: operation_metrics_attributes,
Expand All@@ -279,7 +264,7 @@ impl<R: Runtime> Engine<R> {
tracing::debug!(target: GRAFBASE_TARGET, "{message}")
}

HttpGraphqlResponse::build(response, None, response_metadata)
HttpGraphqlResponse::build(response, None)
}
.instrument(span)
.await
Expand DownExpand Up@@ -428,9 +413,9 @@ impl<'ctx, R: Runtime> PreExecutionContext<'ctx, R> {

if let Some(operation) = self.operation_cache.get(&cache_key).await {
Ok(operation)
} else if let Some(persisted_query) = document_fut {
match persisted_query.await {
Ok(query) => Err((cache_key, Some(query))),
} else if let Some(document_fut) = document_fut {
match document_fut.await {
Ok(document) => Err((cache_key, Some(document))),
Err(err) => return Err((None, Response::pre_execution_error(err))),
}
} else {
Expand All@@ -440,8 +425,8 @@ impl<'ctx, R: Runtime> PreExecutionContext<'ctx, R> {

let operation = match result {
Ok(operation) => operation,
Err((cache_key, query)) => {
if let Some(query) = query {
Err((cache_key, document)) => {
if let Some(query) = document {
request.query = query
}
let operation = Operation::build(&self.schema, &request)
Expand Down
45 changes: 12 additions & 33 deletions engine/crates/engine-v2/src/engine/cache.rs
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
use std::borrow::Cow;

use base64::{display::Base64Display, engine::general_purpose::URL_SAFE_NO_PAD};
use engine::PersistedQueryRequestExtension;
use schema::Schema;
Expand All@@ -6,8 +8,6 @@ use super::SchemaVersion;

mod namespaces {
pub const OPERATION: &str = "op";
pub const TRUSTED_DOCUMENT: &str = "tdoc";
pub const APQ: &str = "apq";
}

/// Unique cache key that generates a URL-safe string.
Expand All@@ -18,18 +18,11 @@ pub(super) enum Key<'a> {
schema_version: &'a SchemaVersion,
document: Document<'a>,
},
TrustedDocument {
client_name: &'a str,
document_id: &'a str,
},
Apq {
ext: &'a PersistedQueryRequestExtension,
},
}

pub(super) enum Document<'a> {
PersistedQueryExt(&'a PersistedQueryRequestExtension),
Id(&'a str),
AutomaticallyPersistedQuery(&'a PersistedQueryRequestExtension),
TrustedDocumentId { client_name: &'a str, doc_id: Cow<'a, str> },
Text(&'a str),
}

Expand All@@ -56,21 +49,24 @@ impl std::fmt::Display for Key<'_> {
// operation name.
hasher.update(&[0x00]);
match document {
Document::PersistedQueryExt(ext) => {
Document::AutomaticallyPersistedQuery(ext) => {
hasher.update(b"apq");
hasher.update(&[0x00]);
hasher.update(&ext.version.to_ne_bytes());
hasher.update(&ext.sha256_hash);
}
Document::Id(doc_id) => {
Document::TrustedDocumentId { client_name, doc_id } => {
hasher.update(b"docid");
hasher.update(&[0x00]);
hasher.update(&client_name.len().to_ne_bytes());
hasher.update(client_name.as_bytes());
hasher.update(&doc_id.len().to_ne_bytes());
hasher.update(doc_id.as_bytes());
}
Document::Text(query) => {
hasher.update(b"query");
Document::Text(document) => {
hasher.update(b"doc");
hasher.update(&[0x00]);
hasher.update(query.as_bytes());
hasher.update(document.as_bytes());
}
}
let hash = hasher.finalize();
Expand All@@ -81,23 +77,6 @@ impl std::fmt::Display for Key<'_> {
Base64Display::new(hash.as_bytes(), &URL_SAFE_NO_PAD)
))
}
Key::TrustedDocument {
client_name,
document_id,
} => f.write_fmt(format_args!(
"{}.{}.{}",
namespaces::TRUSTED_DOCUMENT,
Base64Display::new(client_name.as_bytes(), &URL_SAFE_NO_PAD),
Base64Display::new(document_id.as_bytes(), &URL_SAFE_NO_PAD)
)),
Key::Apq {
ext: PersistedQueryRequestExtension { version, sha256_hash },
} => f.write_fmt(format_args!(
"{}.{}.{}",
namespaces::APQ,
version,
Base64Display::new(sha256_hash, &URL_SAFE_NO_PAD)
)),
}
}
}
4 changes: 2 additions & 2 deletions engine/crates/engine-v2/src/engine/runtime.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,14 +4,14 @@ use runtime::{entity_cache::EntityCache, fetch::Fetcher, kv::KvStore, rate_limit

pub trait Runtime: Send + Sync + 'static {
type Hooks: runtime::hooks::Hooks;
type CacheFactory: runtime::hot_cache::HotCacheFactory;
type OperationCacheFactory: runtime::operation_cache::OperationCacheFactory;

fn fetcher(&self) -> &Fetcher;
fn kv(&self) -> &KvStore;
fn trusted_documents(&self) -> &runtime::trusted_documents_client::Client;
fn meter(&self) -> &Meter;
fn hooks(&self) -> &Self::Hooks;
fn cache_factory(&self) -> &Self::CacheFactory;
fn operation_cache_factory(&self) -> &Self::OperationCacheFactory;
fn rate_limiter(&self) -> &RateLimiter;
fn sleep(&self, duration: std::time::Duration) -> BoxFuture<'static, ()>;
fn entity_cache(&self) -> &dyn EntityCache;
Expand Down
Loading