Skip to content

Commit

Permalink
Merge branch 'develop' into mustache-docs
Browse files Browse the repository at this point in the history
  • Loading branch information
ibishal authored Mar 3, 2024
2 parents 7a3d581 + d9fabd6 commit 906ec64
Show file tree
Hide file tree
Showing 11 changed files with 342 additions and 75 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,5 @@ yarn-error.log*
.yarn/

.idea/
src/*/*.json
src/*/*.json
.vscode/
3 changes: 2 additions & 1 deletion docs/guides/client-tuning.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
---
title: Tuning Client for Performance
title: Client Tuning
description: Tuning client for performance
---

### HTTP (Hypertext Transfer Protocol)
Expand Down
56 changes: 56 additions & 0 deletions docs/guides/http-cache.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
---
title: Http Cache
description: A comprehensive guide to leverage HTTP cache for REST APIs using Tailcall
---

HTTP Caching in Tailcall is designed to enhance performance and minimize the frequency of requests to upstream services by caching HTTP responses. This guide explains the concept, benefits, and how to effectively implement HTTP caching within Tailcall.

### Understanding HTTP Caching

HTTP Caching involves saving copies of HTTP responses to serve identical future requests directly from the cache, bypassing the need for new API calls. This reduces latency, conserves bandwidth, and alleviates the load on upstream services by utilizing a cache keyed by request URLs and headers.

By default, HTTP caching is turned off in Tailcall. Enabling it requires setting the `httpCache` parameter to `true` in the `@upstream` configuration. Tailcall employs a in-memory _Least_Recently_Used_ (LRU) cache mechanism to manage stored responses, adhering to upstream-provided caching directives like `Cache-Control` to optimize the caching process and minimize redundant upstream API requests.

### Enabling HTTP Caching

To activate HTTP caching, adjust the upstream configuration in Tailcall by setting `httpCache` to `true`, as shown in the following example:

```graphql
schema
@server(port: 4000)
@upstream(
baseURL: "https://api.example.com"
# highlight-start
httpCache: true
# highlight-end
) {
query: Query
}
```

This configuration instructs Tailcall to cache responses from the designated upstream API.

### Cache-Control headers in responses

Enabling the `cacheControlHeader` setting in Tailcall ensures that [Cache-Control] headers are included in the responses returned to clients. When activated, Tailcall dynamically sets the `max-age` directive in the `Cache-Control` header to the minimum `max-age` value encountered in any of the responses from upstream services. This approach guarantees that the caching duration for the composite response is conservative, aligning with the shortest cache validity period provided by the upstream services. By default, this feature is disabled (`false`), meaning Tailcall will not modify or add `Cache-Control` headers unless explicitly instructed to do so. This setting is distinct from the general HTTP cache setting, which controls whether responses are cached internally by Tailcall; `cacheControlHeader` specifically controls the caching instructions sent to clients.

Here is how you can enable the `cacheControlHeader` setting within your Tailcall schema to apply these caching instructions:

```graphql
schema @server(cacheControlHeader: true) {
query: Query
mutation: Mutation
}
```

[cache-control]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control

### Best Practices for Enhancing REST API Performance with Tailcall

The combination of `httpCache` and `cacheControlHeader` provides a comprehensive caching solution. While `httpCache` focuses on internal caching to reduce the impact of high latency and frequent requests, `cacheControlHeader` manages client-side caching policies, ensuring an optimal balance between performance, data freshness, and efficient resource use.

These caching primitives are beneficial for REST APIs that are latency-sensitive, have a high rate of request repetition, or come with explicit caching headers indicating cacheable responses. Together, they tackle the common challenges of optimizing REST API performance by minimizing unnecessary network traffic and server load while ensuring response accuracy.

To further enhance the performance of any API with Tailcall, integrating the [@cache] directive offers protocol agnostic control over caching at the field level within a GraphQL schema.

[@cache]: /docs/operators/cache.md
53 changes: 0 additions & 53 deletions docs/guides/operator-composition.md

This file was deleted.

1 change: 1 addition & 0 deletions docs/operators/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ Certainly! Here's the table with hyperlinks added back to the operator names:
| [@graphQL](graphql.md) | Resolves a field or node by a GraphQL API. |
| [@grpc](grpc.md) | Resolves a field or node by a gRPC API. |
| [@http](http.md) | Resolves a field or node by a REST API. |
| [@link](link.md) | Imports external resources such as config files, certs, protobufs, etc in the schema. |
| [@modify](modify.md) | Enables changes to attributes of fields or nodes in the schema. |
| [@omit](omit.md) | Excludes fields or nodes from the generated schema, making them inaccessible through the GraphQL API. |
| [@server](server.md) | Provides server configurations for behavior tuning and tailcall optimization in specific use-cases. |
Expand Down
68 changes: 68 additions & 0 deletions docs/operators/link.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
---
title: "@link"
---

The **@link** operator is used for bringing external resources into your GraphQL schema. It makes it easier to include configurations, .proto files for gRPC services, and other files into your schema. With this operator, external resources are either merged with or used effectively in the importing configuration.

## How it Works

The `@link` directive requires specifying a source `src`, the resource's type `type`, and an optional identifier `id`.

- `src`: The source of the link is defined here. It can be either a URL or a file path. When a file path is given, it's relative to the file's location that is importing the link.

- `type`: This specifies the link's type, which determines how the imported resource is integrated into the schema. For a list of supported types, see the [Supported Types](#supported-types) section.

- `id`: This is an optional field that assigns a unique identifier to the link. It's helpful for referring to the link within the schema.

## Example

The following example illustrates how to utilize the `@link` directive to incorporate a Protocol Buffers (.proto) file for a gRPC service into your GraphQL schema.

```graphql showLineNumbers
schema
@server(port: 8000, graphiql: true)
@upstream(baseURL: "http://news.local", httpCache: true, batch: {delay: 10})
@link(id: "news", src: "../src/grpc/news.proto", type: Protobuf) {
query: Query
}

type Query {
news: NewsData! @grpc(method: "news.NewsService.GetAllNews")
}

type News {
id: Int
title: String
body: String
postImage: String
}

type NewsData {
news: [News]!
}
```

## Supported Types

The `@link` directive supports the following types of links:

- `Config`: Imports a schema configuration file. During the merge, settings from the imported file override those in the main schema for any overlaps, facilitating a modular and scalable approach to schema configuration. The operation is morally equivalent to tailcall's [compose](/docs/guides/cli.md#compose) command.

- `Protobuf`: Imports a .proto file for gRPC services. This type facilitates the integration of gRPC services into your GraphQL schema by allowing the inclusion of Protocol Buffers definitions. It enables the GraphQL server to communicate with gRPC services directly. For integrating gRPC services, refer to [gRPC Integration Guide](/docs/guides/grpc.md).

- `Script`: A link to an external JavaScript file that listens on every HTTP request response event. This allows for the execution of custom logic or filters based on the request and response. Example usage:

```javascript showLineNumbers
function onRequest({request}) {
// Add a custom header for all outgoing responses
request.headers["X-Custom-Header"] = "Processed"

// Return the updated request
return {request}
}
```

- `Cert`: Imports a SSL/TLS certificate for HTTPS.
- `Key`: Imports a SSL/TLS private key for HTTPS.

Each type serves a specific purpose, enabling the flexible integration of external resources into your GraphQL schema.
19 changes: 16 additions & 3 deletions src/components/contact/Hello.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,20 @@ import Heading from "@theme/Heading"
import toast, {Toaster} from "react-hot-toast"
import Grid from "@site/static/images/about/grid-large.svg"
import LinkButton from "../shared/LinkButton"
import {analyticsHandler} from "@site/src/utils"
import {analyticsHandler, validateEmail} from "@site/src/utils"
import {Theme, radioOptions, zapierLink} from "@site/src/constants"

const Hello = (): JSX.Element => {
const [email, setEmail] = useState<string>("")
const [message, setMessage] = useState<string>("")
const [stage, setStage] = useState<string>("")
const [isValid, setIsValid] = useState<boolean>(true)

const sendData = useCallback(async () => {
if (!validateEmail(email)) {
setIsValid(false)
return
}
const response = await fetch(zapierLink, {
method: "POST",
body: JSON.stringify({
Expand All @@ -31,6 +36,7 @@ const Hello = (): JSX.Element => {
setEmail("")
setMessage("")
setStage("")
setIsValid(true)
}
}, [email, message, stage])

Expand All @@ -56,10 +62,17 @@ const Hello = (): JSX.Element => {
name="email"
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
className="border border-solid border-tailCall-border-light-500 rounded-lg font-space-grotesk h-11 w-[95%] sm:w-[480px] p-SPACE_03 text-content-small outline-none focus:border-x-tailCall-light-700"
onChange={(e) => {
setEmail(e.target.value)
if (!isValid) setIsValid(true)
}}
className={`border border-solid border-tailCall-border-light-500 rounded-lg font-space-grotesk h-11 w-[95%] sm:w-[480px]
p-SPACE_03 text-content-small outline-none focus:border-x-tailCall-light-700 ${
isValid ? "is-valid" : "is-invalid"
}`}
placeholder="[email protected]"
/>
{!isValid && <div className="text-red-400">Please enter a valid email.</div>}
</div>

<div className="flex flex-col space-y-SPACE_02">
Expand Down
Loading

0 comments on commit 906ec64

Please sign in to comment.