├── .editorconfig ├── .github └── workflows │ └── build_test_publish.yaml ├── .gitignore ├── .npmignore ├── .nvmrc ├── CHANGELOG.md ├── Cargo.lock ├── Cargo.toml ├── LICENSE ├── README.md ├── package-lock.json ├── package.json ├── rust-toolchain.toml ├── src ├── connector.ts ├── error.ts ├── index.ts ├── instrumentation.ts ├── logging.ts ├── schema │ ├── index.ts │ ├── schema.generated.json │ ├── schema.generated.ts │ ├── schema.generated.ts.patch │ └── version.generated.ts └── server.ts ├── tsconfig.json └── typegen ├── Cargo.toml ├── regenerate-schema.sh └── src └── main.rs /.editorconfig: -------------------------------------------------------------------------------- 1 | # EditorConfig is awesome: https://EditorConfig.org 2 | 3 | # top-most EditorConfig file 4 | root = true 5 | 6 | [*] 7 | indent_style = space 8 | indent_size = 2 9 | end_of_line = lf 10 | charset = utf-8 11 | trim_trailing_whitespace = true 12 | insert_final_newline = true 13 | 14 | [*.rs] 15 | indent_size = 4 16 | -------------------------------------------------------------------------------- /.github/workflows/build_test_publish.yaml: -------------------------------------------------------------------------------- 1 | name: "Build, Test, Publish" 2 | on: 3 | pull_request: 4 | branches: 5 | - main 6 | push: 7 | branches: 8 | - 'main' 9 | tags: 10 | - v** 11 | jobs: 12 | build: 13 | runs-on: ubuntu-latest 14 | steps: 15 | - uses: actions/checkout@v4 16 | - uses: actions/setup-node@v3 17 | with: 18 | node-version-file: .nvmrc 19 | registry-url: 'https://registry.npmjs.org' 20 | cache: 'npm' 21 | - run: npm ci 22 | - run: npm run build 23 | 24 | publish: 25 | needs: build 26 | runs-on: ubuntu-latest 27 | if: ${{ startsWith(github.ref, 'refs/tags/v') }} 28 | steps: 29 | - uses: actions/checkout@v4 30 | - uses: actions/setup-node@v3 31 | with: 32 | node-version-file: .nvmrc 33 | registry-url: 'https://registry.npmjs.org' 34 | cache: 'npm' 35 | - run: | 36 | PACKAGE_VERSION=`npm version | sed -rn "2 s/.*: '([^']*)'.*/\1/g; 2 p"` 37 | TAG=`echo "$GITHUB_REF"| sed -r "s#.*/##g"` 38 | echo '$TAG' = "$TAG" 39 | echo '$GITHUB_REF' = "$GITHUB_REF" 40 | echo '$PACKAGE_VERSION' = "$PACKAGE_VERSION" 41 | if [ "$TAG" = "v$PACKAGE_VERSION" ] 42 | then 43 | echo "Success! Versions match." 44 | else 45 | echo "Package version (v$PACKAGE_VERSION) must match tag (GITHUB_REF: $GITHUB_REF) in order to publish" 1>&2 46 | exit 1 47 | fi 48 | - run: npm ci 49 | - run: npm run build 50 | - run: npm publish --access public 51 | env: 52 | NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} 53 | 54 | - name: Get version from tag 55 | id: get-version 56 | run: | 57 | echo "tagged_version=${GITHUB_REF#refs/tags/v}" >> $GITHUB_OUTPUT 58 | shell: bash 59 | 60 | - uses: mindsers/changelog-reader-action@v2 61 | id: changelog-reader 62 | with: 63 | version: ${{ steps.get-version.outputs.tagged_version }} 64 | path: ./CHANGELOG.md 65 | 66 | - uses: softprops/action-gh-release@v1 67 | with: 68 | draft: false 69 | tag_name: v${{ steps.get-version.outputs.tagged_version }} 70 | body: ${{ steps.changelog-reader.outputs.changes }} 71 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | target 3 | dist 4 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | target 3 | typegen 4 | Cargo.lock 5 | Cargo.toml 6 | example 7 | -------------------------------------------------------------------------------- /.nvmrc: -------------------------------------------------------------------------------- 1 | v18.18.2 2 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # NDC TypeScript SDK Changelog 2 | 3 | ## Unreleased changes 4 | 5 | ## [8.1.0] - 2025-05-12 6 | 7 | - Increased `bodyLimit` from 1mb to 30mb 8 | 9 | ## [8.0.0] - 2025-03-13 10 | **Breaking changes** since v7.0.0 ([#39](https://github.com/hasura/ndc-sdk-typescript/pull/39), [#40](https://github.com/hasura/ndc-sdk-typescript/pull/40), [#42](https://github.com/hasura/ndc-sdk-typescript/pull/42), [#43](https://github.com/hasura/ndc-sdk-typescript/pull/43)): 11 | - Updated to support [v0.2.0 of the NDC Spec](https://hasura.github.io/ndc-spec/specification/changelog.html#020). This is a very large update which adds new features and some breaking changes. 12 | - If the [`X-Hasura-NDC-Version`](https://hasura.github.io/ndc-spec/specification/versioning.html) header is sent, the SDK will validate that the connector supports the incoming request's version and reject it if it does not. If no header is sent, no action is taken. 13 | 14 | ## [8.0.0-rc.1] - 2025-01-30 15 | - Updated to support the latest release candidate (rc.3) of [v0.2.0 of the NDC Spec](https://hasura.github.io/ndc-spec/specification/changelog.html#020) ([#42](https://github.com/hasura/ndc-sdk-typescript/pull/42)) 16 | 17 | ## [8.0.0-rc.0] - 2025-01-08 18 | **Breaking changes** ([#39](https://github.com/hasura/ndc-sdk-typescript/pull/39), [#40](https://github.com/hasura/ndc-sdk-typescript/pull/40)): 19 | - Updated to support [v0.2.0 of the NDC Spec](https://hasura.github.io/ndc-spec/specification/changelog.html#020). This is a very large update which adds new features and some breaking changes. 20 | - If the [`X-Hasura-NDC-Version`](https://hasura.github.io/ndc-spec/specification/versioning.html) header is sent, the SDK will validate that the connector supports the incoming request's version and reject it if it does not. If no header is sent, no action is taken. 21 | 22 | ## [7.0.0] - 2024-09-20 23 | - Added support for exporting OpenTelemetry traces and metrics over GRPC. A new environment variable `OTEL_EXPORTER_OTLP_PROTOCOL` lets you switch between `http/protobuf` and `grpc`. 24 | - **Breaking change**: the default OpenTelemetry exporter has changed from `http/protobuf` sending to `http://localhost:4318` to `grpc` sending to `http://localhost:4317`. To return to the old defaults, set the following environment variables: 25 | - `OTEL_EXPORTER_OTLP_PROTOCOL="http/protobuf"` 26 | - `OTEL_EXPORTER_OTLP_ENDPOINT="http://localhost:4318"` 27 | 28 | ## [6.1.0] - 2024-08-26 29 | - Updated to support [v0.1.6 of the NDC Spec](https://hasura.github.io/ndc-spec/specification/changelog.html#016) ([#37](https://github.com/hasura/ndc-sdk-typescript/pull/37)) 30 | - Support for [querying nested collections](https://hasura.github.io/ndc-spec/specification/queries/filtering.html#nested-collections) inside an EXISTS expression in a predicate 31 | 32 | ## [6.0.0] - 2024-08-08 33 | Breaking changes ([#36](https://github.com/hasura/ndc-sdk-typescript/pull/36)): 34 | - `Connector.healthCheck` has been removed and replaced with `Connector.getHealthReadiness`, which only returns whether the connector is able to accept requests, not whether any underlying connections to data sources actually work. 35 | - The `/health` endpoint is now unauthorized, allowing healthchecks to be performed without authorization. 36 | - `Connector.getCapabilities` now returns `Capabilities` instead of `CapabilitiesResponse`. The SDK will now take care of adding the correct NDC version to the `Capabilities` on behalf of the connector. 37 | 38 | ## [5.2.0] - 2024-07-30 39 | - The connector now listens on both ipv4 and ipv6 interfaces by default. This can be configured by using the `HASURA_CONNECTOR_HOST` environment variable, which sets the host the web server listens on. ([#34](https://github.com/hasura/ndc-sdk-typescript/pull/34)) 40 | - Updated to support [v0.1.5 of the NDC Spec](https://hasura.github.io/ndc-spec/specification/changelog.html#015) ([#35](https://github.com/hasura/ndc-sdk-typescript/pull/35)) 41 | - There are no real changes in this version; it is a version number-only change 42 | 43 | ## [5.1.0] - 2024-06-19 44 | - Updated to support [v0.1.4 of the NDC Spec](https://hasura.github.io/ndc-spec/specification/changelog.html#014) ([#33](https://github.com/hasura/ndc-sdk-typescript/pull/33)) 45 | - Support for [aggregates](https://hasura.github.io/ndc-spec/specification/queries/aggregates.html) over nested fields 46 | 47 | ## [5.0.0] - 2024-05-31 48 | - Updated to support [v0.1.3 of the NDC Spec](https://hasura.github.io/ndc-spec/specification/changelog.html#013) ([#32](https://github.com/hasura/ndc-sdk-typescript/pull/32)) 49 | - Breaking change: new `nested_fields` property on `QueryCapabilities`; set it to `{}` to retain previous v0.1.2 semantics and not support new v0.1.3 capabilities. 50 | - Support [field arguments](https://hasura.github.io/ndc-spec/specification/queries/arguments.html#field-arguments) 51 | - Support [filtering](https://hasura.github.io/ndc-spec/specification/queries/filtering.html#referencing-nested-fields-within-columns) and [ordering](https://hasura.github.io/ndc-spec/specification/queries/sorting.html#type-column) by nested fields 52 | - Added a [`biginteger` type representation](https://hasura.github.io/ndc-spec/specification/schema/scalar-types.html#type-representations) 53 | 54 | ## [4.6.0] - 2024-04-17 55 | - Use [`prom-client`](https://github.com/siimon/prom-client) to implement the metrics endpoint ([#29](https://github.com/hasura/ndc-sdk-typescript/pull/29)) 56 | - Allow any error code in custom HTTP responses ([#30](https://github.com/hasura/ndc-sdk-typescript/pull/30)) 57 | 58 | ## [4.5.0] - 2024-04-17 59 | - Support [b3](https://github.com/open-telemetry/opentelemetry-js/tree/main/packages/opentelemetry-propagator-b3#b3-formats) (zipkin) OpenTelemetry trace propagation headers ([#28](https://github.com/hasura/ndc-sdk-typescript/pull/28)) 60 | 61 | ## [4.4.0] - 2024-04-05 62 | - Updated to support [v0.1.2 of the NDC Spec](https://hasura.github.io/ndc-spec/specification/changelog.html#012) 63 | - More precise [type representations](https://hasura.github.io/ndc-spec/specification/schema/scalar-types.html#type-representations) of scalar types were added and the general numeric ones were deprecated (`number` and `integer`) 64 | 65 | ## [4.3.0] - 2024-03-26 66 | - Updated to support [v0.1.1 of the NDC Spec](https://hasura.github.io/ndc-spec/specification/changelog.html#011) 67 | - A more [precise definition of equality operators](https://hasura.github.io/ndc-spec/specification/schema/scalar-types.html#note-syntactic-equality) 68 | - Scalar types can now [specify a representation](https://hasura.github.io/ndc-spec/specification/schema/scalar-types.html#type-representations), including an enum representation 69 | 70 | ## [4.2.1] - 2024-02-28 71 | - Add `main` and `types` properties to the `package.json` to enable `node10` module resolution to be used by projects using legacy TypeScript compiler settings 72 | 73 | ## [4.2.0] - 2024-02-23 74 | - OpenTelemetry spans are now attributed with `internal.visibility: "user"` so that they show up in the Hasura Console 75 | - `@hasura/ndc-sdk-typescript/instrumentation` now exports `withActiveSpan` to wrap a span around a function and `withInternalActiveSpan` which does the same but without the `internal.visibility: "user"` attribute. 76 | - Automatic OpenTelemetry instrumentation for fetch requests has been added 77 | 78 | ## [4.1.0] - 2024-02-21 79 | - Add OpenTelemetry support 80 | - Set env var `OTEL_EXPORTER_OTLP_ENDPOINT` to the endpoint to send OpenTelemetry to 81 | - `OTEL_SERVICE_NAME` overrides the service name 82 | - Command line arguments `--otlp-endpoint` and `--service-name` have been removed in favour of the environment variables 83 | - Import `@hasura/ndc-sdk-typescript/instrumentation` to use `initTelemetry` to initialize OpenTelemetry earlier in your startup, if necessary 84 | 85 | ## [1.3.0] - 2024-02-21 86 | - Add OpenTelemetry support 87 | - Set env var `OTEL_EXPORTER_OTLP_ENDPOINT` to the endpoint to send OpenTelemetry to 88 | - `OTEL_SERVICE_NAME` overrides the service name 89 | - Command line arguments `--otlp_endpoint` and `--service-name` have been removed in favour of the environment variables 90 | - Import `@hasura/ndc-sdk-typescript/instrumentation` to use `initTelemetry` to initialize OpenTelemetry earlier in your startup, if necessary 91 | 92 | ## [4.0.0] - 2024-02-19 93 | Breaking change: support for the [Connector Deployment Spec](https://github.com/hasura/ndc-hub/blob/main/rfcs/0000-deployment.md). 94 | 95 | - The connector configuration server has been removed 96 | - The way configuration is handled on `Connector` interface has changed 97 | - `getRawConfigurationSchema`, `makeEmptyConfiguration`, `updateConfiguration` have been removed. 98 | - `parseConfiguation` replaces `validateRawConfiguration`, and is given the directory path in which the connector's configuration files can be found 99 | - The `RawConfiguration` type parameter has been removed 100 | - The default port has changed from 8100 to 8080 101 | - The command line arguments passed to the `serve` command have changed: 102 | - The `--configuration` argument now takes the connector's configuration directory. Its associated environment variable is now `HASURA_CONFIGURATION_DIRECTORY` 103 | - The `--otlp_endpoint` argument has been renamed to `--otlp-endpoint` and its environment variable is now `OTEL_EXPORTER_OTLP_ENDPOINT` 104 | - The `PORT` environment variable has changed to `HASURA_CONNECTOR_PORT` 105 | - The `SERVICE_TOKEN_SECRET` environment variable has changed to `HASURA_SERVICE_TOKEN_SECRET` 106 | - The `LOG_LEVEL` environment variable has changed to `HASURA_LOG_LEVEL` 107 | - The `PRETTY_PRINT_LOGS` environment variable has changed to `HASURA_PRETTY_PRINT_LOGS` 108 | 109 | ## [3.0.0] - 2024-02-13 110 | Breaking change: support for the [v0.1.0-rc.15 of NDC Spec](https://github.com/hasura/ndc-spec/compare/v0.1.0-rc.14...v0.1.0-rc.15). 111 | 112 | - The [mutation request/response format has changed](https://github.com/hasura/ndc-spec/pull/90). 113 | - `MutationOperation` fields are now defined as a `NestedField` 114 | - `MutationOperationResponse` now returns a single value rather than a rowset 115 | 116 | ## [2.0.0] - 2024-02-05 117 | Breaking change: support for the [v0.1.0-rc.14 of NDC Spec](https://github.com/hasura/ndc-spec/compare/v0.1.0-rc.13...v0.1.0-rc.14). 118 | 119 | - Function name formatting is now standard JavaScript `camelCase`. NDC types used for wire-transmission match the spec (snake_cased). 120 | - Added [nested field selections](https://github.com/hasura/ndc-spec/pull/70) (`Field.fields`) 121 | - Capabilities now only specifies [a single supported version](https://github.com/hasura/ndc-spec/pull/82) (`CapabilitiesResponse.version`) 122 | - `Expression.where` [renamed](https://github.com/hasura/ndc-spec/pull/87) to `Expression.predicate` 123 | - `PathElement.predicate` is now [optional](https://github.com/hasura/ndc-spec/pull/87) 124 | - Added [Predicate types](https://github.com/hasura/ndc-spec/blob/main/rfcs/0002-boolean-expression-types.md) (new `predicate` Type.type) 125 | - Added [mutation capability](https://github.com/hasura/ndc-spec/pull/80) 126 | - Comparison operators 127 | - [Changes to explain](https://github.com/hasura/ndc-spec/pull/85): 128 | - `Connector.explain` renamed to `Connector.queryExplain` and endpoint moved from `/explain` to `/query/explain`. 129 | - `Connector.mutationExplain` added with endpoint `/mutation/explain`. 130 | - `explain` capability moved to `query.explain`. `mutation.explain` capability added. 131 | - `ComparisonOperatorDefinition` now has `equal` and `in` as [two standard definitions](https://github.com/hasura/ndc-spec/pull/79/files) and custom operators can be defined. The equality operator is no longer required to be defined and must be explicitly defined. 132 | 133 | ## [1.2.8] - 2024-01-18 134 | - Add new `ConnectorError` types: 135 | - `UnprocessableContent`: The request could not be handled because, while the request was well-formed, it was not semantically correct. For example, a value for a custom scalar type was provided, but with an incorrect type 136 | - `BadGateway`: The request could not be handled because an upstream service was unavailable or returned an unexpected response, e.g., a connection to a database server failed 137 | - Generate TypeScript declaration maps for better "go to definition" tooling 138 | 139 | ## [1.2.7] - 2023-12-21 140 | - `get_serve_command` and `get_serve_configuration_command` now support creation without 141 | automatically starting servers. This allows usage in scenarios where a customized server startup 142 | is desired. 143 | 144 | ## [1.2.6] - 2023-12-15 145 | - added auth hook using secret token 146 | -------------------------------------------------------------------------------- /Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | version = 4 4 | 5 | [[package]] 6 | name = "android-tzdata" 7 | version = "0.1.1" 8 | source = "registry+https://github.com/rust-lang/crates.io-index" 9 | checksum = "e999941b234f3131b00bc13c22d06e8c5ff726d1b6318ac7eb276997bbb4fef0" 10 | 11 | [[package]] 12 | name = "android_system_properties" 13 | version = "0.1.5" 14 | source = "registry+https://github.com/rust-lang/crates.io-index" 15 | checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311" 16 | dependencies = [ 17 | "libc", 18 | ] 19 | 20 | [[package]] 21 | name = "autocfg" 22 | version = "1.2.0" 23 | source = "registry+https://github.com/rust-lang/crates.io-index" 24 | checksum = "f1fdabc7756949593fe60f30ec81974b613357de856987752631dea1e3394c80" 25 | 26 | [[package]] 27 | name = "base64" 28 | version = "0.22.1" 29 | source = "registry+https://github.com/rust-lang/crates.io-index" 30 | checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" 31 | 32 | [[package]] 33 | name = "bumpalo" 34 | version = "3.15.4" 35 | source = "registry+https://github.com/rust-lang/crates.io-index" 36 | checksum = "7ff69b9dd49fd426c69a0db9fc04dd934cdb6645ff000864d98f7e2af8830eaa" 37 | 38 | [[package]] 39 | name = "cc" 40 | version = "1.0.90" 41 | source = "registry+https://github.com/rust-lang/crates.io-index" 42 | checksum = "8cd6604a82acf3039f1144f54b8eb34e91ffba622051189e71b781822d5ee1f5" 43 | 44 | [[package]] 45 | name = "cfg-if" 46 | version = "1.0.0" 47 | source = "registry+https://github.com/rust-lang/crates.io-index" 48 | checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" 49 | 50 | [[package]] 51 | name = "chrono" 52 | version = "0.4.35" 53 | source = "registry+https://github.com/rust-lang/crates.io-index" 54 | checksum = "8eaf5903dcbc0a39312feb77df2ff4c76387d591b9fc7b04a238dcf8bb62639a" 55 | dependencies = [ 56 | "android-tzdata", 57 | "iana-time-zone", 58 | "num-traits", 59 | "serde", 60 | "windows-targets", 61 | ] 62 | 63 | [[package]] 64 | name = "core-foundation-sys" 65 | version = "0.8.6" 66 | source = "registry+https://github.com/rust-lang/crates.io-index" 67 | checksum = "06ea2b9bc92be3c2baa9334a323ebca2d6f074ff852cd1d7b11064035cd3868f" 68 | 69 | [[package]] 70 | name = "darling" 71 | version = "0.20.8" 72 | source = "registry+https://github.com/rust-lang/crates.io-index" 73 | checksum = "54e36fcd13ed84ffdfda6f5be89b31287cbb80c439841fe69e04841435464391" 74 | dependencies = [ 75 | "darling_core", 76 | "darling_macro", 77 | ] 78 | 79 | [[package]] 80 | name = "darling_core" 81 | version = "0.20.8" 82 | source = "registry+https://github.com/rust-lang/crates.io-index" 83 | checksum = "9c2cf1c23a687a1feeb728783b993c4e1ad83d99f351801977dd809b48d0a70f" 84 | dependencies = [ 85 | "fnv", 86 | "ident_case", 87 | "proc-macro2", 88 | "quote", 89 | "strsim", 90 | "syn 2.0.55", 91 | ] 92 | 93 | [[package]] 94 | name = "darling_macro" 95 | version = "0.20.8" 96 | source = "registry+https://github.com/rust-lang/crates.io-index" 97 | checksum = "a668eda54683121533a393014d8692171709ff57a7d61f187b6e782719f8933f" 98 | dependencies = [ 99 | "darling_core", 100 | "quote", 101 | "syn 2.0.55", 102 | ] 103 | 104 | [[package]] 105 | name = "deranged" 106 | version = "0.3.11" 107 | source = "registry+https://github.com/rust-lang/crates.io-index" 108 | checksum = "b42b6fa04a440b495c8b04d0e71b707c585f83cb9cb28cf8cd0d976c315e31b4" 109 | dependencies = [ 110 | "powerfmt", 111 | "serde", 112 | ] 113 | 114 | [[package]] 115 | name = "dyn-clone" 116 | version = "1.0.17" 117 | source = "registry+https://github.com/rust-lang/crates.io-index" 118 | checksum = "0d6ef0072f8a535281e4876be788938b528e9a1d43900b82c2569af7da799125" 119 | 120 | [[package]] 121 | name = "equivalent" 122 | version = "1.0.1" 123 | source = "registry+https://github.com/rust-lang/crates.io-index" 124 | checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5" 125 | 126 | [[package]] 127 | name = "fnv" 128 | version = "1.0.7" 129 | source = "registry+https://github.com/rust-lang/crates.io-index" 130 | checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" 131 | 132 | [[package]] 133 | name = "generate_types" 134 | version = "0.1.0" 135 | dependencies = [ 136 | "ndc-models", 137 | "schemars", 138 | "serde", 139 | "serde_derive", 140 | "serde_json", 141 | ] 142 | 143 | [[package]] 144 | name = "hashbrown" 145 | version = "0.12.3" 146 | source = "registry+https://github.com/rust-lang/crates.io-index" 147 | checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" 148 | 149 | [[package]] 150 | name = "hashbrown" 151 | version = "0.14.3" 152 | source = "registry+https://github.com/rust-lang/crates.io-index" 153 | checksum = "290f1a1d9242c78d09ce40a5e87e7554ee637af1351968159f4952f028f75604" 154 | 155 | [[package]] 156 | name = "hex" 157 | version = "0.4.3" 158 | source = "registry+https://github.com/rust-lang/crates.io-index" 159 | checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" 160 | 161 | [[package]] 162 | name = "iana-time-zone" 163 | version = "0.1.60" 164 | source = "registry+https://github.com/rust-lang/crates.io-index" 165 | checksum = "e7ffbb5a1b541ea2561f8c41c087286cc091e21e556a4f09a8f6cbf17b69b141" 166 | dependencies = [ 167 | "android_system_properties", 168 | "core-foundation-sys", 169 | "iana-time-zone-haiku", 170 | "js-sys", 171 | "wasm-bindgen", 172 | "windows-core", 173 | ] 174 | 175 | [[package]] 176 | name = "iana-time-zone-haiku" 177 | version = "0.1.2" 178 | source = "registry+https://github.com/rust-lang/crates.io-index" 179 | checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" 180 | dependencies = [ 181 | "cc", 182 | ] 183 | 184 | [[package]] 185 | name = "ident_case" 186 | version = "1.0.1" 187 | source = "registry+https://github.com/rust-lang/crates.io-index" 188 | checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" 189 | 190 | [[package]] 191 | name = "indexmap" 192 | version = "1.9.3" 193 | source = "registry+https://github.com/rust-lang/crates.io-index" 194 | checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99" 195 | dependencies = [ 196 | "autocfg", 197 | "hashbrown 0.12.3", 198 | "serde", 199 | ] 200 | 201 | [[package]] 202 | name = "indexmap" 203 | version = "2.2.6" 204 | source = "registry+https://github.com/rust-lang/crates.io-index" 205 | checksum = "168fb715dda47215e360912c096649d23d58bf392ac62f73919e831745e40f26" 206 | dependencies = [ 207 | "equivalent", 208 | "hashbrown 0.14.3", 209 | "serde", 210 | ] 211 | 212 | [[package]] 213 | name = "itoa" 214 | version = "1.0.10" 215 | source = "registry+https://github.com/rust-lang/crates.io-index" 216 | checksum = "b1a46d1a171d865aa5f83f92695765caa047a9b4cbae2cbf37dbd613a793fd4c" 217 | 218 | [[package]] 219 | name = "js-sys" 220 | version = "0.3.69" 221 | source = "registry+https://github.com/rust-lang/crates.io-index" 222 | checksum = "29c15563dc2726973df627357ce0c9ddddbea194836909d655df6a75d2cf296d" 223 | dependencies = [ 224 | "wasm-bindgen", 225 | ] 226 | 227 | [[package]] 228 | name = "libc" 229 | version = "0.2.153" 230 | source = "registry+https://github.com/rust-lang/crates.io-index" 231 | checksum = "9c198f91728a82281a64e1f4f9eeb25d82cb32a5de251c6bd1b5154d63a8e7bd" 232 | 233 | [[package]] 234 | name = "log" 235 | version = "0.4.21" 236 | source = "registry+https://github.com/rust-lang/crates.io-index" 237 | checksum = "90ed8c1e510134f979dbc4f070f87d4313098b704861a105fe34231c70a3901c" 238 | 239 | [[package]] 240 | name = "ndc-models" 241 | version = "0.2.0" 242 | source = "git+http://github.com/hasura/ndc-spec.git?tag=v0.2.0#e25213f51a7e8422d712509d63ae012c67b4f3f1" 243 | dependencies = [ 244 | "indexmap 2.2.6", 245 | "ref-cast", 246 | "schemars", 247 | "serde", 248 | "serde_json", 249 | "serde_with", 250 | "smol_str", 251 | ] 252 | 253 | [[package]] 254 | name = "num-conv" 255 | version = "0.1.0" 256 | source = "registry+https://github.com/rust-lang/crates.io-index" 257 | checksum = "51d515d32fb182ee37cda2ccdcb92950d6a3c2893aa280e540671c2cd0f3b1d9" 258 | 259 | [[package]] 260 | name = "num-traits" 261 | version = "0.2.18" 262 | source = "registry+https://github.com/rust-lang/crates.io-index" 263 | checksum = "da0df0e5185db44f69b44f26786fe401b6c293d1907744beaa7fa62b2e5a517a" 264 | dependencies = [ 265 | "autocfg", 266 | ] 267 | 268 | [[package]] 269 | name = "once_cell" 270 | version = "1.19.0" 271 | source = "registry+https://github.com/rust-lang/crates.io-index" 272 | checksum = "3fdb12b2476b595f9358c5161aa467c2438859caa136dec86c26fdd2efe17b92" 273 | 274 | [[package]] 275 | name = "powerfmt" 276 | version = "0.2.0" 277 | source = "registry+https://github.com/rust-lang/crates.io-index" 278 | checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" 279 | 280 | [[package]] 281 | name = "proc-macro2" 282 | version = "1.0.79" 283 | source = "registry+https://github.com/rust-lang/crates.io-index" 284 | checksum = "e835ff2298f5721608eb1a980ecaee1aef2c132bf95ecc026a11b7bf3c01c02e" 285 | dependencies = [ 286 | "unicode-ident", 287 | ] 288 | 289 | [[package]] 290 | name = "quote" 291 | version = "1.0.35" 292 | source = "registry+https://github.com/rust-lang/crates.io-index" 293 | checksum = "291ec9ab5efd934aaf503a6466c5d5251535d108ee747472c3977cc5acc868ef" 294 | dependencies = [ 295 | "proc-macro2", 296 | ] 297 | 298 | [[package]] 299 | name = "ref-cast" 300 | version = "1.0.23" 301 | source = "registry+https://github.com/rust-lang/crates.io-index" 302 | checksum = "ccf0a6f84d5f1d581da8b41b47ec8600871962f2a528115b542b362d4b744931" 303 | dependencies = [ 304 | "ref-cast-impl", 305 | ] 306 | 307 | [[package]] 308 | name = "ref-cast-impl" 309 | version = "1.0.23" 310 | source = "registry+https://github.com/rust-lang/crates.io-index" 311 | checksum = "bcc303e793d3734489387d205e9b186fac9c6cfacedd98cbb2e8a5943595f3e6" 312 | dependencies = [ 313 | "proc-macro2", 314 | "quote", 315 | "syn 2.0.55", 316 | ] 317 | 318 | [[package]] 319 | name = "ryu" 320 | version = "1.0.17" 321 | source = "registry+https://github.com/rust-lang/crates.io-index" 322 | checksum = "e86697c916019a8588c99b5fac3cead74ec0b4b819707a682fd4d23fa0ce1ba1" 323 | 324 | [[package]] 325 | name = "schemars" 326 | version = "0.8.16" 327 | source = "registry+https://github.com/rust-lang/crates.io-index" 328 | checksum = "45a28f4c49489add4ce10783f7911893516f15afe45d015608d41faca6bc4d29" 329 | dependencies = [ 330 | "dyn-clone", 331 | "indexmap 1.9.3", 332 | "indexmap 2.2.6", 333 | "schemars_derive", 334 | "serde", 335 | "serde_json", 336 | "smol_str", 337 | ] 338 | 339 | [[package]] 340 | name = "schemars_derive" 341 | version = "0.8.16" 342 | source = "registry+https://github.com/rust-lang/crates.io-index" 343 | checksum = "c767fd6fa65d9ccf9cf026122c1b555f2ef9a4f0cea69da4d7dbc3e258d30967" 344 | dependencies = [ 345 | "proc-macro2", 346 | "quote", 347 | "serde_derive_internals", 348 | "syn 1.0.109", 349 | ] 350 | 351 | [[package]] 352 | name = "serde" 353 | version = "1.0.197" 354 | source = "registry+https://github.com/rust-lang/crates.io-index" 355 | checksum = "3fb1c873e1b9b056a4dc4c0c198b24c3ffa059243875552b2bd0933b1aee4ce2" 356 | dependencies = [ 357 | "serde_derive", 358 | ] 359 | 360 | [[package]] 361 | name = "serde_derive" 362 | version = "1.0.197" 363 | source = "registry+https://github.com/rust-lang/crates.io-index" 364 | checksum = "7eb0b34b42edc17f6b7cac84a52a1c5f0e1bb2227e997ca9011ea3dd34e8610b" 365 | dependencies = [ 366 | "proc-macro2", 367 | "quote", 368 | "syn 2.0.55", 369 | ] 370 | 371 | [[package]] 372 | name = "serde_derive_internals" 373 | version = "0.26.0" 374 | source = "registry+https://github.com/rust-lang/crates.io-index" 375 | checksum = "85bf8229e7920a9f636479437026331ce11aa132b4dde37d121944a44d6e5f3c" 376 | dependencies = [ 377 | "proc-macro2", 378 | "quote", 379 | "syn 1.0.109", 380 | ] 381 | 382 | [[package]] 383 | name = "serde_json" 384 | version = "1.0.114" 385 | source = "registry+https://github.com/rust-lang/crates.io-index" 386 | checksum = "c5f09b1bd632ef549eaa9f60a1f8de742bdbc698e6cee2095fc84dde5f549ae0" 387 | dependencies = [ 388 | "indexmap 2.2.6", 389 | "itoa", 390 | "ryu", 391 | "serde", 392 | ] 393 | 394 | [[package]] 395 | name = "serde_with" 396 | version = "3.8.1" 397 | source = "registry+https://github.com/rust-lang/crates.io-index" 398 | checksum = "0ad483d2ab0149d5a5ebcd9972a3852711e0153d863bf5a5d0391d28883c4a20" 399 | dependencies = [ 400 | "base64", 401 | "chrono", 402 | "hex", 403 | "indexmap 1.9.3", 404 | "indexmap 2.2.6", 405 | "serde", 406 | "serde_derive", 407 | "serde_json", 408 | "serde_with_macros", 409 | "time", 410 | ] 411 | 412 | [[package]] 413 | name = "serde_with_macros" 414 | version = "3.8.1" 415 | source = "registry+https://github.com/rust-lang/crates.io-index" 416 | checksum = "65569b702f41443e8bc8bbb1c5779bd0450bbe723b56198980e80ec45780bce2" 417 | dependencies = [ 418 | "darling", 419 | "proc-macro2", 420 | "quote", 421 | "syn 2.0.55", 422 | ] 423 | 424 | [[package]] 425 | name = "smol_str" 426 | version = "0.1.24" 427 | source = "registry+https://github.com/rust-lang/crates.io-index" 428 | checksum = "fad6c857cbab2627dcf01ec85a623ca4e7dcb5691cbaa3d7fb7653671f0d09c9" 429 | dependencies = [ 430 | "serde", 431 | ] 432 | 433 | [[package]] 434 | name = "strsim" 435 | version = "0.10.0" 436 | source = "registry+https://github.com/rust-lang/crates.io-index" 437 | checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" 438 | 439 | [[package]] 440 | name = "syn" 441 | version = "1.0.109" 442 | source = "registry+https://github.com/rust-lang/crates.io-index" 443 | checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" 444 | dependencies = [ 445 | "proc-macro2", 446 | "quote", 447 | "unicode-ident", 448 | ] 449 | 450 | [[package]] 451 | name = "syn" 452 | version = "2.0.55" 453 | source = "registry+https://github.com/rust-lang/crates.io-index" 454 | checksum = "002a1b3dbf967edfafc32655d0f377ab0bb7b994aa1d32c8cc7e9b8bf3ebb8f0" 455 | dependencies = [ 456 | "proc-macro2", 457 | "quote", 458 | "unicode-ident", 459 | ] 460 | 461 | [[package]] 462 | name = "time" 463 | version = "0.3.34" 464 | source = "registry+https://github.com/rust-lang/crates.io-index" 465 | checksum = "c8248b6521bb14bc45b4067159b9b6ad792e2d6d754d6c41fb50e29fefe38749" 466 | dependencies = [ 467 | "deranged", 468 | "itoa", 469 | "num-conv", 470 | "powerfmt", 471 | "serde", 472 | "time-core", 473 | "time-macros", 474 | ] 475 | 476 | [[package]] 477 | name = "time-core" 478 | version = "0.1.2" 479 | source = "registry+https://github.com/rust-lang/crates.io-index" 480 | checksum = "ef927ca75afb808a4d64dd374f00a2adf8d0fcff8e7b184af886c3c87ec4a3f3" 481 | 482 | [[package]] 483 | name = "time-macros" 484 | version = "0.2.17" 485 | source = "registry+https://github.com/rust-lang/crates.io-index" 486 | checksum = "7ba3a3ef41e6672a2f0f001392bb5dcd3ff0a9992d618ca761a11c3121547774" 487 | dependencies = [ 488 | "num-conv", 489 | "time-core", 490 | ] 491 | 492 | [[package]] 493 | name = "unicode-ident" 494 | version = "1.0.12" 495 | source = "registry+https://github.com/rust-lang/crates.io-index" 496 | checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b" 497 | 498 | [[package]] 499 | name = "wasm-bindgen" 500 | version = "0.2.92" 501 | source = "registry+https://github.com/rust-lang/crates.io-index" 502 | checksum = "4be2531df63900aeb2bca0daaaddec08491ee64ceecbee5076636a3b026795a8" 503 | dependencies = [ 504 | "cfg-if", 505 | "wasm-bindgen-macro", 506 | ] 507 | 508 | [[package]] 509 | name = "wasm-bindgen-backend" 510 | version = "0.2.92" 511 | source = "registry+https://github.com/rust-lang/crates.io-index" 512 | checksum = "614d787b966d3989fa7bb98a654e369c762374fd3213d212cfc0251257e747da" 513 | dependencies = [ 514 | "bumpalo", 515 | "log", 516 | "once_cell", 517 | "proc-macro2", 518 | "quote", 519 | "syn 2.0.55", 520 | "wasm-bindgen-shared", 521 | ] 522 | 523 | [[package]] 524 | name = "wasm-bindgen-macro" 525 | version = "0.2.92" 526 | source = "registry+https://github.com/rust-lang/crates.io-index" 527 | checksum = "a1f8823de937b71b9460c0c34e25f3da88250760bec0ebac694b49997550d726" 528 | dependencies = [ 529 | "quote", 530 | "wasm-bindgen-macro-support", 531 | ] 532 | 533 | [[package]] 534 | name = "wasm-bindgen-macro-support" 535 | version = "0.2.92" 536 | source = "registry+https://github.com/rust-lang/crates.io-index" 537 | checksum = "e94f17b526d0a461a191c78ea52bbce64071ed5c04c9ffe424dcb38f74171bb7" 538 | dependencies = [ 539 | "proc-macro2", 540 | "quote", 541 | "syn 2.0.55", 542 | "wasm-bindgen-backend", 543 | "wasm-bindgen-shared", 544 | ] 545 | 546 | [[package]] 547 | name = "wasm-bindgen-shared" 548 | version = "0.2.92" 549 | source = "registry+https://github.com/rust-lang/crates.io-index" 550 | checksum = "af190c94f2773fdb3729c55b007a722abb5384da03bc0986df4c289bf5567e96" 551 | 552 | [[package]] 553 | name = "windows-core" 554 | version = "0.52.0" 555 | source = "registry+https://github.com/rust-lang/crates.io-index" 556 | checksum = "33ab640c8d7e35bf8ba19b884ba838ceb4fba93a4e8c65a9059d08afcfc683d9" 557 | dependencies = [ 558 | "windows-targets", 559 | ] 560 | 561 | [[package]] 562 | name = "windows-targets" 563 | version = "0.52.4" 564 | source = "registry+https://github.com/rust-lang/crates.io-index" 565 | checksum = "7dd37b7e5ab9018759f893a1952c9420d060016fc19a472b4bb20d1bdd694d1b" 566 | dependencies = [ 567 | "windows_aarch64_gnullvm", 568 | "windows_aarch64_msvc", 569 | "windows_i686_gnu", 570 | "windows_i686_msvc", 571 | "windows_x86_64_gnu", 572 | "windows_x86_64_gnullvm", 573 | "windows_x86_64_msvc", 574 | ] 575 | 576 | [[package]] 577 | name = "windows_aarch64_gnullvm" 578 | version = "0.52.4" 579 | source = "registry+https://github.com/rust-lang/crates.io-index" 580 | checksum = "bcf46cf4c365c6f2d1cc93ce535f2c8b244591df96ceee75d8e83deb70a9cac9" 581 | 582 | [[package]] 583 | name = "windows_aarch64_msvc" 584 | version = "0.52.4" 585 | source = "registry+https://github.com/rust-lang/crates.io-index" 586 | checksum = "da9f259dd3bcf6990b55bffd094c4f7235817ba4ceebde8e6d11cd0c5633b675" 587 | 588 | [[package]] 589 | name = "windows_i686_gnu" 590 | version = "0.52.4" 591 | source = "registry+https://github.com/rust-lang/crates.io-index" 592 | checksum = "b474d8268f99e0995f25b9f095bc7434632601028cf86590aea5c8a5cb7801d3" 593 | 594 | [[package]] 595 | name = "windows_i686_msvc" 596 | version = "0.52.4" 597 | source = "registry+https://github.com/rust-lang/crates.io-index" 598 | checksum = "1515e9a29e5bed743cb4415a9ecf5dfca648ce85ee42e15873c3cd8610ff8e02" 599 | 600 | [[package]] 601 | name = "windows_x86_64_gnu" 602 | version = "0.52.4" 603 | source = "registry+https://github.com/rust-lang/crates.io-index" 604 | checksum = "5eee091590e89cc02ad514ffe3ead9eb6b660aedca2183455434b93546371a03" 605 | 606 | [[package]] 607 | name = "windows_x86_64_gnullvm" 608 | version = "0.52.4" 609 | source = "registry+https://github.com/rust-lang/crates.io-index" 610 | checksum = "77ca79f2451b49fa9e2af39f0747fe999fcda4f5e241b2898624dca97a1f2177" 611 | 612 | [[package]] 613 | name = "windows_x86_64_msvc" 614 | version = "0.52.4" 615 | source = "registry+https://github.com/rust-lang/crates.io-index" 616 | checksum = "32b752e52a2da0ddfbdbcc6fceadfeede4c939ed16d13e648833a61dfb611ed8" 617 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [workspace] 2 | members = ["typegen"] 3 | resolver = "2" 4 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Native Data Connector SDK for TypeScript 2 | 3 | This SDK is mostly analogous to the Rust SDK, except where necessary. 4 | 5 | All functions of the Connector interface are analogous to their Rust counterparts. 6 | 7 | ## Installing 8 | 9 | ### From NPM 10 | 11 | ```sh 12 | npm install @hasura/ndc-sdk-typescript 13 | ``` 14 | 15 | ### From this repo: 16 | 17 | The repo does not include build artifacts, so you'll need to run the build step: 18 | 19 | ```sh 20 | npm install https://github.com/hasura/ndc-sdk-typescript 21 | 22 | cd node_modules/ndc-sdk-typescript 23 | 24 | npm install 25 | 26 | npm run build 27 | ``` 28 | 29 | ## Using this SDK 30 | 31 | The SDK exports a `start` function, which takes a `connector` object, that is an object that implements the `Connector` interface defined in `connector.ts` 32 | 33 | This function should be your starting point. 34 | 35 | A connector can thus start liks so: 36 | 37 | ```ts 38 | const connector: Connector = { 39 | /* implementation of the Connector interface removed for brevity */ 40 | }; 41 | 42 | start(connector); 43 | ``` 44 | 45 | Please refer to the [NDC Spec](https://hasura.github.io/ndc-spec/) for details on implementing the Connector interface. 46 | 47 | ## Publishing a new version of the SDK to NPM 48 | 49 | Pushing a new version tag will automatically publish the tag to NPM provided that it matches the version specified in `package.json`. 50 | 51 | See `.github/workflows/build_test_publish.yaml` for details. 52 | 53 | ## Regenerating Schema Types 54 | The NDC spec types are generated from the NDC Spec Rust types. First, a JSON schema is derived from the Rust types into `./src/schema/schema.generated.json` (see `./typegen/src/main.rs`). 55 | 56 | Then the TypeScript types are generated from that JSON Schema document into `./src/schema/schema.generated.ts`. 57 | 58 | In order to regenerate the types, run 59 | ``` 60 | > npm run regenerate-schema 61 | ``` 62 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@hasura/ndc-sdk-typescript", 3 | "version": "8.1.0", 4 | "description": "", 5 | "main": "./dist/index.js", 6 | "types": "./dist/index.d.ts", 7 | "exports": { 8 | ".": "./dist/index.js", 9 | "./instrumentation": "./dist/instrumentation.js" 10 | }, 11 | "scripts": { 12 | "test": "echo \"Error: no test specified\" && exit 1", 13 | "regenerate-schema": "./typegen/regenerate-schema.sh", 14 | "build": "tsc" 15 | }, 16 | "keywords": [ 17 | "hasura", 18 | "ndc" 19 | ], 20 | "author": "Hasura", 21 | "license": "Apache-2.0", 22 | "dependencies": { 23 | "@json-schema-tools/meta-schema": "^1.7.0", 24 | "@opentelemetry/api": "^1.8.0", 25 | "@opentelemetry/exporter-metrics-otlp-proto": "^0.53.0", 26 | "@opentelemetry/exporter-metrics-otlp-grpc": "^0.53.0", 27 | "@opentelemetry/instrumentation-fastify": "^0.36.0", 28 | "@opentelemetry/instrumentation-fetch": "^0.53.0", 29 | "@opentelemetry/instrumentation-http": "^0.53.0", 30 | "@opentelemetry/instrumentation-pino": "^0.38.0", 31 | "@opentelemetry/resources": "^1.24.0", 32 | "@opentelemetry/sdk-metrics": "^1.24.0", 33 | "@opentelemetry/sdk-node": "^0.51.0", 34 | "@opentelemetry/semantic-conventions": "^1.24.0", 35 | "commander": "^11.0.0", 36 | "fastify": "^4.23.2", 37 | "pino-pretty": "^10.2.3", 38 | "prom-client": "^15.1.2", 39 | "semver": "^7.6.3" 40 | }, 41 | "devDependencies": { 42 | "@tsconfig/node18": "^18.2.4", 43 | "@types/node": "^18.11.9", 44 | "@types/semver": "^7.5.8", 45 | "json-schema-to-typescript": "^13.1.1", 46 | "typescript": "^5.8.2" 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /rust-toolchain.toml: -------------------------------------------------------------------------------- 1 | [toolchain] 2 | channel = "1.83.0" 3 | profile = "default" # see https://rust-lang.github.io/rustup/concepts/profiles.html 4 | components = ["llvm-tools-preview", "rust-analyzer", "rust-src"] # see https://rust-lang.github.io/rustup/concepts/components.html 5 | -------------------------------------------------------------------------------- /src/connector.ts: -------------------------------------------------------------------------------- 1 | import { Registry } from "prom-client"; 2 | import { 3 | Capabilities, 4 | QueryRequest, 5 | QueryResponse, 6 | SchemaResponse, 7 | ExplainResponse, 8 | MutationRequest, 9 | MutationResponse, 10 | } from "./schema"; 11 | 12 | export interface Connector { 13 | 14 | /** 15 | * Validate the configuration files provided by the user, returning a validated 'Configuration', 16 | * or throwing an 'Error'. Throwing an error prevents Connector startup. 17 | * @param configuration 18 | */ 19 | parseConfiguration( 20 | configurationDir: string 21 | ): Promise; 22 | 23 | /** 24 | * Initialize the connector's in-memory state. 25 | * 26 | * For example, any connection pools, prepared queries, 27 | * or other managed resources would be allocated here. 28 | * 29 | * In addition, this function should register any 30 | * connector-specific metrics with the metrics registry. 31 | * @param configuration 32 | * @param metrics 33 | */ 34 | tryInitState( 35 | configuration: Configuration, 36 | metrics: Registry 37 | ): Promise; 38 | 39 | /** 40 | * 41 | * Update any metrics from the state 42 | * 43 | * Note: some metrics can be updated directly, and do not 44 | * need to be updated here. This function can be useful to 45 | * query metrics which cannot be updated directly, e.g. 46 | * the number of idle connections in a connection pool 47 | * can be polled but not updated directly. 48 | * @param configuration 49 | * @param state 50 | */ 51 | fetchMetrics(configuration: Configuration, state: State): Promise; 52 | 53 | /** 54 | * Check the health of the connector. 55 | * 56 | * This should simply verify that the connector is ready to start accepting 57 | * requests. It should not verify that external data sources are available. 58 | * 59 | * This function is optional to implement; if left unimplemented, a default 60 | * implementation will be used that returns healthy once the connector 61 | * webserver is running. 62 | * 63 | * @param configuration 64 | * @param state 65 | */ 66 | getHealthReadiness?(configuration: Configuration, state: State): Promise; 67 | 68 | /** 69 | * Get the connector's capabilities. 70 | * 71 | * This function implements the [capabilities endpoint](https://hasura.github.io/ndc-spec/specification/capabilities.html) 72 | * from the NDC specification. 73 | * 74 | * This function should be synchronous 75 | * @param configuration 76 | */ 77 | getCapabilities(configuration: Configuration): Capabilities; 78 | 79 | /** 80 | * Get the connector's schema. 81 | * 82 | * This function implements the [schema endpoint](https://hasura.github.io/ndc-spec/specification/schema/index.html) 83 | * from the NDC specification. 84 | * @param configuration 85 | */ 86 | getSchema(configuration: Configuration): Promise; 87 | 88 | /** 89 | * Explain a query by creating an execution plan 90 | * 91 | * This function implements the [explain endpoint](https://hasura.github.io/ndc-spec/specification/explain.html) 92 | * from the NDC specification. 93 | * @param configuration 94 | * @param state 95 | * @param request 96 | */ 97 | queryExplain( 98 | configuration: Configuration, 99 | state: State, 100 | request: QueryRequest 101 | ): Promise; 102 | 103 | /** 104 | * Explain a mutation by creating an execution plan 105 | * 106 | * This function implements the [explain endpoint](https://hasura.github.io/ndc-spec/specification/explain.html) 107 | * from the NDC specification. 108 | * @param configuration 109 | * @param state 110 | * @param request 111 | */ 112 | mutationExplain( 113 | configuration: Configuration, 114 | state: State, 115 | request: MutationRequest 116 | ): Promise; 117 | 118 | /** 119 | * Execute a mutation 120 | * 121 | * This function implements the [mutation endpoint](https://hasura.github.io/ndc-spec/specification/mutations/index.html) 122 | * from the NDC specification. 123 | * @param configuration 124 | * @param state 125 | * @param request 126 | */ 127 | mutation( 128 | configuration: Configuration, 129 | state: State, 130 | request: MutationRequest 131 | ): Promise; 132 | 133 | /** 134 | * Execute a query 135 | * 136 | * This function implements the [query endpoint](https://hasura.github.io/ndc-spec/specification/queries/index.html) 137 | * from the NDC specification. 138 | * @param configuration 139 | * @param state 140 | * @param request 141 | */ 142 | query( 143 | configuration: Configuration, 144 | state: State, 145 | request: QueryRequest 146 | ): Promise; 147 | } 148 | -------------------------------------------------------------------------------- /src/error.ts: -------------------------------------------------------------------------------- 1 | import { ErrorResponse } from "./schema"; 2 | 3 | // ref: https://hasura.github.io/ndc-spec/specification/error-handling.html 4 | type ErrorCode = 5 | | /** Bad Request - The request did not match the data connector's expectation based on this specification. */ 400 6 | | /** Forbidden - The request could not be handled because a permission check failed - for example, a mutation might fail because a check constraint was not met.*/ 403 7 | | /** Conflict - The request could not be handled because it would create a conflicting state for the data source - for example, a mutation might fail because a foreign key constraint was not met.*/ 409 8 | | /** Unprocessable Content - The request could not be handled because, while the request was well-formed, it was not semantically correct. For example, a value for a custom scalar type was provided, but with an incorrect type.*/ 422 9 | | /** Internal Server Error - The request could not be handled because of an error on the server */ 500 10 | | /** Not Supported - The request could not be handled because it relies on an unsupported capability. Note: this ought to indicate an error on the caller side, since the caller should not generate requests which are incompatible with the indicated capabilities. */ 501 11 | | /** Bad Gateway - The request could not be handled because an upstream service was unavailable or returned an unexpected response, e.g., a connection to a database server failed. */ 502 12 | | number; 13 | 14 | export class ConnectorError extends Error { 15 | statusCode: ErrorCode; 16 | details?: ErrorResponse["details"]; 17 | 18 | constructor( 19 | statusCode: ErrorCode, 20 | message: ErrorResponse["message"], 21 | details?: ErrorResponse["details"] 22 | ) { 23 | super(message); 24 | 25 | this.statusCode = statusCode; 26 | 27 | if (details !== undefined) { 28 | this.details = details; 29 | } 30 | 31 | return this; 32 | } 33 | } 34 | 35 | /** The request did not match the data connector's expectation based on this specification */ 36 | export class BadRequest extends ConnectorError { 37 | constructor( 38 | message: ErrorResponse["message"], 39 | details?: ErrorResponse["details"] 40 | ) { 41 | super(400, message, details); 42 | } 43 | } 44 | 45 | /** The request could not be handled because a permission check failed - for example, a mutation might fail because a check constraint was not met */ 46 | export class Forbidden extends ConnectorError { 47 | constructor( 48 | message: ErrorResponse["message"], 49 | details?: ErrorResponse["details"] 50 | ) { 51 | super(403, message, details); 52 | } 53 | } 54 | 55 | /** The request could not be handled because it would create a conflicting state for the data source - for example, a mutation might fail because a foreign key constraint was not met */ 56 | export class Conflict extends ConnectorError { 57 | constructor( 58 | message: ErrorResponse["message"], 59 | details?: ErrorResponse["details"] 60 | ) { 61 | super(409, message, details); 62 | } 63 | } 64 | 65 | /** The request could not be handled because, while the request was well-formed, it was not semantically correct. For example, a value for a custom scalar type was provided, but with an incorrect type */ 66 | export class UnprocessableContent extends ConnectorError { 67 | constructor( 68 | message: ErrorResponse["message"], 69 | details?: ErrorResponse["details"] 70 | ) { 71 | super(422, message, details); 72 | } 73 | } 74 | 75 | /** The request could not be handled because of an error on the server */ 76 | export class InternalServerError extends ConnectorError { 77 | constructor( 78 | message: ErrorResponse["message"], 79 | details?: ErrorResponse["details"] 80 | ) { 81 | super(500, message, details); 82 | } 83 | } 84 | 85 | /** The request could not be handled because it relies on an unsupported capability. Note: this ought to indicate an error on the caller side, since the caller should not generate requests which are incompatible with the indicated capabilities */ 86 | export class NotSupported extends ConnectorError { 87 | constructor( 88 | message: ErrorResponse["message"], 89 | details?: ErrorResponse["details"] 90 | ) { 91 | super(501, message, details); 92 | } 93 | } 94 | 95 | /** The request could not be handled because an upstream service was unavailable or returned an unexpected response, e.g., a connection to a database server failed */ 96 | export class BadGateway extends ConnectorError { 97 | constructor( 98 | message: ErrorResponse["message"], 99 | details?: ErrorResponse["details"] 100 | ) { 101 | super(502, message, details); 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | // Initializing telemetry must be done before importing any other module 2 | // Users of the SDK can choose to initialize it manually themselves, so we check that 3 | // that hasn't already been done 4 | import * as instrumentation from "./instrumentation"; 5 | if (!instrumentation.isInitialized()) { 6 | instrumentation.initTelemetry(); 7 | } 8 | 9 | import { Connector } from "./connector"; 10 | import { Command, Option, InvalidOptionArgumentError } from "commander"; 11 | import { ServerOptions, startServer } from "./server"; 12 | export * from "./error"; 13 | export * from "./schema"; 14 | export { Connector, ServerOptions, startServer }; 15 | 16 | /** 17 | * Starts the connector. 18 | * Will read command line arguments or environment variables to determine runtime configuration. 19 | * 20 | * This should be the entrypoint of your connector 21 | * @param connector An object that implements the Connector interface 22 | */ 23 | export function start( 24 | connector: Connector 25 | ) { 26 | const program = new Command(); 27 | 28 | program.addCommand(getServeCommand(connector)); 29 | 30 | program.parseAsync(process.argv).catch(console.error); 31 | } 32 | 33 | export function getServeCommand( 34 | connector?: Connector 35 | ) { 36 | const command = new Command("serve") 37 | .addOption( 38 | new Option("--configuration ") 39 | .env("HASURA_CONFIGURATION_DIRECTORY") 40 | .makeOptionMandatory(true) 41 | ) 42 | .addOption( 43 | new Option("--host ") 44 | .env("HASURA_CONNECTOR_HOST") 45 | .default("::") 46 | ) 47 | .addOption( 48 | new Option("--port ") 49 | .env("HASURA_CONNECTOR_PORT") 50 | .default(8080) 51 | .argParser(parseIntOption) 52 | ) 53 | .addOption( 54 | new Option("--service-token-secret ").env("HASURA_SERVICE_TOKEN_SECRET") 55 | ) 56 | .addOption(new Option("--log-level ").env("HASURA_LOG_LEVEL").default("info")) 57 | .addOption(new Option("--pretty-print-logs").env("HASURA_PRETTY_PRINT_LOGS").default(false)); 58 | 59 | if (connector) { 60 | command.action(async (options: ServerOptions) => { 61 | await startServer(connector, options); 62 | }); 63 | } 64 | return command; 65 | } 66 | 67 | function parseIntOption(value: string, _previous: number): number { 68 | // parseInt takes a string and a radix 69 | const parsedValue = parseInt(value, 10); 70 | if (isNaN(parsedValue)) { 71 | throw new InvalidOptionArgumentError("Not a valid integer."); 72 | } 73 | return parsedValue; 74 | } 75 | -------------------------------------------------------------------------------- /src/instrumentation.ts: -------------------------------------------------------------------------------- 1 | import * as opentelemetry from "@opentelemetry/sdk-node"; 2 | import * as traceHttpProto from "@opentelemetry/exporter-trace-otlp-proto"; 3 | import * as metricsHttpProto from "@opentelemetry/exporter-metrics-otlp-proto"; 4 | import * as traceGrpc from "@opentelemetry/exporter-trace-otlp-grpc"; 5 | import * as metricsGrpc from "@opentelemetry/exporter-metrics-otlp-grpc"; 6 | import { PeriodicExportingMetricReader } from "@opentelemetry/sdk-metrics"; 7 | import { PinoInstrumentation } from "@opentelemetry/instrumentation-pino"; 8 | import { FastifyInstrumentation } from "@opentelemetry/instrumentation-fastify"; 9 | import { HttpInstrumentation } from "@opentelemetry/instrumentation-http"; 10 | import { FetchInstrumentation } from "@opentelemetry/instrumentation-fetch"; 11 | import { Attributes, Span, SpanStatusCode, Tracer } from "@opentelemetry/api"; 12 | import { CompositePropagator, W3CBaggagePropagator, W3CTraceContextPropagator } from "@opentelemetry/core"; 13 | import { B3Propagator, B3InjectEncoding } from "@opentelemetry/propagator-b3" 14 | 15 | let sdk: opentelemetry.NodeSDK | null = null; 16 | 17 | export type Protocol = "grpc" | "http/protobuf"; 18 | 19 | export function initTelemetry( 20 | defaultServiceName: string = "hasura-ndc", 21 | defaultEndpoint: string = "http://localhost:4317", 22 | defaultProtocol: Protocol = "grpc", 23 | ) { 24 | if (isInitialized()) { 25 | throw new Error("Telemetry has already been initialized!"); 26 | } 27 | 28 | const serviceName = process.env["OTEL_SERVICE_NAME"] || defaultServiceName; 29 | const endpoint = 30 | process.env["OTEL_EXPORTER_OTLP_ENDPOINT"] || defaultEndpoint; 31 | const protocol = process.env["OTEL_EXPORTER_OTLP_PROTOCOL"] || defaultProtocol; 32 | 33 | let exporters = getExporters(protocol, endpoint); 34 | 35 | sdk = new opentelemetry.NodeSDK({ 36 | serviceName, 37 | traceExporter: exporters.traceExporter, 38 | metricReader: new PeriodicExportingMetricReader({ 39 | exporter: exporters.metricsExporter, 40 | }), 41 | instrumentations: [ 42 | new HttpInstrumentation({ 43 | applyCustomAttributesOnSpan: (span, request, response) => { 44 | span.setAttributes(USER_VISIBLE_SPAN_ATTRIBUTE); 45 | }, 46 | }), 47 | new FastifyInstrumentation({ 48 | requestHook: (span, info) => { 49 | span.setAttributes(USER_VISIBLE_SPAN_ATTRIBUTE); 50 | }, 51 | }), 52 | new FetchInstrumentation({ 53 | applyCustomAttributesOnSpan: (span, request, response) => { 54 | span.setAttributes(USER_VISIBLE_SPAN_ATTRIBUTE);; 55 | }, 56 | }), 57 | // the pino instrumentation adds trace information to pino logs 58 | new PinoInstrumentation({ 59 | logHook: (span, record, level) => { 60 | record["resource.service.name"] = serviceName; 61 | // This logs the parent span ID in the pino logs, useful for debugging propagation. 62 | // parentSpanId is an internal property, hence the cast to any, because I can't 63 | // seem to find a way to get at it through a supported API 😭 64 | record["parent_span_id"] = (span as any).parentSpanId; 65 | }, 66 | }), 67 | ], 68 | textMapPropagator: new CompositePropagator({ 69 | propagators: [ 70 | new W3CTraceContextPropagator(), 71 | new W3CBaggagePropagator(), 72 | new B3Propagator(), 73 | new B3Propagator({ injectEncoding: B3InjectEncoding.MULTI_HEADER }), 74 | ] 75 | }), 76 | }); 77 | 78 | process.on("beforeExit", async () => { 79 | await sdk?.shutdown(); 80 | }); 81 | 82 | sdk.start(); 83 | } 84 | 85 | type Exporters = { 86 | traceExporter: opentelemetry.node.SpanExporter, 87 | metricsExporter: opentelemetry.metrics.PushMetricExporter, 88 | } 89 | 90 | function getExporters(protocol: Protocol | string, endpoint: string): Exporters { 91 | switch (protocol) { 92 | case "grpc": 93 | return { 94 | traceExporter: new traceGrpc.OTLPTraceExporter({ 95 | url: endpoint, 96 | }), 97 | metricsExporter: new metricsGrpc.OTLPMetricExporter({ 98 | url: endpoint, 99 | }) 100 | }; 101 | case "http/protobuf": 102 | return { 103 | traceExporter: new traceHttpProto.OTLPTraceExporter({ 104 | url: `${endpoint}/v1/traces`, 105 | }), 106 | metricsExporter: new metricsHttpProto.OTLPMetricExporter({ 107 | url: `${endpoint}/v1/metrics`, 108 | }) 109 | }; 110 | default: 111 | throw new Error(`Unsupported protocol: {protocol}`); 112 | } 113 | } 114 | 115 | export function isInitialized(): boolean { 116 | return sdk !== null; 117 | } 118 | 119 | export const USER_VISIBLE_SPAN_ATTRIBUTE: Attributes = { 120 | "internal.visibility": "user", 121 | }; 122 | 123 | export function withActiveSpan( 124 | tracer: Tracer, 125 | name: string, 126 | func: (span: Span) => TReturn, 127 | attributes?: Attributes 128 | ): TReturn { 129 | return withInternalActiveSpan(tracer, name, func, attributes ? { ...USER_VISIBLE_SPAN_ATTRIBUTE, ...attributes } : USER_VISIBLE_SPAN_ATTRIBUTE); 130 | } 131 | 132 | export function withInternalActiveSpan( 133 | tracer: Tracer, 134 | name: string, 135 | func: (span: Span) => TReturn, 136 | attributes?: Attributes 137 | ): TReturn { 138 | return tracer.startActiveSpan(name, (span) => { 139 | if (attributes) span.setAttributes(attributes); 140 | 141 | const handleError = (err: unknown) => { 142 | if (err instanceof Error || typeof err === "string") { 143 | span.recordException(err); 144 | } 145 | span.setStatus({ code: SpanStatusCode.ERROR }); 146 | span.end(); 147 | }; 148 | 149 | try { 150 | const retval = func(span); 151 | // If the function returns a Promise, then wire up the span completion to 152 | // the completion of the promise 153 | if ( 154 | typeof retval === "object" && 155 | retval !== null && 156 | "then" in retval && 157 | typeof retval.then === "function" 158 | ) { 159 | return (retval as PromiseLike).then( 160 | (successVal) => { 161 | span.end(); 162 | return successVal; 163 | }, 164 | (errorVal) => { 165 | handleError(errorVal); 166 | throw errorVal; 167 | } 168 | ) as TReturn; 169 | } 170 | // Not a promise, just end the span and return 171 | else { 172 | span.end(); 173 | return retval; 174 | } 175 | } catch (e) { 176 | handleError(e); 177 | throw e; 178 | } 179 | }); 180 | } 181 | -------------------------------------------------------------------------------- /src/logging.ts: -------------------------------------------------------------------------------- 1 | import { FastifyLoggerOptions, PinoLoggerOptions } from "fastify/types/logger"; 2 | 3 | export type LogOptions = { 4 | logLevel: string 5 | prettyPrintLogs: string 6 | } 7 | 8 | export function configureFastifyLogging(options: LogOptions): FastifyLoggerOptions & PinoLoggerOptions { 9 | return { 10 | level: options.logLevel, 11 | ...( 12 | options.prettyPrintLogs 13 | ? { transport: { target: 'pino-pretty' } } 14 | : {} 15 | ) 16 | }; 17 | } 18 | -------------------------------------------------------------------------------- /src/schema/index.ts: -------------------------------------------------------------------------------- 1 | import { JSONSchemaObject } from "@json-schema-tools/meta-schema"; 2 | import schema from "./schema.generated.json"; 3 | import { VERSION, VERSION_HEADER_NAME } from "./version.generated"; 4 | 5 | function schemaForType(type_name: string): JSONSchemaObject { 6 | return { 7 | $schema: schema.$schema, 8 | $ref: `#/definitions/${type_name}`, 9 | definitions: schema.definitions 10 | } 11 | } 12 | 13 | const CapabilitiesResponseSchema = schemaForType("CapabilitiesResponse"); 14 | const SchemaResponseSchema = schemaForType("SchemaResponse"); 15 | const QueryRequestSchema = schemaForType("QueryRequest"); 16 | const QueryResponseSchema = schemaForType("QueryResponse"); 17 | const ExplainResponseSchema = schemaForType("ExplainResponse"); 18 | const MutationRequestSchema = schemaForType("MutationRequest"); 19 | const MutationResponseSchema = schemaForType("MutationResponse"); 20 | const ErrorResponseSchema = schemaForType("ErrorResponse"); 21 | const ValidateResponseSchema = schemaForType("ValidateResponse"); 22 | 23 | export * from "./schema.generated"; 24 | export { 25 | CapabilitiesResponseSchema, 26 | SchemaResponseSchema, 27 | QueryRequestSchema, 28 | QueryResponseSchema, 29 | ExplainResponseSchema, 30 | MutationRequestSchema, 31 | MutationResponseSchema, 32 | ErrorResponseSchema, 33 | ValidateResponseSchema, 34 | VERSION, 35 | VERSION_HEADER_NAME, 36 | }; 37 | -------------------------------------------------------------------------------- /src/schema/schema.generated.ts: -------------------------------------------------------------------------------- 1 | /* eslint-disable */ 2 | /** 3 | * This file was automatically generated by json-schema-to-typescript. 4 | * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, 5 | * and run json-schema-to-typescript to regenerate this file. 6 | */ 7 | 8 | /** 9 | * Representations of scalar types 10 | */ 11 | export type TypeRepresentation = 12 | | { 13 | type: "boolean"; 14 | } 15 | | { 16 | type: "string"; 17 | } 18 | | { 19 | type: "int8"; 20 | } 21 | | { 22 | type: "int16"; 23 | } 24 | | { 25 | type: "int32"; 26 | } 27 | | { 28 | type: "int64"; 29 | } 30 | | { 31 | type: "float32"; 32 | } 33 | | { 34 | type: "float64"; 35 | } 36 | | { 37 | type: "biginteger"; 38 | } 39 | | { 40 | type: "bigdecimal"; 41 | } 42 | | { 43 | type: "uuid"; 44 | } 45 | | { 46 | type: "date"; 47 | } 48 | | { 49 | type: "timestamp"; 50 | } 51 | | { 52 | type: "timestamptz"; 53 | } 54 | | { 55 | type: "geography"; 56 | } 57 | | { 58 | type: "geometry"; 59 | } 60 | | { 61 | type: "bytes"; 62 | } 63 | | { 64 | type: "json"; 65 | } 66 | | { 67 | type: "enum"; 68 | one_of: string[]; 69 | }; 70 | /** 71 | * The definition of an aggregation function on a scalar type 72 | */ 73 | export type AggregateFunctionDefinition = 74 | | { 75 | type: "min"; 76 | } 77 | | { 78 | type: "max"; 79 | } 80 | | { 81 | type: "sum"; 82 | /** 83 | * The scalar type of the result of this function, which should have one of the type representations Int64 or Float64, depending on whether this function is defined on a scalar type with an integer or floating-point representation, respectively. 84 | */ 85 | result_type: string; 86 | } 87 | | { 88 | type: "average"; 89 | /** 90 | * The scalar type of the result of this function, which should have the type representation Float64 91 | */ 92 | result_type: string; 93 | } 94 | | { 95 | type: "custom"; 96 | /** 97 | * The scalar or object type of the result of this function 98 | */ 99 | result_type: Type; 100 | }; 101 | /** 102 | * Types track the valid representations of values as JSON 103 | */ 104 | export type Type = 105 | | { 106 | type: "named"; 107 | /** 108 | * The name can refer to a scalar or object type 109 | */ 110 | name: string; 111 | } 112 | | { 113 | type: "nullable"; 114 | /** 115 | * The type of the non-null inhabitants of this type 116 | */ 117 | underlying_type: Type; 118 | } 119 | | { 120 | type: "array"; 121 | /** 122 | * The type of the elements of the array 123 | */ 124 | element_type: Type; 125 | } 126 | | { 127 | type: "predicate"; 128 | /** 129 | * The object type name 130 | */ 131 | object_type_name: string; 132 | }; 133 | /** 134 | * The definition of a comparison operator on a scalar type 135 | */ 136 | export type ComparisonOperatorDefinition = 137 | | { 138 | type: "equal"; 139 | } 140 | | { 141 | type: "in"; 142 | } 143 | | { 144 | type: "less_than"; 145 | } 146 | | { 147 | type: "less_than_or_equal"; 148 | } 149 | | { 150 | type: "greater_than"; 151 | } 152 | | { 153 | type: "greater_than_or_equal"; 154 | } 155 | | { 156 | type: "contains"; 157 | } 158 | | { 159 | type: "contains_insensitive"; 160 | } 161 | | { 162 | type: "starts_with"; 163 | } 164 | | { 165 | type: "starts_with_insensitive"; 166 | } 167 | | { 168 | type: "ends_with"; 169 | } 170 | | { 171 | type: "ends_with_insensitive"; 172 | } 173 | | { 174 | type: "custom"; 175 | /** 176 | * The type of the argument to this operator 177 | */ 178 | argument_type: Type; 179 | }; 180 | /** 181 | * The definition of an aggregation function on a scalar type 182 | */ 183 | export type ExtractionFunctionDefinition = 184 | | { 185 | type: "nanosecond"; 186 | /** 187 | * The result type, which must be a defined scalar type in the schema response. 188 | */ 189 | result_type: string; 190 | } 191 | | { 192 | type: "microsecond"; 193 | /** 194 | * The result type, which must be a defined scalar type in the schema response. 195 | */ 196 | result_type: string; 197 | } 198 | | { 199 | type: "second"; 200 | /** 201 | * The result type, which must be a defined scalar type in the schema response. 202 | */ 203 | result_type: string; 204 | } 205 | | { 206 | type: "minute"; 207 | /** 208 | * The result type, which must be a defined scalar type in the schema response. 209 | */ 210 | result_type: string; 211 | } 212 | | { 213 | type: "hour"; 214 | /** 215 | * The result type, which must be a defined scalar type in the schema response. 216 | */ 217 | result_type: string; 218 | } 219 | | { 220 | type: "day"; 221 | /** 222 | * The result type, which must be a defined scalar type in the schema response. 223 | */ 224 | result_type: string; 225 | } 226 | | { 227 | type: "week"; 228 | /** 229 | * The result type, which must be a defined scalar type in the schema response. 230 | */ 231 | result_type: string; 232 | } 233 | | { 234 | type: "month"; 235 | /** 236 | * The result type, which must be a defined scalar type in the schema response. 237 | */ 238 | result_type: string; 239 | } 240 | | { 241 | type: "quarter"; 242 | /** 243 | * The result type, which must be a defined scalar type in the schema response. 244 | */ 245 | result_type: string; 246 | } 247 | | { 248 | type: "year"; 249 | /** 250 | * The result type, which must be a defined scalar type in the schema response. 251 | */ 252 | result_type: string; 253 | } 254 | | { 255 | type: "day_of_week"; 256 | /** 257 | * The result type, which must be a defined scalar type in the schema response. 258 | */ 259 | result_type: string; 260 | } 261 | | { 262 | type: "day_of_year"; 263 | /** 264 | * The result type, which must be a defined scalar type in the schema response. 265 | */ 266 | result_type: string; 267 | } 268 | | { 269 | type: "custom"; 270 | /** 271 | * The scalar or object type of the result of this function 272 | */ 273 | result_type: Type; 274 | }; 275 | export type Aggregate = 276 | | { 277 | type: "column_count"; 278 | /** 279 | * The column to apply the count aggregate function to 280 | */ 281 | column: string; 282 | /** 283 | * Arguments to satisfy the column specified by 'column' 284 | */ 285 | arguments?: { 286 | [k: string]: Argument; 287 | }; 288 | /** 289 | * Path to a nested field within an object column 290 | */ 291 | field_path?: string[] | null; 292 | /** 293 | * Whether or not only distinct items should be counted 294 | */ 295 | distinct: boolean; 296 | } 297 | | { 298 | type: "single_column"; 299 | /** 300 | * The column to apply the aggregation function to 301 | */ 302 | column: string; 303 | /** 304 | * Arguments to satisfy the column specified by 'column' 305 | */ 306 | arguments?: { 307 | [k: string]: Argument; 308 | }; 309 | /** 310 | * Path to a nested field within an object column 311 | */ 312 | field_path?: string[] | null; 313 | /** 314 | * Single column aggregate function name. 315 | */ 316 | function: string; 317 | } 318 | | { 319 | type: "star_count"; 320 | }; 321 | export type Argument = 322 | | { 323 | type: "variable"; 324 | name: string; 325 | } 326 | | { 327 | type: "literal"; 328 | value: unknown; 329 | }; 330 | export type Field = 331 | | { 332 | type: "column"; 333 | column: string; 334 | /** 335 | * When the type of the column is a (possibly-nullable) array or object, the caller can request a subset of the complete column data, by specifying fields to fetch here. If omitted, the column data will be fetched in full. 336 | */ 337 | fields?: NestedField | null; 338 | arguments?: { 339 | [k: string]: Argument; 340 | }; 341 | } 342 | | { 343 | type: "relationship"; 344 | query: Query; 345 | /** 346 | * The name of the relationship to follow for the subquery 347 | */ 348 | relationship: string; 349 | /** 350 | * Values to be provided to any collection arguments 351 | */ 352 | arguments: { 353 | [k: string]: RelationshipArgument; 354 | }; 355 | }; 356 | export type NestedField = NestedObject | NestedArray | NestedCollection; 357 | export type RelationshipArgument = 358 | | { 359 | type: "variable"; 360 | name: string; 361 | } 362 | | { 363 | type: "literal"; 364 | value: unknown; 365 | } 366 | | { 367 | type: "column"; 368 | name: string; 369 | }; 370 | export type OrderDirection = "asc" | "desc"; 371 | export type OrderByTarget = 372 | | { 373 | type: "column"; 374 | /** 375 | * Any (object) relationships to traverse to reach this column. Only non-empty if the 'relationships' capability is supported. 'PathElement.field_path' will only be non-empty if the 'relationships.nested.ordering' capability is supported. 376 | */ 377 | path: PathElement[]; 378 | /** 379 | * The name of the column 380 | */ 381 | name: string; 382 | /** 383 | * Arguments to satisfy the column specified by 'name' 384 | */ 385 | arguments?: { 386 | [k: string]: Argument; 387 | }; 388 | /** 389 | * Path to a nested field within an object column. Only non-empty if the 'query.nested_fields.order_by' capability is supported. 390 | */ 391 | field_path?: string[] | null; 392 | } 393 | | { 394 | type: "aggregate"; 395 | /** 396 | * Non-empty collection of relationships to traverse. Only non-empty if the 'relationships' capability is supported. 'PathElement.field_path' will only be non-empty if the 'relationships.nested.ordering' capability is supported. 397 | */ 398 | path: PathElement[]; 399 | /** 400 | * The aggregation method to use 401 | */ 402 | aggregate: Aggregate; 403 | }; 404 | export type Expression = 405 | | { 406 | type: "and"; 407 | expressions: Expression[]; 408 | } 409 | | { 410 | type: "or"; 411 | expressions: Expression[]; 412 | } 413 | | { 414 | type: "not"; 415 | expression: Expression; 416 | } 417 | | { 418 | type: "unary_comparison_operator"; 419 | column: ComparisonTarget; 420 | operator: UnaryComparisonOperator; 421 | } 422 | | { 423 | type: "binary_comparison_operator"; 424 | column: ComparisonTarget; 425 | operator: string; 426 | value: ComparisonValue; 427 | } 428 | | { 429 | type: "array_comparison"; 430 | column: ComparisonTarget; 431 | comparison: ArrayComparison; 432 | } 433 | | { 434 | type: "exists"; 435 | in_collection: ExistsInCollection; 436 | predicate?: Expression | null; 437 | }; 438 | export type ComparisonTarget = 439 | | { 440 | type: "column"; 441 | /** 442 | * The name of the column 443 | */ 444 | name: string; 445 | /** 446 | * Arguments to satisfy the column specified by 'name' 447 | */ 448 | arguments?: { 449 | [k: string]: Argument; 450 | }; 451 | /** 452 | * Path to a nested field within an object column. Only non-empty if the 'query.nested_fields.filter_by' capability is supported. 453 | */ 454 | field_path?: string[] | null; 455 | } 456 | | { 457 | type: "aggregate"; 458 | /** 459 | * Non-empty collection of relationships to traverse 460 | */ 461 | path: PathElement[]; 462 | /** 463 | * The aggregation method to use 464 | */ 465 | aggregate: Aggregate; 466 | }; 467 | export type UnaryComparisonOperator = "is_null"; 468 | export type ComparisonValue = 469 | | { 470 | type: "column"; 471 | /** 472 | * Any relationships to traverse to reach this column. Only non-empty if the 'relationships.relation_comparisons' is supported. 473 | */ 474 | path: PathElement[]; 475 | /** 476 | * The name of the column 477 | */ 478 | name: string; 479 | /** 480 | * Arguments to satisfy the column specified by 'name' 481 | */ 482 | arguments?: { 483 | [k: string]: Argument; 484 | }; 485 | /** 486 | * Path to a nested field within an object column. Only non-empty if the 'query.nested_fields.filter_by' capability is supported. 487 | */ 488 | field_path?: string[] | null; 489 | /** 490 | * The scope in which this column exists, identified by an top-down index into the stack of scopes. The stack grows inside each `Expression::Exists`, so scope 0 (the default) refers to the current collection, and each subsequent index refers to the collection outside its predecessor's immediately enclosing `Expression::Exists` expression. Only used if the 'query.exists.named_scopes' capability is supported. 491 | */ 492 | scope?: number | null; 493 | } 494 | | { 495 | type: "scalar"; 496 | value: unknown; 497 | } 498 | | { 499 | type: "variable"; 500 | name: string; 501 | }; 502 | export type ArrayComparison = 503 | | { 504 | type: "contains"; 505 | value: ComparisonValue; 506 | } 507 | | { 508 | type: "is_empty"; 509 | }; 510 | export type ExistsInCollection = 511 | | { 512 | type: "related"; 513 | /** 514 | * Path to a nested field within an object column that must be navigated before the relationship is navigated. Only non-empty if the 'relationships.nested.filtering' capability is supported. 515 | */ 516 | field_path?: string[] | null; 517 | /** 518 | * The name of the relationship to follow 519 | */ 520 | relationship: string; 521 | /** 522 | * Values to be provided to any collection arguments 523 | */ 524 | arguments: { 525 | [k: string]: RelationshipArgument; 526 | }; 527 | } 528 | | { 529 | type: "unrelated"; 530 | /** 531 | * The name of a collection 532 | */ 533 | collection: string; 534 | /** 535 | * Values to be provided to any collection arguments 536 | */ 537 | arguments: { 538 | [k: string]: RelationshipArgument; 539 | }; 540 | } 541 | | { 542 | type: "nested_collection"; 543 | column_name: string; 544 | arguments?: { 545 | [k: string]: Argument; 546 | }; 547 | /** 548 | * Path to a nested collection via object columns 549 | */ 550 | field_path?: string[]; 551 | } 552 | | { 553 | type: "nested_scalar_collection"; 554 | column_name: string; 555 | arguments?: { 556 | [k: string]: Argument; 557 | }; 558 | /** 559 | * Path to a nested collection via object columns 560 | */ 561 | field_path?: string[]; 562 | }; 563 | export type Dimension = { 564 | type: "column"; 565 | /** 566 | * Any (object) relationships to traverse to reach this column. Only non-empty if the 'relationships' capability is supported. 567 | */ 568 | path: PathElement[]; 569 | /** 570 | * The name of the column 571 | */ 572 | column_name: string; 573 | /** 574 | * Arguments to satisfy the column specified by 'column_name' 575 | */ 576 | arguments?: { 577 | [k: string]: Argument; 578 | }; 579 | /** 580 | * Path to a nested field within an object column 581 | */ 582 | field_path?: string[] | null; 583 | /** 584 | * The name of the extraction function to apply to the selected value, if any 585 | */ 586 | extraction?: string | null; 587 | }; 588 | export type GroupExpression = 589 | | { 590 | type: "and"; 591 | expressions: GroupExpression[]; 592 | } 593 | | { 594 | type: "or"; 595 | expressions: GroupExpression[]; 596 | } 597 | | { 598 | type: "not"; 599 | expression: GroupExpression; 600 | } 601 | | { 602 | type: "unary_comparison_operator"; 603 | target: AggregateComparisonTarget; 604 | operator: UnaryComparisonOperator; 605 | } 606 | | { 607 | type: "binary_comparison_operator"; 608 | target: AggregateComparisonTarget; 609 | operator: string; 610 | value: AggregateComparisonValue; 611 | }; 612 | export type AggregateComparisonTarget = { 613 | type: "aggregate"; 614 | aggregate: Aggregate; 615 | }; 616 | export type AggregateComparisonValue = 617 | | { 618 | type: "scalar"; 619 | value: unknown; 620 | } 621 | | { 622 | type: "variable"; 623 | name: string; 624 | }; 625 | export type GroupOrderByTarget = 626 | | { 627 | type: "dimension"; 628 | /** 629 | * The index of the dimension to order by, selected from the dimensions provided in the `Grouping` request. 630 | */ 631 | index: number; 632 | } 633 | | { 634 | type: "aggregate"; 635 | /** 636 | * Aggregation method to apply 637 | */ 638 | aggregate: Aggregate; 639 | }; 640 | export type RelationshipType = "object" | "array"; 641 | /** 642 | * Query responses may return multiple RowSets when using queries with variables. Else, there should always be exactly one RowSet 643 | */ 644 | export type QueryResponse = RowSet[]; 645 | export type MutationOperation = { 646 | type: "procedure"; 647 | /** 648 | * The name of a procedure 649 | */ 650 | name: string; 651 | /** 652 | * Any named procedure arguments 653 | */ 654 | arguments: { 655 | [k: string]: unknown; 656 | }; 657 | /** 658 | * The fields to return from the result, or null to return everything 659 | */ 660 | fields?: NestedField | null; 661 | }; 662 | export type MutationOperationResults = { 663 | type: "procedure"; 664 | result: unknown; 665 | }; 666 | 667 | export interface SchemaRoot { 668 | capabilities_response: CapabilitiesResponse; 669 | schema_response: SchemaResponse; 670 | query_request: QueryRequest; 671 | query_response: QueryResponse; 672 | mutation_request: MutationRequest; 673 | mutation_response: MutationResponse; 674 | explain_response: ExplainResponse; 675 | error_response: ErrorResponse; 676 | validate_response: ValidateResponse; 677 | } 678 | export interface CapabilitiesResponse { 679 | version: string; 680 | capabilities: Capabilities; 681 | } 682 | /** 683 | * Describes the features of the specification which a data connector implements. 684 | */ 685 | export interface Capabilities { 686 | query: QueryCapabilities; 687 | mutation: MutationCapabilities; 688 | relationships?: RelationshipCapabilities | null; 689 | } 690 | export interface QueryCapabilities { 691 | /** 692 | * Does the connector support aggregate queries 693 | */ 694 | aggregates?: AggregateCapabilities | null; 695 | /** 696 | * Does the connector support queries which use variables 697 | */ 698 | variables?: LeafCapability | null; 699 | /** 700 | * Does the connector support explaining queries 701 | */ 702 | explain?: LeafCapability | null; 703 | /** 704 | * Does the connector support nested fields 705 | */ 706 | nested_fields?: NestedFieldCapabilities; 707 | /** 708 | * Does the connector support EXISTS predicates 709 | */ 710 | exists?: ExistsCapabilities; 711 | } 712 | export interface AggregateCapabilities { 713 | /** 714 | * Does the connector support filtering based on aggregated values 715 | */ 716 | filter_by?: LeafCapability | null; 717 | /** 718 | * Does the connector support aggregations over groups 719 | */ 720 | group_by?: GroupByCapabilities | null; 721 | } 722 | /** 723 | * A unit value to indicate a particular leaf capability is supported. This is an empty struct to allow for future sub-capabilities. 724 | */ 725 | export interface LeafCapability {} 726 | export interface GroupByCapabilities { 727 | /** 728 | * Does the connector support post-grouping predicates 729 | */ 730 | filter?: LeafCapability | null; 731 | /** 732 | * Does the connector support post-grouping ordering 733 | */ 734 | order?: LeafCapability | null; 735 | /** 736 | * Does the connector support post-grouping pagination 737 | */ 738 | paginate?: LeafCapability | null; 739 | } 740 | export interface NestedFieldCapabilities { 741 | /** 742 | * Does the connector support filtering by values of nested fields 743 | */ 744 | filter_by?: NestedFieldFilterByCapabilities | null; 745 | /** 746 | * Does the connector support ordering by values of nested fields 747 | */ 748 | order_by?: LeafCapability | null; 749 | /** 750 | * Does the connector support aggregating values within nested fields 751 | */ 752 | aggregates?: LeafCapability | null; 753 | /** 754 | * Does the connector support nested collection queries using `NestedField::NestedCollection` 755 | */ 756 | nested_collections?: LeafCapability | null; 757 | } 758 | export interface NestedFieldFilterByCapabilities { 759 | /** 760 | * Does the connector support filtering over nested arrays (ie. Expression::ArrayComparison) 761 | */ 762 | nested_arrays?: NestedArrayFilterByCapabilities | null; 763 | } 764 | export interface NestedArrayFilterByCapabilities { 765 | /** 766 | * Does the connector support filtering over nested arrays by checking if the array contains a value. This must be supported for all types that can be contained in an array that implement an 'eq' comparison operator. 767 | */ 768 | contains?: LeafCapability | null; 769 | /** 770 | * Does the connector support filtering over nested arrays by checking if the array is empty. This must be supported no matter what type is contained in the array. 771 | */ 772 | is_empty?: LeafCapability | null; 773 | } 774 | export interface ExistsCapabilities { 775 | /** 776 | * Does the connector support named scopes in column references inside EXISTS predicates 777 | */ 778 | named_scopes?: LeafCapability | null; 779 | /** 780 | * Does the connector support ExistsInCollection::Unrelated 781 | */ 782 | unrelated?: LeafCapability | null; 783 | /** 784 | * Does the connector support ExistsInCollection::NestedCollection 785 | */ 786 | nested_collections?: LeafCapability | null; 787 | /** 788 | * Does the connector support filtering over nested scalar arrays using existential quantification. This means the connector must support ExistsInCollection::NestedScalarCollection. 789 | */ 790 | nested_scalar_collections?: LeafCapability | null; 791 | } 792 | export interface MutationCapabilities { 793 | /** 794 | * Does the connector support executing multiple mutations in a transaction. 795 | */ 796 | transactional?: LeafCapability | null; 797 | /** 798 | * Does the connector support explaining mutations 799 | */ 800 | explain?: LeafCapability | null; 801 | } 802 | export interface RelationshipCapabilities { 803 | /** 804 | * Does the connector support comparisons that involve related collections (ie. joins)? 805 | */ 806 | relation_comparisons?: LeafCapability | null; 807 | /** 808 | * Does the connector support ordering by an aggregated array relationship? 809 | */ 810 | order_by_aggregate?: LeafCapability | null; 811 | /** 812 | * Does the connector support navigating a relationship from inside a nested object 813 | */ 814 | nested?: NestedRelationshipCapabilities | null; 815 | } 816 | export interface NestedRelationshipCapabilities { 817 | /** 818 | * Does the connector support navigating a relationship from inside a nested object inside a nested array 819 | */ 820 | array?: LeafCapability | null; 821 | /** 822 | * Does the connector support filtering over a relationship that starts from inside a nested object 823 | */ 824 | filtering?: LeafCapability | null; 825 | /** 826 | * Does the connector support ordering over a relationship that starts from inside a nested object 827 | */ 828 | ordering?: LeafCapability | null; 829 | } 830 | export interface SchemaResponse { 831 | /** 832 | * A list of scalar types which will be used as the types of collection columns 833 | */ 834 | scalar_types: { 835 | [k: string]: ScalarType; 836 | }; 837 | /** 838 | * A list of object types which can be used as the types of arguments, or return types of procedures. Names should not overlap with scalar type names. 839 | */ 840 | object_types: { 841 | [k: string]: ObjectType; 842 | }; 843 | /** 844 | * Collections which are available for queries 845 | */ 846 | collections: CollectionInfo[]; 847 | /** 848 | * Functions (i.e. collections which return a single column and row) 849 | */ 850 | functions: FunctionInfo[]; 851 | /** 852 | * Procedures which are available for execution as part of mutations 853 | */ 854 | procedures: ProcedureInfo[]; 855 | /** 856 | * Schema data which is relevant to features enabled by capabilities 857 | */ 858 | capabilities?: CapabilitySchemaInfo | null; 859 | } 860 | /** 861 | * The definition of a scalar type, i.e. types that can be used as the types of columns. 862 | */ 863 | export interface ScalarType { 864 | /** 865 | * A description of valid values for this scalar type. 866 | */ 867 | representation: TypeRepresentation; 868 | /** 869 | * A map from aggregate function names to their definitions. Result type names must be defined scalar types declared in ScalarTypesCapabilities. 870 | */ 871 | aggregate_functions: { 872 | [k: string]: AggregateFunctionDefinition; 873 | }; 874 | /** 875 | * A map from comparison operator names to their definitions. Argument type names must be defined scalar types declared in ScalarTypesCapabilities. 876 | */ 877 | comparison_operators: { 878 | [k: string]: ComparisonOperatorDefinition; 879 | }; 880 | /** 881 | * A map from extraction function names to their definitions. 882 | */ 883 | extraction_functions?: { 884 | [k: string]: ExtractionFunctionDefinition; 885 | }; 886 | } 887 | /** 888 | * The definition of an object type 889 | */ 890 | export interface ObjectType { 891 | /** 892 | * Description of this type 893 | */ 894 | description?: string | null; 895 | /** 896 | * Fields defined on this object type 897 | */ 898 | fields: { 899 | [k: string]: ObjectField; 900 | }; 901 | /** 902 | * Any foreign keys defined for this object type's columns 903 | */ 904 | foreign_keys: { 905 | [k: string]: ForeignKeyConstraint; 906 | }; 907 | } 908 | /** 909 | * The definition of an object field 910 | */ 911 | export interface ObjectField { 912 | /** 913 | * Description of this field 914 | */ 915 | description?: string | null; 916 | /** 917 | * The type of this field 918 | */ 919 | type: Type; 920 | /** 921 | * The arguments available to the field - Matches implementation from CollectionInfo 922 | */ 923 | arguments?: { 924 | [k: string]: ArgumentInfo; 925 | }; 926 | } 927 | export interface ArgumentInfo { 928 | /** 929 | * Argument description 930 | */ 931 | description?: string | null; 932 | /** 933 | * The name of the type of this argument 934 | */ 935 | type: Type; 936 | } 937 | export interface ForeignKeyConstraint { 938 | /** 939 | * The columns on which you want want to define the foreign key. This is a mapping between fields on object type to columns on the foreign collection. The column on the foreign collection is specified via a field path (ie. an array of field names that descend through nested object fields). The field path must only contain a single item, meaning a column on the foreign collection's type, unless the 'relationships.nested' capability is supported, in which case multiple items can be used to denote a nested object field. 940 | */ 941 | column_mapping: { 942 | [k: string]: string[]; 943 | }; 944 | /** 945 | * The name of a collection 946 | */ 947 | foreign_collection: string; 948 | } 949 | export interface CollectionInfo { 950 | /** 951 | * The name of the collection 952 | * 953 | * Note: these names are abstract - there is no requirement that this name correspond to the name of an actual collection in the database. 954 | */ 955 | name: string; 956 | /** 957 | * Description of the collection 958 | */ 959 | description?: string | null; 960 | /** 961 | * Any arguments that this collection requires 962 | */ 963 | arguments: { 964 | [k: string]: ArgumentInfo; 965 | }; 966 | /** 967 | * The name of the collection's object type 968 | */ 969 | type: string; 970 | /** 971 | * Any uniqueness constraints enforced on this collection 972 | */ 973 | uniqueness_constraints: { 974 | [k: string]: UniquenessConstraint; 975 | }; 976 | } 977 | export interface UniquenessConstraint { 978 | /** 979 | * A list of columns which this constraint requires to be unique 980 | */ 981 | unique_columns: string[]; 982 | } 983 | export interface FunctionInfo { 984 | /** 985 | * The name of the function 986 | */ 987 | name: string; 988 | /** 989 | * Description of the function 990 | */ 991 | description?: string | null; 992 | /** 993 | * Any arguments that this collection requires 994 | */ 995 | arguments: { 996 | [k: string]: ArgumentInfo; 997 | }; 998 | /** 999 | * The name of the function's result type 1000 | */ 1001 | result_type: Type; 1002 | } 1003 | export interface ProcedureInfo { 1004 | /** 1005 | * The name of the procedure 1006 | */ 1007 | name: string; 1008 | /** 1009 | * Column description 1010 | */ 1011 | description?: string | null; 1012 | /** 1013 | * Any arguments that this collection requires 1014 | */ 1015 | arguments: { 1016 | [k: string]: ArgumentInfo; 1017 | }; 1018 | /** 1019 | * The name of the result type 1020 | */ 1021 | result_type: Type; 1022 | } 1023 | export interface CapabilitySchemaInfo { 1024 | /** 1025 | * Schema information relevant to query capabilities 1026 | */ 1027 | query?: QueryCapabilitiesSchemaInfo | null; 1028 | } 1029 | export interface QueryCapabilitiesSchemaInfo { 1030 | /** 1031 | * Schema information relevant to aggregate query capabilities 1032 | */ 1033 | aggregates?: AggregateCapabilitiesSchemaInfo | null; 1034 | } 1035 | export interface AggregateCapabilitiesSchemaInfo { 1036 | /** 1037 | * The scalar type which should be used for the return type of count (star_count and column_count) operations. 1038 | */ 1039 | count_scalar_type: string; 1040 | } 1041 | /** 1042 | * This is the request body of the query POST endpoint 1043 | */ 1044 | export interface QueryRequest { 1045 | /** 1046 | * The name of a collection 1047 | */ 1048 | collection: string; 1049 | /** 1050 | * The query syntax tree 1051 | */ 1052 | query: Query; 1053 | /** 1054 | * Values to be provided to any collection arguments 1055 | */ 1056 | arguments: { 1057 | [k: string]: Argument; 1058 | }; 1059 | /** 1060 | * Any relationships between collections involved in the query request. Only used if the 'relationships' capability is supported. 1061 | */ 1062 | collection_relationships: { 1063 | [k: string]: Relationship; 1064 | }; 1065 | /** 1066 | * One set of named variables for each rowset to fetch. Each variable set should be subtituted in turn, and a fresh set of rows returned. Only used if the 'query.variables' capability is supported. 1067 | */ 1068 | variables?: 1069 | | { 1070 | [k: string]: unknown; 1071 | }[] 1072 | | null; 1073 | } 1074 | export interface Query { 1075 | /** 1076 | * Aggregate fields of the query. Only used if the 'query.aggregates' capability is supported. 1077 | */ 1078 | aggregates?: { 1079 | [k: string]: Aggregate; 1080 | } | null; 1081 | /** 1082 | * Fields of the query 1083 | */ 1084 | fields?: { 1085 | [k: string]: Field; 1086 | } | null; 1087 | /** 1088 | * Optionally limit to N results 1089 | */ 1090 | limit?: number | null; 1091 | /** 1092 | * Optionally offset from the Nth result 1093 | */ 1094 | offset?: number | null; 1095 | /** 1096 | * Optionally specify how rows should be ordered 1097 | */ 1098 | order_by?: OrderBy | null; 1099 | /** 1100 | * Optionally specify a predicate to apply to the rows 1101 | */ 1102 | predicate?: Expression | null; 1103 | /** 1104 | * Optionally group and aggregate the selected rows. Only used if the 'query.aggregates.group_by' capability is supported. 1105 | */ 1106 | groups?: Grouping | null; 1107 | } 1108 | export interface NestedObject { 1109 | type: "object"; 1110 | fields: { 1111 | [k: string]: Field; 1112 | }; 1113 | } 1114 | export interface NestedArray { 1115 | type: "array"; 1116 | fields: NestedField; 1117 | } 1118 | /** 1119 | * Perform a query over the nested array's rows. Only used if the 'query.nested_fields.nested_collections' capability is supported. 1120 | */ 1121 | export interface NestedCollection { 1122 | type: "collection"; 1123 | query: Query; 1124 | } 1125 | export interface OrderBy { 1126 | /** 1127 | * The elements to order by, in priority order 1128 | */ 1129 | elements: OrderByElement[]; 1130 | } 1131 | export interface OrderByElement { 1132 | order_direction: OrderDirection; 1133 | target: OrderByTarget; 1134 | } 1135 | export interface PathElement { 1136 | /** 1137 | * Path to a nested field within an object column that must be navigated before the relationship is navigated. Only non-empty if the 'relationships.nested' capability is supported (plus perhaps one of the sub-capabilities, depending on the feature using the PathElement). 1138 | */ 1139 | field_path?: string[] | null; 1140 | /** 1141 | * The name of the relationship to follow 1142 | */ 1143 | relationship: string; 1144 | /** 1145 | * Values to be provided to any collection arguments 1146 | */ 1147 | arguments: { 1148 | [k: string]: RelationshipArgument; 1149 | }; 1150 | /** 1151 | * A predicate expression to apply to the target collection 1152 | */ 1153 | predicate?: Expression | null; 1154 | } 1155 | export interface Grouping { 1156 | /** 1157 | * Dimensions along which to partition the data 1158 | */ 1159 | dimensions: Dimension[]; 1160 | /** 1161 | * Aggregates to compute in each group 1162 | */ 1163 | aggregates: { 1164 | [k: string]: Aggregate; 1165 | }; 1166 | /** 1167 | * Optionally specify a predicate to apply after grouping rows. Only used if the 'query.aggregates.group_by.filter' capability is supported. 1168 | */ 1169 | predicate?: GroupExpression | null; 1170 | /** 1171 | * Optionally specify how groups should be ordered Only used if the 'query.aggregates.group_by.order' capability is supported. 1172 | */ 1173 | order_by?: GroupOrderBy | null; 1174 | /** 1175 | * Optionally limit to N groups Only used if the 'query.aggregates.group_by.paginate' capability is supported. 1176 | */ 1177 | limit?: number | null; 1178 | /** 1179 | * Optionally offset from the Nth group Only used if the 'query.aggregates.group_by.paginate' capability is supported. 1180 | */ 1181 | offset?: number | null; 1182 | } 1183 | export interface GroupOrderBy { 1184 | /** 1185 | * The elements to order by, in priority order 1186 | */ 1187 | elements: GroupOrderByElement[]; 1188 | } 1189 | export interface GroupOrderByElement { 1190 | order_direction: OrderDirection; 1191 | target: GroupOrderByTarget; 1192 | } 1193 | export interface Relationship { 1194 | /** 1195 | * A mapping between columns on the source row to columns on the target collection. The column on the target collection is specified via a field path (ie. an array of field names that descend through nested object fields). The field path will only contain a single item, meaning a column on the target collection's type, unless the 'relationships.nested' capability is supported, in which case multiple items denotes a nested object field. 1196 | */ 1197 | column_mapping: { 1198 | [k: string]: string[]; 1199 | }; 1200 | relationship_type: RelationshipType; 1201 | /** 1202 | * The name of a collection 1203 | */ 1204 | target_collection: string; 1205 | /** 1206 | * Values to be provided to any collection arguments 1207 | */ 1208 | arguments: { 1209 | [k: string]: RelationshipArgument; 1210 | }; 1211 | } 1212 | export interface RowSet { 1213 | /** 1214 | * The results of the aggregates returned by the query 1215 | */ 1216 | aggregates?: { 1217 | [k: string]: unknown; 1218 | } | null; 1219 | /** 1220 | * The rows returned by the query, corresponding to the query's fields 1221 | */ 1222 | rows?: 1223 | | { 1224 | [k: string]: RowFieldValue; 1225 | }[] 1226 | | null; 1227 | /** 1228 | * The results of any grouping operation 1229 | */ 1230 | groups?: Group[] | null; 1231 | } 1232 | export type RowFieldValue = unknown; // Manually corrected :( 1233 | export interface Group { 1234 | /** 1235 | * Values of dimensions which identify this group 1236 | */ 1237 | dimensions: unknown[]; 1238 | /** 1239 | * Aggregates computed within this group 1240 | */ 1241 | aggregates: { 1242 | [k: string]: unknown; 1243 | }; 1244 | } 1245 | export interface MutationRequest { 1246 | /** 1247 | * The mutation operations to perform 1248 | */ 1249 | operations: MutationOperation[]; 1250 | /** 1251 | * The relationships between collections involved in the entire mutation request. Only used if the 'relationships' capability is supported. 1252 | */ 1253 | collection_relationships: { 1254 | [k: string]: Relationship; 1255 | }; 1256 | } 1257 | export interface MutationResponse { 1258 | /** 1259 | * The results of each mutation operation, in the same order as they were received 1260 | */ 1261 | operation_results: MutationOperationResults[]; 1262 | } 1263 | export interface ExplainResponse { 1264 | /** 1265 | * A list of human-readable key-value pairs describing a query execution plan. For example, a connector for a relational database might return the generated SQL and/or the output of the `EXPLAIN` command. An API-based connector might encode a list of statically-known API calls which would be made. 1266 | */ 1267 | details: { 1268 | [k: string]: string; 1269 | }; 1270 | } 1271 | export interface ErrorResponse { 1272 | /** 1273 | * A human-readable summary of the error 1274 | */ 1275 | message: string; 1276 | /** 1277 | * Any additional structured information about the error 1278 | */ 1279 | details: { 1280 | [k: string]: unknown; 1281 | }; 1282 | } 1283 | export interface ValidateResponse { 1284 | schema: SchemaResponse; 1285 | capabilities: CapabilitiesResponse; 1286 | resolved_configuration: string; 1287 | } 1288 | -------------------------------------------------------------------------------- /src/schema/schema.generated.ts.patch: -------------------------------------------------------------------------------- 1 | diff --git a/src/schema/schema.generated.ts b/src/schema/schema.generated.ts 2 | index 372b5ee..dc8fed2 100644 3 | --- a/src/schema/schema.generated.ts 4 | +++ b/src/schema/schema.generated.ts 5 | @@ -1101,9 +1101,7 @@ export interface RowSet { 6 | */ 7 | groups?: Group[] | null; 8 | } 9 | -export interface RowFieldValue { 10 | - [k: string]: unknown; 11 | -} 12 | +export type RowFieldValue = unknown; // Manually corrected :( 13 | export interface Group { 14 | /** 15 | * Values of dimensions which identify this group 16 | -------------------------------------------------------------------------------- /src/schema/version.generated.ts: -------------------------------------------------------------------------------- 1 | export const VERSION = "0.2.0"; 2 | export const VERSION_HEADER_NAME="X-Hasura-NDC-Version" 3 | -------------------------------------------------------------------------------- /src/server.ts: -------------------------------------------------------------------------------- 1 | import Fastify, { FastifyRequest } from "fastify"; 2 | import opentelemetry, { 3 | SpanStatusCode, 4 | } from "@opentelemetry/api"; 5 | 6 | import { Connector } from "./connector"; 7 | import { ConnectorError } from "./error"; 8 | import { configureFastifyLogging } from "./logging"; 9 | 10 | import { 11 | CapabilitiesResponseSchema, 12 | SchemaResponseSchema, 13 | QueryRequestSchema, 14 | QueryResponseSchema, 15 | ExplainResponseSchema, 16 | MutationRequestSchema, 17 | MutationResponseSchema, 18 | ErrorResponseSchema, 19 | CapabilitiesResponse, 20 | SchemaResponse, 21 | MutationResponse, 22 | MutationRequest, 23 | QueryRequest, 24 | VERSION, 25 | VERSION_HEADER_NAME, 26 | ErrorResponse, 27 | } from "./schema"; 28 | 29 | import { Options as AjvOptions } from "ajv"; 30 | import { withActiveSpan } from "./instrumentation"; 31 | import { Registry, collectDefaultMetrics } from "prom-client"; 32 | import semver from "semver"; 33 | 34 | // Create custom Ajv options to handle Rust's uint types which are formats used in the JSON schemas, so this converts that to a number 35 | const customAjvOptions: AjvOptions = { 36 | allErrors: true, 37 | removeAdditional: true, 38 | formats: { 39 | uint: { 40 | validate: (data: any) => { 41 | return ( 42 | typeof data === "number" && 43 | data >= 0 && 44 | data <= 4294967295 && 45 | Number.isInteger(data) 46 | ); 47 | }, 48 | type: "number", 49 | }, 50 | uint32: { 51 | validate: (data: any) => { 52 | return ( 53 | typeof data === "number" && 54 | data >= 0 && 55 | data <= 4294967295 && 56 | Number.isInteger(data) 57 | ); 58 | }, 59 | type: "number", 60 | }, 61 | }, 62 | }; 63 | 64 | const errorResponses = { 65 | 400: ErrorResponseSchema, 66 | 403: ErrorResponseSchema, 67 | 409: ErrorResponseSchema, 68 | 422: ErrorResponseSchema, 69 | 500: ErrorResponseSchema, 70 | 501: ErrorResponseSchema, 71 | 502: ErrorResponseSchema, 72 | }; 73 | 74 | export interface ServerOptions { 75 | configuration: string; 76 | host: string; 77 | port: number; 78 | serviceTokenSecret: string | undefined; 79 | logLevel: string; 80 | prettyPrintLogs: string; 81 | } 82 | 83 | const tracer = opentelemetry.trace.getTracer("ndc-sdk-typescript.server"); 84 | 85 | export async function startServer( 86 | connector: Connector, 87 | options: ServerOptions 88 | ) { 89 | const configuration = await connector.parseConfiguration( 90 | options.configuration 91 | ); 92 | 93 | const metrics = new Registry(); 94 | collectDefaultMetrics({ register: metrics }); 95 | 96 | const state = await connector.tryInitState(configuration, metrics); 97 | 98 | const server = Fastify({ 99 | logger: configureFastifyLogging(options), 100 | bodyLimit: 1048576 * 30, // 30mb body limit 101 | ajv: { 102 | customOptions: customAjvOptions, 103 | }, 104 | }); 105 | 106 | // temporary: use JSON.stringify instead of https://github.com/fastify/fast-json-stringify 107 | // todo: remove this once issue is addressed https://github.com/fastify/fastify/issues/5073 108 | server.setSerializerCompiler( 109 | ({ schema, method, url, httpStatus, contentType }) => { 110 | return (data) => JSON.stringify(data); 111 | } 112 | ); 113 | 114 | // Authorization handler 115 | server.addHook("preHandler", async (request, reply) => { 116 | // Don't apply authorization to the healthcheck endpoint 117 | if (request.routeOptions.method === "GET" && request.routeOptions.url === "/health") { 118 | return; 119 | } 120 | 121 | const expectedAuthHeader = 122 | options.serviceTokenSecret === undefined 123 | ? undefined 124 | : `Bearer ${options.serviceTokenSecret}`; 125 | 126 | if (request.headers.authorization === expectedAuthHeader) { 127 | return; 128 | } else { 129 | reply.code(401).send({ 130 | message: "Internal Error", 131 | details: { 132 | cause: "Bearer token does not match.", 133 | }, 134 | }); 135 | 136 | return reply; 137 | } 138 | }); 139 | 140 | // NDC Version header handler 141 | const lowercaseVersionHeaderName = VERSION_HEADER_NAME.toLowerCase(); 142 | const connectorSemVer = new semver.SemVer(VERSION); 143 | server.addHook("preHandler", async (request, reply) => { 144 | const versionHeader = request.headers[lowercaseVersionHeaderName]; 145 | if (versionHeader === undefined) { 146 | return; 147 | } 148 | 149 | if (Array.isArray(versionHeader)) { 150 | reply.code(400).send({ 151 | message: `Multiple ${VERSION_HEADER_NAME} headers received. Only one is supported.`, 152 | }) 153 | return reply; 154 | } 155 | 156 | let wantedSemVer: semver.SemVer; 157 | try { 158 | wantedSemVer = new semver.SemVer(versionHeader); 159 | } catch (e) { 160 | reply.code(400).send({ 161 | message: `Invalid semver in ${VERSION_HEADER_NAME}s header`, 162 | details: e instanceof Error ? { error: e.message } : {} 163 | }) 164 | return reply; 165 | } 166 | 167 | const wantedSemVerRange = new semver.Range(`^${wantedSemVer.toString()}`); 168 | 169 | if (!semver.satisfies(connectorSemVer, wantedSemVerRange)) { 170 | reply.code(400).send({ 171 | message: `The connector does not support the requested NDC version`, 172 | details: { 173 | connectorVersion: connectorSemVer.toString(), 174 | requestedVersionRange: wantedSemVerRange.toString(), 175 | } 176 | }) 177 | return reply; 178 | } 179 | }); 180 | 181 | server.get( 182 | "/capabilities", 183 | { 184 | schema: { 185 | response: { 186 | 200: CapabilitiesResponseSchema, 187 | ...errorResponses, 188 | }, 189 | }, 190 | }, 191 | (_request: FastifyRequest): CapabilitiesResponse => { 192 | return withActiveSpan( 193 | tracer, 194 | "getCapabilities", 195 | () => ({ 196 | version: VERSION, 197 | capabilities: connector.getCapabilities(configuration), 198 | }) 199 | ); 200 | } 201 | ); 202 | 203 | server.get("/health", async (_request): Promise => { 204 | return connector.getHealthReadiness 205 | ? await connector.getHealthReadiness(configuration, state) 206 | : undefined; 207 | }); 208 | 209 | server.get("/metrics", (_request) => { 210 | connector.fetchMetrics(configuration, state); 211 | return metrics.metrics(); 212 | }); 213 | 214 | server.get( 215 | "/schema", 216 | { 217 | schema: { 218 | response: { 219 | 200: SchemaResponseSchema, 220 | ...errorResponses, 221 | }, 222 | }, 223 | }, 224 | (_request): Promise => { 225 | return withActiveSpan( 226 | tracer, 227 | "getSchema", 228 | () => connector.getSchema(configuration) 229 | ); 230 | } 231 | ); 232 | 233 | server.post( 234 | "/query", 235 | { 236 | schema: { 237 | body: QueryRequestSchema, 238 | response: { 239 | 200: QueryResponseSchema, 240 | ...errorResponses, 241 | }, 242 | }, 243 | }, 244 | async ( 245 | request: FastifyRequest<{ 246 | Body: QueryRequest; 247 | }> 248 | ) => { 249 | request.log.debug({ requestHeaders: request.headers, requestBody: request.body }, "Query Request"); 250 | 251 | const queryResponse = await withActiveSpan( 252 | tracer, 253 | "handleQuery", 254 | () => connector.query(configuration, state, request.body) 255 | ); 256 | 257 | request.log.debug({ responseBody: queryResponse }, "Query Response"); 258 | return queryResponse; 259 | } 260 | ); 261 | 262 | server.post( 263 | "/query/explain", 264 | { 265 | schema: { 266 | body: QueryRequestSchema, 267 | response: { 268 | 200: ExplainResponseSchema, 269 | ...errorResponses, 270 | }, 271 | }, 272 | }, 273 | async (request: FastifyRequest<{ Body: QueryRequest }>) => { 274 | request.log.debug({ requestHeaders: request.headers, requestBody: request.body }, "Explain Request"); 275 | 276 | const explainResponse = await withActiveSpan( 277 | tracer, 278 | "handleQueryExplain", 279 | () => connector.queryExplain(configuration, state, request.body) 280 | ); 281 | 282 | request.log.debug( 283 | { responseBody: explainResponse }, 284 | "Query Explain Response" 285 | ); 286 | return explainResponse; 287 | } 288 | ); 289 | 290 | server.post( 291 | "/mutation", 292 | { 293 | schema: { 294 | body: MutationRequestSchema, 295 | response: { 296 | 200: MutationResponseSchema, 297 | ...errorResponses, 298 | }, 299 | }, 300 | }, 301 | async ( 302 | request: FastifyRequest<{ 303 | Body: MutationRequest; 304 | }> 305 | ): Promise => { 306 | request.log.debug({ requestHeaders: request.headers, requestBody: request.body }, "Mutation Request"); 307 | 308 | const mutationResponse = await withActiveSpan( 309 | tracer, 310 | "handleMutation", 311 | () => connector.mutation(configuration, state, request.body) 312 | ); 313 | 314 | request.log.debug( 315 | { responseBody: mutationResponse }, 316 | "Mutation Response" 317 | ); 318 | return mutationResponse; 319 | } 320 | ); 321 | 322 | server.post( 323 | "/mutation/explain", 324 | { 325 | schema: { 326 | body: MutationRequestSchema, 327 | response: { 328 | 200: ExplainResponseSchema, 329 | ...errorResponses, 330 | }, 331 | }, 332 | }, 333 | async (request: FastifyRequest<{ Body: MutationRequest }>) => { 334 | request.log.debug( 335 | { requestHeaders: request.headers, requestBody: request.body }, 336 | "Mutation Explain Request" 337 | ); 338 | 339 | const explainResponse = await withActiveSpan( 340 | tracer, 341 | "handleMutationExplain", 342 | () => connector.mutationExplain(configuration, state, request.body) 343 | ); 344 | 345 | request.log.debug( 346 | { responseBody: explainResponse }, 347 | "Mutation Explain Response" 348 | ); 349 | return explainResponse; 350 | } 351 | ); 352 | 353 | server.setErrorHandler(function(error, _request, reply) { 354 | // pino trace instrumentation will add trace information to log output 355 | this.log.error(error); 356 | 357 | if (error.validation) { 358 | reply.status(400).send({ 359 | message: 360 | "Validation Error - https://fastify.dev/docs/latest/Reference/Validation-and-Serialization#error-handling", 361 | details: error.validation, 362 | }); 363 | } else if (error instanceof ConnectorError) { 364 | // Send error response 365 | reply.status(error.statusCode).send({ 366 | message: error.message, 367 | details: error.details ?? {}, 368 | }); 369 | } else { 370 | const span = opentelemetry.trace.getActiveSpan(); 371 | span?.recordException(error); 372 | span?.setStatus({ code: SpanStatusCode.ERROR }); 373 | 374 | reply.status(500).send({ 375 | message: error.message, 376 | details: {}, 377 | }); 378 | } 379 | }); 380 | 381 | try { 382 | await server.listen({ port: options.port, host: options.host }); 383 | } catch (error) { 384 | server.log.error(error); 385 | process.exitCode = 1; 386 | } 387 | } 388 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "@tsconfig/node18", 3 | "compilerOptions": { 4 | "rootDir": "./src", 5 | "resolveJsonModule": true, 6 | "declaration": true, 7 | "declarationMap": true, 8 | "sourceMap": true, 9 | "outDir": "./dist" 10 | }, 11 | "include": [ 12 | "src/**/*.ts", 13 | "src/**/*.json" 14 | ] 15 | } 16 | -------------------------------------------------------------------------------- /typegen/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "generate_types" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | ndc-models = { git = "http://github.com/hasura/ndc-spec.git", tag = "v0.2.0" } 10 | schemars = "^0.8" 11 | serde = "^1.0" 12 | serde_json = "^1.0" 13 | serde_derive = "^1.0" 14 | -------------------------------------------------------------------------------- /typegen/regenerate-schema.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -eu -o pipefail 3 | 4 | # Generate JSON schema from Rust types 5 | cargo run -- ./src/schema 6 | 7 | # Generate TypeScript types from JSON schema 8 | json2ts -i ./src/schema/schema.generated.json -o ./src/schema/schema.generated.ts --no-additionalProperties 9 | echo './src/schema/schema.generated.ts generated' 10 | 11 | # Unfortunately we have a manual patch of the generated types in place 12 | # to fix a type generation issue. This applies that patch 13 | git add ./src/schema/schema.generated.ts 14 | git apply --3way ./src/schema/schema.generated.ts.patch 15 | -------------------------------------------------------------------------------- /typegen/src/main.rs: -------------------------------------------------------------------------------- 1 | use ndc_models::{ 2 | CapabilitiesResponse, ErrorResponse, ExplainResponse, MutationRequest, MutationResponse, 3 | QueryRequest, QueryResponse, SchemaResponse, VERSION, VERSION_HEADER_NAME, 4 | }; 5 | use schemars::{schema_for, JsonSchema}; 6 | use serde_derive::{Deserialize, Serialize}; 7 | use std::{env, error::Error, fs, path::PathBuf}; 8 | 9 | #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)] 10 | #[schemars(title = "SchemaRoot")] 11 | struct SchemaRoot { 12 | capabilities_response: CapabilitiesResponse, 13 | schema_response: SchemaResponse, 14 | query_request: QueryRequest, 15 | query_response: QueryResponse, 16 | mutation_request: MutationRequest, 17 | mutation_response: MutationResponse, 18 | explain_response: ExplainResponse, 19 | error_response: ErrorResponse, 20 | validate_response: ValidateResponse, 21 | } 22 | 23 | #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)] 24 | #[schemars(title = "ValidateResponse")] 25 | struct ValidateResponse { 26 | schema: SchemaResponse, 27 | capabilities: CapabilitiesResponse, 28 | resolved_configuration: String, 29 | } 30 | 31 | fn main() -> Result<(), Box> { 32 | let args = env::args().collect::>(); 33 | let (schema_json_path, version_path) = if args.len() >= 2 { 34 | let schema_json_path = [args[1].as_str(), "schema.generated.json"] 35 | .iter() 36 | .collect::(); 37 | let version_path = [args[1].as_str(), "version.generated.ts"] 38 | .iter() 39 | .collect::(); 40 | Ok((schema_json_path, version_path)) 41 | } else { 42 | Err("Schema directory not passed on command line") 43 | }?; 44 | 45 | print!( 46 | "Generating schema JSON to {}...", 47 | schema_json_path.to_str().unwrap() 48 | ); 49 | let schema_json = serde_json::to_string_pretty(&schema_for!(SchemaRoot))?; 50 | fs::write(schema_json_path, schema_json + "\n")?; 51 | println!("done!"); 52 | 53 | print!( 54 | "Generating schema version to {}...", 55 | version_path.to_str().unwrap() 56 | ); 57 | fs::write( 58 | version_path, 59 | format!("export const VERSION = \"{VERSION}\";\nexport const VERSION_HEADER_NAME=\"{VERSION_HEADER_NAME}\"\n"), 60 | )?; 61 | println!("done!"); 62 | 63 | Ok(()) 64 | } 65 | --------------------------------------------------------------------------------