From c4b6b34b7402d39eddd6c0b50f7c6bf8b665aa53 Mon Sep 17 00:00:00 2001 From: Teo Stocco Date: Fri, 24 Feb 2023 22:46:13 +0100 Subject: [PATCH] feat: better logging and fix deployment (#150) * feat: better logging and fix deployment * fix tests * remove comment --------- Co-authored-by: Natoandro --- Cargo.lock | 128 ++++++++---------- dev/Dockerfile | 67 +++++---- dev/Dockerfile.dockerignore | 1 + examples/docker-compose.yml | 4 +- .../migration.sql | 14 +- libs/common/src/{migrations.rs => archive.rs} | 1 - libs/common/src/lib.rs | 2 +- libs/macros/src/lib.rs | 39 ++++-- meta-cli/src/cli/prisma.rs | 14 +- typegate/native/Cargo.toml | 2 +- typegate/native/src/lib.rs | 85 +++++++----- typegate/native/src/runtimes/prisma/engine.rs | 5 +- .../src/runtimes/prisma/engine_import.rs | 28 +++- .../native/src/runtimes/prisma/migration.rs | 11 +- typegate/native/src/runtimes/prisma/mod.rs | 10 +- typegate/native/src/runtimes/temporal.rs | 6 +- typegate/run.sh | 1 - typegate/src/config.ts | 101 +++++--------- typegate/src/engine.ts | 4 +- typegate/src/log.ts | 99 +++++++++++++- typegate/src/main.ts | 17 +-- typegate/src/planner/mod.ts | 6 +- typegate/src/register.ts | 2 - typegate/src/runtimes/deno.ts | 4 +- typegate/src/runtimes/googleapis.ts | 10 +- typegate/src/runtimes/graphql.ts | 7 +- typegate/src/runtimes/prisma.ts | 8 +- typegate/src/runtimes/utils/deno-worker.ts | 1 - typegate/src/typegraph.ts | 7 +- typegate/src/utils.ts | 20 ++- typegate/src/web/auth_debug.ts | 1 - typegate/tests/deno/ts/deno.ts | 2 +- typegate/tests/http/http_content_type_test.ts | 4 - typegate/tests/policies/ts/policies.ts | 1 - .../prisma_migrate/prisma_migrate_test.ts | 2 - typegate/tests/rest/rest_test.ts | 1 - typegate/tests/utils.ts | 4 + website/docs/reference/changelog.mdx | 23 ++++ .../typegate/prisma-migration/mutations.md | 12 +- .../typegate/prisma-migration/queries.md | 4 +- .../typegate/prisma-migration/scalars.md | 7 +- .../reference/typegate/typegate/mutations.md | 2 - .../reference/typegate/typegate/queries.md | 2 - .../reference/typegraph/typegraph/types.md | 24 ++++ whiz.yaml | 4 +- 45 files changed, 475 insertions(+), 322 deletions(-) rename examples/prisma/migrations/blog/blog/{20221207134232_init_db => 20230223181908_init}/migration.sql (100%) rename libs/common/src/{migrations.rs => archive.rs} (99%) diff --git a/Cargo.lock b/Cargo.lock index 1ca96f7388..8b4977e127 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -513,7 +513,7 @@ dependencies = [ [[package]] name = "builtin-psl-connectors" version = "0.1.0" -source = "git+https://github.com/prisma/prisma-engines#b1d5289e9e93ba26d4b023ac7cb3828aa8594668" +source = "git+https://github.com/prisma/prisma-engines#8f13e5fcea8c4ffe14e8a95303c186ea3888f78f" dependencies = [ "connection-string", "either", @@ -669,9 +669,9 @@ dependencies = [ [[package]] name = "clap_lex" -version = "0.3.1" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "783fe232adfca04f90f56201b26d79682d4cd2625e0bc7290b95123afe558ade" +checksum = "350b9cf31731f9957399229e9b2adc51eeabdfbe9d71d9a0552275fd12710d09" dependencies = [ "os_str_bytes", ] @@ -1068,7 +1068,7 @@ checksum = "23d8666cb01533c39dde32bcbab8e227b4ed6679b2c925eba05feabea39508fb" [[package]] name = "datamodel-renderer" version = "0.1.0" -source = "git+https://github.com/prisma/prisma-engines#b1d5289e9e93ba26d4b023ac7cb3828aa8594668" +source = "git+https://github.com/prisma/prisma-engines#8f13e5fcea8c4ffe14e8a95303c186ea3888f78f" dependencies = [ "base64 0.13.1", "once_cell", @@ -1184,7 +1184,7 @@ dependencies = [ [[package]] name = "diagnostics" version = "0.1.0" -source = "git+https://github.com/prisma/prisma-engines#b1d5289e9e93ba26d4b023ac7cb3828aa8594668" +source = "git+https://github.com/prisma/prisma-engines#8f13e5fcea8c4ffe14e8a95303c186ea3888f78f" dependencies = [ "colored", "indoc 1.0.9", @@ -1252,7 +1252,7 @@ checksum = "0688c2a7f92e427f44895cd63841bff7b29f8d7a1648b9e7e07a4a365b2e1257" [[package]] name = "dml" version = "0.1.0" -source = "git+https://github.com/prisma/prisma-engines#b1d5289e9e93ba26d4b023ac7cb3828aa8594668" +source = "git+https://github.com/prisma/prisma-engines#8f13e5fcea8c4ffe14e8a95303c186ea3888f78f" dependencies = [ "chrono", "cuid", @@ -1270,7 +1270,7 @@ dependencies = [ [[package]] name = "dmmf" version = "0.1.0" -source = "git+https://github.com/prisma/prisma-engines#b1d5289e9e93ba26d4b023ac7cb3828aa8594668" +source = "git+https://github.com/prisma/prisma-engines#8f13e5fcea8c4ffe14e8a95303c186ea3888f78f" dependencies = [ "bigdecimal", "indexmap", @@ -2137,7 +2137,7 @@ dependencies = [ "hyper", "native-tls", "tokio", - "tokio-native-tls 0.3.1", + "tokio-native-tls", ] [[package]] @@ -2294,7 +2294,7 @@ dependencies = [ [[package]] name = "introspection-connector" version = "0.1.0" -source = "git+https://github.com/prisma/prisma-engines#b1d5289e9e93ba26d4b023ac7cb3828aa8594668" +source = "git+https://github.com/prisma/prisma-engines#8f13e5fcea8c4ffe14e8a95303c186ea3888f78f" dependencies = [ "anyhow", "async-trait", @@ -2309,7 +2309,7 @@ dependencies = [ [[package]] name = "introspection-core" version = "0.1.0" -source = "git+https://github.com/prisma/prisma-engines#b1d5289e9e93ba26d4b023ac7cb3828aa8594668" +source = "git+https://github.com/prisma/prisma-engines#8f13e5fcea8c4ffe14e8a95303c186ea3888f78f" dependencies = [ "async-trait", "introspection-connector", @@ -2368,9 +2368,9 @@ checksum = "30e22bd8629359895450b59ea7a776c850561b96a3b1d31321c1949d9e6c9146" [[package]] name = "is-macro" -version = "0.2.1" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c068d4c6b922cd6284c609cfa6dec0e41615c9c5a1a4ba729a970d8daba05fb" +checksum = "8a7d079e129b77477a49c5c4f1cfe9ce6c2c909ef52520693e8e811a714c7b20" dependencies = [ "Inflector", "pmutil", @@ -2381,9 +2381,9 @@ dependencies = [ [[package]] name = "is-terminal" -version = "0.4.3" +version = "0.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "22e18b0a45d56fe973d6db23972bf5bc46f988a4a2385deac9cc29572f09daef" +checksum = "21b6b32576413a8e69b90e952e4a026476040d81017b80445deda5f2d3921857" dependencies = [ "hermit-abi 0.3.1", "io-lifetimes", @@ -2418,7 +2418,7 @@ dependencies = [ [[package]] name = "json-rpc-api-build" version = "0.1.0" -source = "git+https://github.com/prisma/prisma-engines#b1d5289e9e93ba26d4b023ac7cb3828aa8594668" +source = "git+https://github.com/prisma/prisma-engines#8f13e5fcea8c4ffe14e8a95303c186ea3888f78f" dependencies = [ "backtrace", "heck 0.3.3", @@ -2429,7 +2429,7 @@ dependencies = [ [[package]] name = "json-rpc-stdio" version = "0.1.0" -source = "git+https://github.com/prisma/prisma-engines#b1d5289e9e93ba26d4b023ac7cb3828aa8594668" +source = "git+https://github.com/prisma/prisma-engines#8f13e5fcea8c4ffe14e8a95303c186ea3888f78f" dependencies = [ "jsonrpc-core", "serde", @@ -2922,7 +2922,7 @@ dependencies = [ [[package]] name = "migration-connector" version = "0.1.0" -source = "git+https://github.com/prisma/prisma-engines#b1d5289e9e93ba26d4b023ac7cb3828aa8594668" +source = "git+https://github.com/prisma/prisma-engines#8f13e5fcea8c4ffe14e8a95303c186ea3888f78f" dependencies = [ "chrono", "enumflags2", @@ -2937,7 +2937,7 @@ dependencies = [ [[package]] name = "migration-core" version = "0.1.0" -source = "git+https://github.com/prisma/prisma-engines#b1d5289e9e93ba26d4b023ac7cb3828aa8594668" +source = "git+https://github.com/prisma/prisma-engines#8f13e5fcea8c4ffe14e8a95303c186ea3888f78f" dependencies = [ "async-trait", "chrono", @@ -3067,7 +3067,7 @@ dependencies = [ [[package]] name = "mongodb-client" version = "0.1.0" -source = "git+https://github.com/prisma/prisma-engines#b1d5289e9e93ba26d4b023ac7cb3828aa8594668" +source = "git+https://github.com/prisma/prisma-engines#8f13e5fcea8c4ffe14e8a95303c186ea3888f78f" dependencies = [ "mongodb", "once_cell", @@ -3078,7 +3078,7 @@ dependencies = [ [[package]] name = "mongodb-introspection-connector" version = "0.1.0" -source = "git+https://github.com/prisma/prisma-engines#b1d5289e9e93ba26d4b023ac7cb3828aa8594668" +source = "git+https://github.com/prisma/prisma-engines#8f13e5fcea8c4ffe14e8a95303c186ea3888f78f" dependencies = [ "async-trait", "convert_case 0.5.0", @@ -3101,7 +3101,7 @@ dependencies = [ [[package]] name = "mongodb-migration-connector" version = "0.1.0" -source = "git+https://github.com/prisma/prisma-engines#b1d5289e9e93ba26d4b023ac7cb3828aa8594668" +source = "git+https://github.com/prisma/prisma-engines#8f13e5fcea8c4ffe14e8a95303c186ea3888f78f" dependencies = [ "enumflags2", "futures", @@ -3119,7 +3119,7 @@ dependencies = [ [[package]] name = "mongodb-query-connector" version = "0.1.0" -source = "git+https://github.com/prisma/prisma-engines#b1d5289e9e93ba26d4b023ac7cb3828aa8594668" +source = "git+https://github.com/prisma/prisma-engines#8f13e5fcea8c4ffe14e8a95303c186ea3888f78f" dependencies = [ "anyhow", "async-trait", @@ -3152,7 +3152,7 @@ dependencies = [ [[package]] name = "mongodb-schema-describer" version = "0.1.0" -source = "git+https://github.com/prisma/prisma-engines#b1d5289e9e93ba26d4b023ac7cb3828aa8594668" +source = "git+https://github.com/prisma/prisma-engines#8f13e5fcea8c4ffe14e8a95303c186ea3888f78f" dependencies = [ "futures", "mongodb", @@ -3191,7 +3191,7 @@ dependencies = [ "socket2", "thiserror", "tokio", - "tokio-native-tls 0.3.1", + "tokio-native-tls", "tokio-util 0.7.7", "twox-hash", "url", @@ -3259,12 +3259,12 @@ dependencies = [ "http", "introspection-connector", "introspection-core", - "lazy_static", "log", "macros", "migration-connector", "migration-core", "mongodb-introspection-connector", + "once_cell", "prisma-models", "query-connector", "query-core", @@ -3706,7 +3706,7 @@ dependencies = [ [[package]] name = "parser-database" version = "0.1.0" -source = "git+https://github.com/prisma/prisma-engines#b1d5289e9e93ba26d4b023ac7cb3828aa8594668" +source = "git+https://github.com/prisma/prisma-engines#8f13e5fcea8c4ffe14e8a95303c186ea3888f78f" dependencies = [ "diagnostics", "either", @@ -3935,18 +3935,18 @@ checksum = "26f6a7b87c2e435a3241addceeeff740ff8b7e76b74c13bf9acb17fa454ea00b" [[package]] name = "postgres-native-tls" version = "0.5.0" -source = "git+https://github.com/pimeys/rust-postgres?branch=pgbouncer-mode#064a6a50427542e2c166e870027735aab3b52e77" +source = "git+https://github.com/pimeys/rust-postgres?branch=pgbouncer-mode#74f0847e9a8ac350c48dd65c4c33e9be5fcf6010" dependencies = [ "native-tls", "tokio", - "tokio-native-tls 0.3.0", + "tokio-native-tls", "tokio-postgres", ] [[package]] name = "postgres-protocol" version = "0.6.4" -source = "git+https://github.com/pimeys/rust-postgres?branch=pgbouncer-mode#064a6a50427542e2c166e870027735aab3b52e77" +source = "git+https://github.com/pimeys/rust-postgres?branch=pgbouncer-mode#74f0847e9a8ac350c48dd65c4c33e9be5fcf6010" dependencies = [ "base64 0.13.1", "byteorder", @@ -3963,7 +3963,7 @@ dependencies = [ [[package]] name = "postgres-types" version = "0.2.4" -source = "git+https://github.com/pimeys/rust-postgres?branch=pgbouncer-mode#064a6a50427542e2c166e870027735aab3b52e77" +source = "git+https://github.com/pimeys/rust-postgres?branch=pgbouncer-mode#74f0847e9a8ac350c48dd65c4c33e9be5fcf6010" dependencies = [ "bit-vec", "bytes", @@ -4016,7 +4016,7 @@ dependencies = [ [[package]] name = "prisma-models" version = "0.0.0" -source = "git+https://github.com/prisma/prisma-engines#b1d5289e9e93ba26d4b023ac7cb3828aa8594668" +source = "git+https://github.com/prisma/prisma-engines#8f13e5fcea8c4ffe14e8a95303c186ea3888f78f" dependencies = [ "bigdecimal", "chrono", @@ -4033,7 +4033,7 @@ dependencies = [ [[package]] name = "prisma-value" version = "0.1.0" -source = "git+https://github.com/prisma/prisma-engines#b1d5289e9e93ba26d4b023ac7cb3828aa8594668" +source = "git+https://github.com/prisma/prisma-engines#8f13e5fcea8c4ffe14e8a95303c186ea3888f78f" dependencies = [ "base64 0.12.3", "bigdecimal", @@ -4122,9 +4122,9 @@ dependencies = [ [[package]] name = "prost" -version = "0.11.6" +version = "0.11.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "21dc42e00223fc37204bd4aa177e69420c604ca4a183209a8f9de30c6d934698" +checksum = "3933d3ac2717077b3d5f42b40f59edfb1fb6a8c14e1c7de0f38075c4bac8e314" dependencies = [ "bytes", "prost-derive", @@ -4132,9 +4132,9 @@ dependencies = [ [[package]] name = "prost-build" -version = "0.11.6" +version = "0.11.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a3f8ad728fb08fe212df3c05169e940fbb6d9d16a877ddde14644a983ba2012e" +checksum = "a24be1d23b4552a012093e1b93697b73d644ae9590e3253d878d0e77d411b614" dependencies = [ "bytes", "heck 0.4.1", @@ -4154,9 +4154,9 @@ dependencies = [ [[package]] name = "prost-derive" -version = "0.11.6" +version = "0.11.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8bda8c0881ea9f722eb9629376db3d0b903b462477c1aafcb0566610ac28ac5d" +checksum = "8e9935362e8369bc3acd874caeeae814295c504c2bdbcde5c024089cf8b4dc12" dependencies = [ "anyhow", "itertools", @@ -4167,11 +4167,10 @@ dependencies = [ [[package]] name = "prost-types" -version = "0.11.6" +version = "0.11.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a5e0526209433e96d83d750dd81a99118edbc55739e7e61a46764fd2ad537788" +checksum = "7de56acd5cc9642cac2a9518d4c8c53818905398fe42d33235859e0d542a7695" dependencies = [ - "bytes", "prost", ] @@ -4224,7 +4223,7 @@ dependencies = [ [[package]] name = "psl" version = "0.1.0" -source = "git+https://github.com/prisma/prisma-engines#b1d5289e9e93ba26d4b023ac7cb3828aa8594668" +source = "git+https://github.com/prisma/prisma-engines#8f13e5fcea8c4ffe14e8a95303c186ea3888f78f" dependencies = [ "builtin-psl-connectors", "psl-core", @@ -4233,7 +4232,7 @@ dependencies = [ [[package]] name = "psl-core" version = "0.1.0" -source = "git+https://github.com/prisma/prisma-engines#b1d5289e9e93ba26d4b023ac7cb3828aa8594668" +source = "git+https://github.com/prisma/prisma-engines#8f13e5fcea8c4ffe14e8a95303c186ea3888f78f" dependencies = [ "bigdecimal", "chrono", @@ -4275,7 +4274,7 @@ dependencies = [ [[package]] name = "quaint" version = "0.2.0-alpha.13" -source = "git+https://github.com/prisma/quaint#2aa9ac0d501a042d281918ff1d22ec904d9de482" +source = "git+https://github.com/prisma/quaint#53c756a67a0ff3f1b6023c64bec9dc9280bdc1cd" dependencies = [ "async-trait", "base64 0.12.3", @@ -4331,7 +4330,7 @@ dependencies = [ [[package]] name = "query-connector" version = "0.1.0" -source = "git+https://github.com/prisma/prisma-engines#b1d5289e9e93ba26d4b023ac7cb3828aa8594668" +source = "git+https://github.com/prisma/prisma-engines#8f13e5fcea8c4ffe14e8a95303c186ea3888f78f" dependencies = [ "anyhow", "async-trait", @@ -4351,7 +4350,7 @@ dependencies = [ [[package]] name = "query-core" version = "0.1.0" -source = "git+https://github.com/prisma/prisma-engines#b1d5289e9e93ba26d4b023ac7cb3828aa8594668" +source = "git+https://github.com/prisma/prisma-engines#8f13e5fcea8c4ffe14e8a95303c186ea3888f78f" dependencies = [ "async-trait", "base64 0.12.3", @@ -4397,7 +4396,7 @@ dependencies = [ [[package]] name = "query-engine-metrics" version = "0.1.0" -source = "git+https://github.com/prisma/prisma-engines#b1d5289e9e93ba26d4b023ac7cb3828aa8594668" +source = "git+https://github.com/prisma/prisma-engines#8f13e5fcea8c4ffe14e8a95303c186ea3888f78f" dependencies = [ "metrics 0.18.1", "metrics-exporter-prometheus", @@ -4619,7 +4618,7 @@ dependencies = [ [[package]] name = "request-handlers" version = "0.1.0" -source = "git+https://github.com/prisma/prisma-engines#b1d5289e9e93ba26d4b023ac7cb3828aa8594668" +source = "git+https://github.com/prisma/prisma-engines#8f13e5fcea8c4ffe14e8a95303c186ea3888f78f" dependencies = [ "bigdecimal", "connection-string", @@ -4667,7 +4666,7 @@ dependencies = [ "serde_json", "serde_urlencoded", "tokio", - "tokio-native-tls 0.3.1", + "tokio-native-tls", "tokio-util 0.7.7", "tower-service", "url", @@ -4970,7 +4969,7 @@ dependencies = [ [[package]] name = "schema" version = "0.1.0" -source = "git+https://github.com/prisma/prisma-engines#b1d5289e9e93ba26d4b023ac7cb3828aa8594668" +source = "git+https://github.com/prisma/prisma-engines#8f13e5fcea8c4ffe14e8a95303c186ea3888f78f" dependencies = [ "once_cell", "prisma-models", @@ -4980,7 +4979,7 @@ dependencies = [ [[package]] name = "schema-ast" version = "0.1.0" -source = "git+https://github.com/prisma/prisma-engines#b1d5289e9e93ba26d4b023ac7cb3828aa8594668" +source = "git+https://github.com/prisma/prisma-engines#8f13e5fcea8c4ffe14e8a95303c186ea3888f78f" dependencies = [ "diagnostics", "pest", @@ -4990,7 +4989,7 @@ dependencies = [ [[package]] name = "schema-builder" version = "0.1.0" -source = "git+https://github.com/prisma/prisma-engines#b1d5289e9e93ba26d4b023ac7cb3828aa8594668" +source = "git+https://github.com/prisma/prisma-engines#8f13e5fcea8c4ffe14e8a95303c186ea3888f78f" dependencies = [ "once_cell", "prisma-models", @@ -5530,12 +5529,12 @@ checksum = "6e63cff320ae2c57904679ba7cb63280a3dc4613885beafb148ee7bf9aa9042d" [[package]] name = "sql-ddl" version = "0.1.0" -source = "git+https://github.com/prisma/prisma-engines#b1d5289e9e93ba26d4b023ac7cb3828aa8594668" +source = "git+https://github.com/prisma/prisma-engines#8f13e5fcea8c4ffe14e8a95303c186ea3888f78f" [[package]] name = "sql-introspection-connector" version = "0.1.0" -source = "git+https://github.com/prisma/prisma-engines#b1d5289e9e93ba26d4b023ac7cb3828aa8594668" +source = "git+https://github.com/prisma/prisma-engines#8f13e5fcea8c4ffe14e8a95303c186ea3888f78f" dependencies = [ "anyhow", "async-trait", @@ -5561,7 +5560,7 @@ dependencies = [ [[package]] name = "sql-migration-connector" version = "0.1.0" -source = "git+https://github.com/prisma/prisma-engines#b1d5289e9e93ba26d4b023ac7cb3828aa8594668" +source = "git+https://github.com/prisma/prisma-engines#8f13e5fcea8c4ffe14e8a95303c186ea3888f78f" dependencies = [ "chrono", "connection-string", @@ -5588,7 +5587,7 @@ dependencies = [ [[package]] name = "sql-query-connector" version = "0.1.0" -source = "git+https://github.com/prisma/prisma-engines#b1d5289e9e93ba26d4b023ac7cb3828aa8594668" +source = "git+https://github.com/prisma/prisma-engines#8f13e5fcea8c4ffe14e8a95303c186ea3888f78f" dependencies = [ "anyhow", "async-trait", @@ -5619,7 +5618,7 @@ dependencies = [ [[package]] name = "sql-schema-describer" version = "0.1.0" -source = "git+https://github.com/prisma/prisma-engines#b1d5289e9e93ba26d4b023ac7cb3828aa8594668" +source = "git+https://github.com/prisma/prisma-engines#8f13e5fcea8c4ffe14e8a95303c186ea3888f78f" dependencies = [ "async-trait", "bigdecimal", @@ -6322,15 +6321,6 @@ dependencies = [ "syn", ] -[[package]] -name = "tokio-native-tls" -version = "0.3.0" -source = "git+https://github.com/pimeys/tls?branch=vendored-openssl#6d0e6fc7a4bf6f290b1033764b47cb3f26d7fceb" -dependencies = [ - "native-tls", - "tokio", -] - [[package]] name = "tokio-native-tls" version = "0.3.1" @@ -6344,7 +6334,7 @@ dependencies = [ [[package]] name = "tokio-postgres" version = "0.7.7" -source = "git+https://github.com/pimeys/rust-postgres?branch=pgbouncer-mode#064a6a50427542e2c166e870027735aab3b52e77" +source = "git+https://github.com/pimeys/rust-postgres?branch=pgbouncer-mode#74f0847e9a8ac350c48dd65c4c33e9be5fcf6010" dependencies = [ "async-trait", "byteorder", @@ -6883,7 +6873,7 @@ checksum = "e8db7427f936968176eaa7cdf81b7f98b980b18495ec28f1b5791ac3bfe3eea9" [[package]] name = "user-facing-error-macros" version = "0.1.0" -source = "git+https://github.com/prisma/prisma-engines#b1d5289e9e93ba26d4b023ac7cb3828aa8594668" +source = "git+https://github.com/prisma/prisma-engines#8f13e5fcea8c4ffe14e8a95303c186ea3888f78f" dependencies = [ "proc-macro2", "quote", @@ -6893,7 +6883,7 @@ dependencies = [ [[package]] name = "user-facing-errors" version = "0.1.0" -source = "git+https://github.com/prisma/prisma-engines#b1d5289e9e93ba26d4b023ac7cb3828aa8594668" +source = "git+https://github.com/prisma/prisma-engines#8f13e5fcea8c4ffe14e8a95303c186ea3888f78f" dependencies = [ "backtrace", "indoc 1.0.9", diff --git a/dev/Dockerfile b/dev/Dockerfile index 7c8a5be860..c318a8e903 100644 --- a/dev/Dockerfile +++ b/dev/Dockerfile @@ -1,74 +1,91 @@ ARG RUST_VERSION=1.67.1 ARG DENO_VERSION=1.30.3 +ARG DISTROLESS_TAG=nonroot FROM lukemathwalker/cargo-chef:latest-rust-${RUST_VERSION} AS base -WORKDIR / +WORKDIR /app # FROM base as plan COPY . . -RUN rm -rf meta-cli \ - && cargo new meta-cli \ - && cargo chef prepare --recipe-path recipe.json + +RUN cargo chef prepare --recipe-path recipe.json + +# + +FROM denoland/deno:bin-${DENO_VERSION} AS deno-bin # FROM base AS builder -ARG DENO_VERSION=1.30.3 ARG DENO_BINDGEN_URL=https://github.com/denoland/deno_bindgen/raw/main/cli.ts ENV DENO_DIR /deno-dir/ ENV DENO_INSTALL /root/.deno ENV PATH "${DENO_INSTALL}/bin:${PATH}" +ENV OUT_DIR target + +COPY --from=deno-bin /deno /bin/deno RUN apt-get update \ - && apt-get install -y \ + && apt-get install -y --no-install-recommends \ protobuf-compiler \ + libprotobuf-dev \ && rm -rf /var/lib/apt/lists/* \ - && curl -fsSL https://deno.land/x/install/install.sh -o install.sh \ - && sh ./install.sh v${DENO_VERSION} \ && deno install -Afq -n deno_bindgen $DENO_BINDGEN_URL -COPY --from=plan /recipe.json recipe.json -RUN cargo chef cook --release --recipe-path recipe.json +COPY --from=plan /app/recipe.json recipe.json + +RUN cargo chef cook --recipe-path recipe.json --release --package native --features deno COPY . . -RUN OUT_DIR=target deno_bindgen --release -- --locked --package native -F deno \ - && mv /target/release/libnative.so . -WORKDIR /typegate -RUN deno cache --config=deno.json --unstable src/main.ts \ - && mkdir tmp +RUN deno_bindgen --release -- --locked --package native --features deno \ + && mv /app/target/release/libnative.so . + +WORKDIR /app/typegate + +RUN deno cache --unstable src/main.ts \ + && mkdir -p tmp # FROM debian:stable-slim AS debian +ARG TINI_VERSION=v0.19.0 + +ADD https://github.com/krallin/tini/releases/download/${TINI_VERSION}/tini /tini + +RUN chmod +x /tini + # -FROM denoland/deno:distroless-${DENO_VERSION} AS runner +FROM gcr.io/distroless/cc-debian11:${DISTROLESS_TAG} + +ENV DENO_DIR /deno-dir/ WORKDIR /app +COPY --from=debian /tini /tini +COPY --from=deno-bin /deno /bin/deno COPY --from=debian /lib/x86_64-linux-gnu/libz.so* /lib/x86_64-linux-gnu/ COPY LICENSE.md . -COPY --from=builder /bindings/bindings.ts /bindings/ -COPY --from=builder /libnative.so /target/release/ -COPY --from=builder /typegate/deno.json ./ -COPY --from=builder /typegate/src ./src +COPY --from=builder /app/bindings/bindings.ts /bindings/ +COPY --from=builder /app/libnative.so /target/release/ +COPY --from=builder /app/typegate/deno.json ./ +COPY --from=builder /app/typegate/src ./src # writeable COPY --from=builder --chown=nonroot:nonroot /deno-dir /deno-dir -COPY --from=builder --chown=nonroot:nonroot /typegate/deno.lock ./ -COPY --from=builder --chown=nonroot:nonroot /typegate/tmp ./ +COPY --from=builder --chown=nonroot:nonroot /app/typegate/deno.lock ./ +COPY --from=builder --chown=nonroot:nonroot /app/typegate/tmp ./ USER nonroot EXPOSE 7890 -ENTRYPOINT ["/tini", "--"] - -CMD ["deno", "run", "--config=deno.json", "--unstable", "--allow-run=hostname", "--allow-env", "--allow-hrtime", "--allow-write", "--allow-ffi", "--allow-read", "--allow-net", "src/main.ts"] +ENTRYPOINT ["/tini", "--", "/bin/deno"] +CMD ["run", "--unstable", "--allow-run=hostname", "--allow-env", "--allow-hrtime", "--allow-write", "--allow-ffi", "--allow-read", "--allow-net", "src/main.ts"] diff --git a/dev/Dockerfile.dockerignore b/dev/Dockerfile.dockerignore index a2b2f3bfe3..fbc111eb16 100644 --- a/dev/Dockerfile.dockerignore +++ b/dev/Dockerfile.dockerignore @@ -3,3 +3,4 @@ website bindings examples **/.* +tmp diff --git a/examples/docker-compose.yml b/examples/docker-compose.yml index 2d044d1a5c..3969395085 100644 --- a/examples/docker-compose.yml +++ b/examples/docker-compose.yml @@ -12,7 +12,7 @@ services: TG_SECRET: "a4lNi0PbEItlFZbus1oeH/+wyIxi9uH6TpL8AIqIaMBNvp7SESmuUBbfUwC0prxhGhZqHw8vMDYZAGMhSZ4fLw==" TG_ADMIN_PASSWORD: password env_file: - - .env.example + - .env.sample depends_on: - redis @@ -28,3 +28,5 @@ services: POSTGRES_DB: db POSTGRES_USER: postgres POSTGRES_PASSWORD: password + ports: + - "5432:5432" diff --git a/examples/prisma/migrations/blog/blog/20221207134232_init_db/migration.sql b/examples/prisma/migrations/blog/blog/20230223181908_init/migration.sql similarity index 100% rename from examples/prisma/migrations/blog/blog/20221207134232_init_db/migration.sql rename to examples/prisma/migrations/blog/blog/20230223181908_init/migration.sql index 78815a1a8f..7c48373909 100644 --- a/examples/prisma/migrations/blog/blog/20221207134232_init_db/migration.sql +++ b/examples/prisma/migrations/blog/blog/20230223181908_init/migration.sql @@ -1,18 +1,18 @@ -- CreateTable -CREATE TABLE "Post" ( +CREATE TABLE "User" ( "id" INTEGER NOT NULL, - "content" TEXT NOT NULL, - "authorId" INTEGER NOT NULL, + "name" TEXT NOT NULL, - CONSTRAINT "Post_pkey" PRIMARY KEY ("id") + CONSTRAINT "User_pkey" PRIMARY KEY ("id") ); -- CreateTable -CREATE TABLE "User" ( +CREATE TABLE "Post" ( "id" INTEGER NOT NULL, - "name" TEXT NOT NULL, + "content" TEXT NOT NULL, + "authorId" INTEGER NOT NULL, - CONSTRAINT "User_pkey" PRIMARY KEY ("id") + CONSTRAINT "Post_pkey" PRIMARY KEY ("id") ); -- CreateTable diff --git a/libs/common/src/migrations.rs b/libs/common/src/archive.rs similarity index 99% rename from libs/common/src/migrations.rs rename to libs/common/src/archive.rs index 548fab27ce..e22a1db3ba 100644 --- a/libs/common/src/migrations.rs +++ b/libs/common/src/archive.rs @@ -24,6 +24,5 @@ pub fn archive>(folder: P) -> Result { let mut tar = tar::Builder::new(encoder); tar.append_dir_all(".", &folder)?; let bytes = tar.into_inner()?.finish()?; - Ok(STANDARD.encode(bytes)) } diff --git a/libs/common/src/lib.rs b/libs/common/src/lib.rs index b37a5bc469..3ba5b1aa33 100644 --- a/libs/common/src/lib.rs +++ b/libs/common/src/lib.rs @@ -1,6 +1,6 @@ // Copyright Metatype OÜ under the Elastic License 2.0 (ELv2). See LICENSE.md for usage. -pub mod migrations; +pub mod archive; pub mod typegraph; pub fn get_version() -> String { diff --git a/libs/macros/src/lib.rs b/libs/macros/src/lib.rs index b2adfcc068..517e7bbe67 100644 --- a/libs/macros/src/lib.rs +++ b/libs/macros/src/lib.rs @@ -4,21 +4,38 @@ use proc_macro::TokenStream; use quote::quote; use syn::{parse, DeriveInput, ItemFn}; -#[proc_macro_attribute] -pub fn deno(_attr: TokenStream, input: TokenStream) -> TokenStream { +fn deno_attr(input: TokenStream, non_blocking: bool) -> TokenStream { if let Ok(input) = parse::(input.clone()) { + // fn + let deno = if non_blocking { + quote! { deno_bindgen::deno_bindgen(non_blocking) } + } else { + quote! { deno_bindgen::deno_bindgen } + }; let output = quote! { - #[cfg_attr(feature = "deno", deno_bindgen::deno_bindgen(non_blocking))] + #[cfg_attr(feature = "deno", #deno)] #[cfg_attr(not(feature = "deno"), allow(dead_code))] #input }; - return TokenStream::from(output); + TokenStream::from(output) + } else { + // struct + let input = parse::(input).unwrap(); + let output = quote! { + #[derive(Debug)] + #[deno_bindgen::deno_bindgen] + #input + }; + TokenStream::from(output) } - let input = parse::(input).unwrap(); - let output = quote! { - #[derive(Debug)] - #[deno_bindgen::deno_bindgen] - #input - }; - TokenStream::from(output) +} + +#[proc_macro_attribute] +pub fn deno(_attr: TokenStream, input: TokenStream) -> TokenStream { + deno_attr(input, true) +} + +#[proc_macro_attribute] +pub fn deno_sync(_attr: TokenStream, input: TokenStream) -> TokenStream { + deno_attr(input, false) } diff --git a/meta-cli/src/cli/prisma.rs b/meta-cli/src/cli/prisma.rs index 21bd6d1ca0..b2fa0a4037 100644 --- a/meta-cli/src/cli/prisma.rs +++ b/meta-cli/src/cli/prisma.rs @@ -10,10 +10,9 @@ use crate::{ }, }; use anyhow::{bail, Context, Result}; -use base64::{engine::general_purpose::STANDARD, Engine}; use clap::{Parser, Subcommand}; use colored::Colorize; -use flate2::{write::GzEncoder, Compression}; +use common::archive::archive; use indoc::indoc; use prisma_models::psl; use question::{Answer, Question}; @@ -156,12 +155,7 @@ impl Action for Deploy { .join(&self.typegraph) .join(&self.runtime); - let enc = GzEncoder::new(Vec::new(), Compression::default()); - let mut tar = tar::Builder::new(enc); - tar.append_dir_all("migrations", migrations_path.as_path())?; - let enc = tar.into_inner()?; - let migrations = enc.finish()?; - let migrations = STANDARD.encode(migrations); + let migrations = archive(migrations_path.as_path())?; let node_config = config.node("deploy"); let node_url = node_config.url(self.gate.clone()); @@ -351,7 +345,7 @@ impl PrismaMigrate { runtime.as_deref(), )?; let migrations = if let Some(path) = migrations_path { - Some(common::migrations::archive(path)?) + Some(common::archive::archive(path)?) } else { None }; @@ -375,7 +369,7 @@ impl PrismaMigrate { .as_ref() .expect("migrations should have been updated"); // migrations should have been set - common::migrations::unpack(migrations_path, self.migrations)?; + common::archive::unpack(migrations_path, self.migrations)?; Ok(()) } diff --git a/typegate/native/Cargo.toml b/typegate/native/Cargo.toml index 624a4a6ecd..03d88ab84b 100644 --- a/typegate/native/Cargo.toml +++ b/typegate/native/Cargo.toml @@ -32,7 +32,6 @@ connection-string = "0.1.14" url = "2.3.1" thiserror = "1.0.38" tokio = { version = "1.25.0", features = ["full"] } -lazy_static = "1.4.0" log = "0.4.17" env_logger = "0.10.0" serde_json = "1.0.93" @@ -46,3 +45,4 @@ rust-s3 = { git = "https://github.com/zifeo/rust-s3", branch = "order" } http = "0.2.9" uuid = { version = "1.3.0", features = ["v4"] } envconfig = "0.10.0" +once_cell = "1.17.1" diff --git a/typegate/native/src/lib.rs b/typegate/native/src/lib.rs index 9f6226795e..947e35b24e 100644 --- a/typegate/native/src/lib.rs +++ b/typegate/native/src/lib.rs @@ -4,54 +4,67 @@ mod config; mod runtimes; mod typegraph; +use config::Config; use envconfig::Envconfig; -use lazy_static::lazy_static; -use log::info; -use macros::deno; +use log::{error, info}; +use macros::deno_sync; +use once_cell::sync::Lazy; +use sentry::ClientInitGuard; +use std::io::Write; use std::{borrow::Cow, env, fs, panic, path::PathBuf}; use tokio::runtime::Runtime; -lazy_static! { - pub static ref CONFIG: config::Config = config::Config::init_from_env().unwrap(); - static ref RT: Runtime = { - info!("Runtime created"); - Runtime::new().unwrap() +static RT: Lazy = Lazy::new(|| Runtime::new().expect("failed to create Tokio runtime")); +static CONFIG: Lazy = + Lazy::new(|| Config::init_from_env().expect("failed to parse config")); +static TMP_DIR: Lazy = Lazy::new(|| { + let path = env::current_dir().expect("no current dir").join("tmp"); + fs::create_dir_all(&path).expect("failed to create tmp dir"); + path +}); +static SENTRY_GUARD: Lazy = Lazy::new(|| { + let env = if CONFIG.debug { + "development".to_string() + } else { + "production".to_string() }; - static ref SENTRY_GUARD: sentry::ClientInitGuard = { - sentry::init(( - CONFIG.sentry_dsn.clone(), - sentry::ClientOptions { - release: Some(Cow::from(common::get_version())), - environment: Some(Cow::from(if CONFIG.debug { - "development".to_string() - } else { - "production".to_string() - })), - sample_rate: CONFIG.sentry_sample_rate, - traces_sample_rate: CONFIG.sentry_traces_sample_rate, - ..Default::default() - }, - )) - }; - pub static ref TMP_DIR: PathBuf = { - let dir = env::current_dir().expect("no current dir").join("tmp"); - fs::create_dir_all(&dir).expect("failed to create tmp dir"); - dir - }; -} + sentry::init(( + CONFIG.sentry_dsn.clone(), + sentry::ClientOptions { + release: Some(Cow::from(common::get_version())), + environment: Some(Cow::from(env)), + sample_rate: CONFIG.sentry_sample_rate, + traces_sample_rate: CONFIG.sentry_traces_sample_rate, + ..Default::default() + }, + )) +}); -#[deno] -fn init() { - env_logger::init(); - info!("init"); +#[deno_sync] +fn init_native() { + SENTRY_GUARD.is_enabled(); + env_logger::builder() + .format_timestamp_millis() + .format(|buf, record| { + writeln!( + buf, + "{} {: <5} {: <12} {}", + buf.timestamp_millis(), + record.level(), + record.target(), + record.args() + ) + }) + .init(); + info!("init native"); let default_panic = std::panic::take_hook(); panic::set_hook(Box::new(move |panic_info| { - println!("Panic: {}", panic_info); + error!("Panic: {}", panic_info); default_panic(panic_info); })); } -#[deno] +#[deno_sync] fn get_version() -> String { common::get_version() } diff --git a/typegate/native/src/runtimes/prisma/engine.rs b/typegate/native/src/runtimes/prisma/engine.rs index 8108b3b7e2..010fbee03f 100644 --- a/typegate/native/src/runtimes/prisma/engine.rs +++ b/typegate/native/src/runtimes/prisma/engine.rs @@ -3,6 +3,7 @@ use std::{collections::BTreeMap, path::PathBuf, str::FromStr}; use anyhow::{Context, Result}; +use request_handlers::GraphqlBody; pub async fn register_engine(datamodel: String, tg_name: String) -> Result { let conf = super::engine_import::ConstructorOptions { @@ -23,11 +24,11 @@ pub async fn register_engine(datamodel: String, tg_name: String) -> Result Result { - let body = serde_json::from_value(query)?; + let body = serde_json::from_value::(query)?; let engine = super::ENGINES .get(&engine_key) .with_context(|| format!("Cound not find engine '{engine_key}"))?; - let res = engine.query(body, None).await?; + let res = engine.query(body.into(), None).await?; serde_json::to_string(&res) .context("Error while deserializing GraphQL response from the prisma engine") } diff --git a/typegate/native/src/runtimes/prisma/engine_import.rs b/typegate/native/src/runtimes/prisma/engine_import.rs index 88c1a17e5a..9e08603093 100644 --- a/typegate/native/src/runtimes/prisma/engine_import.rs +++ b/typegate/native/src/runtimes/prisma/engine_import.rs @@ -21,9 +21,10 @@ use prisma_models::psl; use psl::diagnostics::Diagnostics; use query_connector::error::ConnectorError; use query_core::executor::TransactionOptions; +use query_core::protocol::EngineProtocol; use query_core::CoreError; use query_core::{executor, schema::QuerySchema, schema_builder, QueryExecutor, TxId}; -use request_handlers::{GraphQlBody, GraphQlHandler, PrismaResponse}; +use request_handlers::{PrismaResponse, RequestBody, RequestHandler}; use serde::{Deserialize, Serialize}; use serde_json::json; use std::{ @@ -76,6 +77,7 @@ pub struct EngineBuilder { schema: Arc, config_dir: PathBuf, env: HashMap, + engine_protocol: EngineProtocol, } /// Internal structure for querying and reconnecting with the engine. @@ -85,6 +87,7 @@ pub struct ConnectedEngine { executor: Executor, config_dir: PathBuf, env: HashMap, + engine_protocol: EngineProtocol, } /// Returned from the `serverInfo` method in javascript. @@ -97,15 +100,17 @@ pub struct ServerInfo { } impl ConnectedEngine { - /// The schema AST for Query Engine core. pub fn query_schema(&self) -> &Arc { &self.query_schema } - /// The query executor. pub fn executor(&self) -> &(dyn QueryExecutor + Send + Sync) { &*self.executor } + + pub fn engine_protocol(&self) -> EngineProtocol { + self.engine_protocol + } } /// Parameters defining the construction of an engine. @@ -165,6 +170,7 @@ impl QueryEngine { schema: Arc::new(schema), config_dir, env, + engine_protocol: EngineProtocol::Graphql, }; Ok(Self { @@ -208,6 +214,7 @@ impl QueryEngine { executor, config_dir: builder.config_dir.clone(), env: builder.env.clone(), + engine_protocol: builder.engine_protocol, }) } .await?; @@ -226,6 +233,7 @@ impl QueryEngine { schema: engine.schema.clone(), config_dir: engine.config_dir.clone(), env: engine.env.clone(), + engine_protocol: engine.engine_protocol(), }; *inner = Inner::Builder(builder); @@ -234,10 +242,14 @@ impl QueryEngine { } /// If connected, sends a query to the core and returns the response. - pub async fn query(&self, query: GraphQlBody, tx_id: Option) -> Result { + pub async fn query(&self, query: RequestBody, tx_id: Option) -> Result { match *self.inner.read().await { Inner::Connected(ref engine) => { - let handler = GraphQlHandler::new(engine.executor(), engine.query_schema()); + let handler = RequestHandler::new( + engine.executor(), + engine.query_schema(), + engine.engine_protocol(), + ); Ok(handler.handle(query, tx_id.map(TxId::from), None).await) } Inner::Builder(_) => Err(ApiError::NotConnected), @@ -252,7 +264,11 @@ impl QueryEngine { let tx_opts: TransactionOptions = serde_json::from_str(&input)?; match engine .executor() - .start_tx(engine.query_schema().clone(), tx_opts) + .start_tx( + engine.query_schema().clone(), + engine.engine_protocol(), + tx_opts, + ) .await { Ok(tx_id) => Ok(json!({ "id": tx_id.to_string() }).to_string()), diff --git a/typegate/native/src/runtimes/prisma/migration.rs b/typegate/native/src/runtimes/prisma/migration.rs index 490418893b..9f5e681ca2 100644 --- a/typegate/native/src/runtimes/prisma/migration.rs +++ b/typegate/native/src/runtimes/prisma/migration.rs @@ -5,6 +5,7 @@ use anyhow::{anyhow, Context, Result}; use convert_case::{Case, Casing}; +use log::info; use migration_core::json_rpc::types::{ ApplyMigrationsInput, CreateMigrationInput, DiffParams, DiffTarget, EvaluateDataLossInput, ListMigrationDirectoriesInput, SchemaContainer, @@ -180,6 +181,12 @@ pub async fn deploy( .await?; let migration_count = res.migrations.len(); + info!( + "migrations in {}: {:?}", + migrations.to_string(), + res.migrations + ); + let res = api .apply_migrations(ApplyMigrationsInput { migrations_directory_path: migrations.to_string(), @@ -197,12 +204,12 @@ struct MigrationsFolder { impl MigrationsFolder { pub fn from(serialized: Option) -> Result { let tempdir = tempdir_in(TMP_DIR.as_path())?; - common::migrations::unpack(&tempdir, serialized)?; + common::archive::unpack(&tempdir, serialized)?; Ok(Self { dir: tempdir }) } fn serialize(self) -> Result { - common::migrations::archive(self) + common::archive::archive(self) } } diff --git a/typegate/native/src/runtimes/prisma/mod.rs b/typegate/native/src/runtimes/prisma/mod.rs index 69f8ac4b6c..c8dd6bf1d8 100644 --- a/typegate/native/src/runtimes/prisma/mod.rs +++ b/typegate/native/src/runtimes/prisma/mod.rs @@ -6,16 +6,14 @@ mod engine; mod engine_import; mod introspection; use introspection::Introspection; +use once_cell::sync::Lazy; mod migration; use crate::RT; use dashmap::DashMap; -use lazy_static::lazy_static; mod utils; use macros::deno; -lazy_static! { - static ref ENGINES: DashMap = DashMap::new(); -} +static ENGINES: Lazy> = Lazy::new(DashMap::new); // introspection @@ -256,7 +254,7 @@ enum UnpackResult { #[deno] fn unpack(input: UnpackInp) -> UnpackResult { - match common::migrations::unpack(&input.dest, Some(input.migrations)) { + match common::archive::unpack(&input.dest, Some(input.migrations)) { Ok(_) => UnpackResult::Ok, Err(e) => UnpackResult::Err { message: e.to_string(), @@ -277,7 +275,7 @@ enum ArchiveResult { #[deno] fn archive(input: ArchiveInp) -> ArchiveResult { - match common::migrations::archive(input.path) { + match common::archive::archive(input.path) { Ok(b) => ArchiveResult::Ok { base64: b }, Err(e) => ArchiveResult::Err { message: e.to_string(), diff --git a/typegate/native/src/runtimes/temporal.rs b/typegate/native/src/runtimes/temporal.rs index 6d45d5acbe..f92b41f775 100644 --- a/typegate/native/src/runtimes/temporal.rs +++ b/typegate/native/src/runtimes/temporal.rs @@ -3,8 +3,8 @@ use crate::RT; use anyhow::Context; use dashmap::DashMap; -use lazy_static::lazy_static; use macros::deno; +use once_cell::sync::Lazy; use std::collections::HashMap; use std::str::FromStr; use temporal_client::{Client, ClientOptionsBuilder, RetryClient}; @@ -13,9 +13,7 @@ use temporal_sdk_core_protos::temporal::api::common::v1::{Payload, Payloads}; use url::Url; -lazy_static! { - static ref CLIENTS: DashMap> = DashMap::new(); -} +static CLIENTS: Lazy>> = Lazy::new(DashMap::new); #[deno] struct TemporalRegisterInput { diff --git a/typegate/run.sh b/typegate/run.sh index bd3a637959..40c1059df2 100755 --- a/typegate/run.sh +++ b/typegate/run.sh @@ -7,7 +7,6 @@ SCRIPT_PATH=$(dirname $(realpath -s $0)) # remember to also update dev/Dockerfile cd ${SCRIPT_PATH} && \ exec deno run \ - --config=deno.json \ --unstable \ --allow-run=hostname \ --allow-env \ diff --git a/typegate/src/config.ts b/typegate/src/config.ts index c044cfd758..18b7d3876f 100644 --- a/typegate/src/config.ts +++ b/typegate/src/config.ts @@ -1,60 +1,21 @@ // Copyright Metatype OÜ under the Elastic License 2.0 (ELv2). See LICENSE.md for usage. import { z } from "zod"; -import { getLogger } from "./log.ts"; -import { deepMerge } from "std/collections/deep_merge.ts"; +import { configOrExit } from "./utils.ts"; import { mapKeys } from "std/collections/map_keys.ts"; + import * as base64 from "std/encoding/base64.ts"; import { parse } from "std/flags/mod.ts"; -import { get_version } from "native"; import { RedisConnectOptions } from "redis"; -async function getHostname() { - try { - const cmd = Deno.run({ cmd: ["hostname"], stdout: "piped" }); - const stdout = await cmd.output(); - cmd.close(); - return new TextDecoder().decode(stdout).trim(); - } catch (e) { - console.debug(`cannot use hostname binary (${e.message}), fallback to env`); - return Deno.env.get("HOSTNAME") ?? "UNKNOWN_HOSTNAME"; - } -} - -const zbooleanstring = z.preprocess( - (a: unknown) => z.coerce.string().parse(a) === "true", - z.boolean(), -); - -const defaults: Record = { - debug: "false", - packaged: "true", - hostname: await getHostname(), - cookies_max_age_sec: 3600 * 24 * 30, - cookies_min_refresh_sec: 60 * 5, - sentry_sample_rate: 1, - sentry_traces_sample_rate: 1, - version: await get_version(), - trust_proxy: false, - trust_header_ip: "X-Forwarded-For", - tg_port: "7890", -}; +// This import ensure log loads before config, important for the version hydration +import { zBooleanString } from "./log.ts"; -const schema = z.object({ - debug: zbooleanstring, - // log_level is accessed directly through Deno.env to avoid leaking config to workers - // config.log_level is only to validate the types and delete right after - log_level: z.enum([ - "NOTSET", - "DEBUG", - "INFO", - "WARNING", - "ERROR", - "CRITICAL", - ]).optional(), +const schema = { + debug: zBooleanString, // To be set to false when running from source. // If false, auto reload system typegraphs on change. Default: to true. - packaged: zbooleanstring, + packaged: zBooleanString, hostname: z.string(), redis_url: z .string() @@ -81,32 +42,40 @@ const schema = z.object({ }), cookies_max_age_sec: z.coerce.number().positive().min(30), cookies_min_refresh_sec: z.coerce.number().positive().min(60), - sentry_dsn: z.string().optional(), - sentry_sample_rate: z.coerce.number().positive().min(0).max(1), - sentry_traces_sample_rate: z.coerce.number().positive().min(0).max(1), version: z.string(), - trust_proxy: zbooleanstring, + trust_proxy: zBooleanString, trust_header_ip: z.string(), request_log: z.string().optional(), -}); - -const sources = [ - defaults, - mapKeys(Deno.env.toObject(), (k: string) => k.toLowerCase()), - parse(Deno.args) as Record, -]; - -const parsing = await schema.safeParse( - sources.reduce((a, b) => deepMerge(a, b), {}), -); +}; -if (!parsing.success) { - getLogger().error(parsing.error); - Deno.exit(1); +async function getHostname() { + try { + const cmd = Deno.run({ cmd: ["hostname"], stdout: "piped" }); + const stdout = await cmd.output(); + cmd.close(); + return new TextDecoder().decode(stdout).trim(); + } catch (e) { + console.debug(`cannot use hostname binary (${e.message}), fallback to env`); + return Deno.env.get("HOSTNAME") ?? "UNKNOWN_HOSTNAME"; + } } -const { data: config } = parsing; -delete config.log_level; +const config = await configOrExit([ + { + debug: "false", + packaged: "true", + hostname: await getHostname(), + cookies_max_age_sec: 3600 * 24 * 30, + cookies_min_refresh_sec: 60 * 5, + sentry_sample_rate: 1, + sentry_traces_sample_rate: 1, + trust_proxy: false, + trust_header_ip: "X-Forwarded-For", + tg_port: "7890", + }, + mapKeys(Deno.env.toObject(), (k: string) => k.toLowerCase()), + parse(Deno.args) as Record, +], schema); export default config; diff --git a/typegate/src/engine.ts b/typegate/src/engine.ts index 3e28e3b1a3..b23dcac43e 100644 --- a/typegate/src/engine.ts +++ b/typegate/src/engine.ts @@ -163,13 +163,13 @@ const authorize = async ( args: Record, ): Promise => { if (Object.values(checks).length < 1) { - // null = inherit + // null means inherited return null; } const [check, ...nextChecks] = checks; const decision = await policiesRegistry[check](args); - verbose && console.log(stageId, decision); + // verbose && console.log(stageId, decision); if (decision === null) { // next policy diff --git a/typegate/src/log.ts b/typegate/src/log.ts index 6adb045af0..0ca921fa39 100644 --- a/typegate/src/log.ts +++ b/typegate/src/log.ts @@ -2,16 +2,105 @@ import { handlers, LevelName, Logger } from "std/log/mod.ts"; import { basename, extname, fromFileUrl } from "std/path/mod.ts"; +import { z } from "zod"; -const console = new handlers.ConsoleHandler( - Deno.env.get("LOG_LEVEL") as LevelName ?? "INFO", +import * as Sentry from "sentry"; +import { configOrExit } from "./utils.ts"; + +if (!Deno.env.has("VERSION")) { + // set version for config and workers, only running in main + const { get_version } = await import("native"); + Deno.env.set("VERSION", get_version()); +} + +export const zBooleanString = z.preprocess( + (a: unknown) => z.coerce.string().parse(a) === "true", + z.boolean(), +); + +// Those envs are split from the config as only a subset of them are shared with the workers +const schema = { + debug: zBooleanString, + log_level: z.enum([ + "NOTSET", + "DEBUG", + "INFO", + "WARNING", + "ERROR", + "CRITICAL", + ]).optional(), + rust_log: z.string().optional(), + sentry_dsn: z.string().optional(), + sentry_sample_rate: z.coerce.number().positive().min(0).max(1), + sentry_traces_sample_rate: z.coerce.number().positive().min(0).max(1), + version: z.string(), +}; + +export const envSharedWithWorkers = Object.keys(schema).map((k) => + k.toUpperCase() +); + +const config = await configOrExit([ + { + sentry_sample_rate: 1, + sentry_traces_sample_rate: 1, + log_level: "INFO", + }, + Object.fromEntries( + envSharedWithWorkers + .map((k) => [k.toLocaleLowerCase(), Deno.env.get(k)]) + .filter(([_, v]) => v !== undefined), + ), +], schema); + +if (config.sentry_dsn) { + Sentry.init({ + dsn: config.sentry_dsn, + release: config.version, + environment: config.debug ? "development" : "production", + sampleRate: config.sentry_sample_rate, + tracesSampleRate: config.sentry_traces_sample_rate, + }); +} + +// set rust log level is not explicit set +if (!config.rust_log) { + const set = (level: string) => Deno.env.set("RUST_LOG", level); + switch (config.log_level) { + case "NOTSET": + set("off"); + break; + case "DEBUG": + set("debug"); + break; + case "WARNING": + set("warn"); + break; + case "ERROR": + case "CRITICAL": + set("error"); + break; + case "INFO": + default: + set("info"); + break; + } +} + +const consoleHandler = new handlers.ConsoleHandler( + config.log_level as LevelName, { - formatter: "{levelName} [{loggerName}] {msg}", + formatter: (log) => + `${log.datetime.toISOString()} ${log.levelName.padEnd(5)} ${ + log.loggerName.padEnd(12) + } ${log.msg}`, }, ); const loggers = new Map(); -const defaultLogger = new Logger("default", "NOTSET", { handlers: [console] }); +const defaultLogger = new Logger("default", "NOTSET", { + handlers: [consoleHandler], +}); export function getLogger( name: ImportMeta | string | null = null, @@ -26,7 +115,7 @@ export function getLogger( } let logger = loggers.get(name); if (!logger) { - logger = new Logger(name, levelName, { handlers: [console] }); + logger = new Logger(name, levelName, { handlers: [consoleHandler] }); loggers.set(name, logger); } return logger; diff --git a/typegate/src/main.ts b/typegate/src/main.ts index a4f7008f7f..44aec638ad 100644 --- a/typegate/src/main.ts +++ b/typegate/src/main.ts @@ -1,27 +1,18 @@ // Copyright Metatype OÜ under the Elastic License 2.0 (ELv2). See LICENSE.md for usage. import { serve } from "std/http/server.ts"; -import * as Sentry from "sentry"; -import { init } from "native"; +import { init_native } from "native"; import { ReplicatedRegister } from "./register.ts"; import config, { redisConfig } from "./config.ts"; -import { getLogger } from "./log.ts"; import { typegate } from "./typegate.ts"; import { RedisRateLimiter } from "./rate_limiter.ts"; import { SystemTypegraph } from "./system_typegraphs.ts"; -if (config.sentry_dsn) { - Sentry.init({ - dsn: config.sentry_dsn, - release: config.version, - environment: config.debug ? "development" : "production", - sampleRate: config.sentry_sample_rate, - tracesSampleRate: config.sentry_traces_sample_rate, - }); -} +import { getLogger } from "./log.ts"; -init(); +// init rust native libs +init_native(); const register = await ReplicatedRegister.init(redisConfig); register.startSync(); diff --git a/typegate/src/planner/mod.ts b/typegate/src/planner/mod.ts index 59884ea709..116b83069f 100644 --- a/typegate/src/planner/mod.ts +++ b/typegate/src/planner/mod.ts @@ -19,6 +19,9 @@ import { ArgumentCollector, ComputeArg } from "./args.ts"; import { FromVars } from "../runtimes/graphql.ts"; import { mapValues } from "std/collections/map_values.ts"; import { filterValues } from "std/collections/filter_values.ts"; +import { getLogger } from "../log.ts"; + +const logger = getLogger(import.meta); interface Node { name: string; @@ -111,9 +114,8 @@ export class Planner { : []; const props = (typ.type === Type.OBJECT && typ.properties) || {}; - // TODO: use logger this.verbose && - console.log( + logger.debug( this.tg.root.title, name, args.map((n) => n.name?.value), diff --git a/typegate/src/register.ts b/typegate/src/register.ts index 5f7d36c1cf..c836eaad77 100644 --- a/typegate/src/register.ts +++ b/typegate/src/register.ts @@ -5,8 +5,6 @@ import { RedisReplicatedMap } from "./replicated_map.ts"; import { RedisConnectOptions } from "redis"; import { SystemTypegraph } from "./system_typegraphs.ts"; -console.log("init replicated map"); - export abstract class Register { abstract set(payload: string): Promise; diff --git a/typegate/src/runtimes/deno.ts b/typegate/src/runtimes/deno.ts index dcc6d3bc6a..7e57dee34a 100644 --- a/typegate/src/runtimes/deno.ts +++ b/typegate/src/runtimes/deno.ts @@ -5,7 +5,7 @@ import * as Sentry from "sentry"; import { ComputeStage } from "../engine.ts"; import type { TypeGraph, TypeGraphDS, TypeMaterializer } from "../typegraph.ts"; import { Runtime } from "./Runtime.ts"; -import { getLogger } from "../log.ts"; +import { envSharedWithWorkers, getLogger } from "../log.ts"; import { FuncTask, ImportFuncTask, Task, TaskContext } from "./utils/codes.ts"; import { ensure, envOrFail } from "../utils.ts"; import { Resolver, RuntimeInitParams } from "../types.ts"; @@ -19,7 +19,7 @@ const localDir = dirname(fromFileUrl(import.meta.url)); const workerFile = toFileUrl(resolve(localDir, "utils/deno-worker.ts")); const defaultPermissions = { - env: ["LOG_LEVEL"], + env: envSharedWithWorkers, hrtime: false, net: false, ffi: false, diff --git a/typegate/src/runtimes/googleapis.ts b/typegate/src/runtimes/googleapis.ts index 0541293632..52341934a0 100644 --- a/typegate/src/runtimes/googleapis.ts +++ b/typegate/src/runtimes/googleapis.ts @@ -4,6 +4,9 @@ import { ComputeStage } from "../engine.ts"; import { Runtime } from "./Runtime.ts"; import { ObjectNode } from "../type_node.ts"; import { Resolver, RuntimeInitParams } from "../types.ts"; +import { getLogger } from "../log.ts"; + +const logger = getLogger(import.meta); export class GoogleapisRuntime extends Runtime { constructor() { @@ -39,10 +42,10 @@ export class GoogleapisRuntime extends Runtime { }, }; - console.log(input, opts); + logger.debug(input, opts); const ret = await fetch(input, opts); const res = await ret.json(); - console.log(JSON.stringify(res)); + logger.debug(JSON.stringify(res)); return res; }; } @@ -88,9 +91,6 @@ export class GoogleapisRuntime extends Runtime { stagesMat.push(queryStage); - console.log("===", stage.props); - console.log(sameRuntime); - for (const field of sameRuntime) { if (field.props.parent?.id() === stage.props.parent?.id()) { throw Error("Not implemented."); diff --git a/typegate/src/runtimes/graphql.ts b/typegate/src/runtimes/graphql.ts index ff00168ead..096ee04244 100644 --- a/typegate/src/runtimes/graphql.ts +++ b/typegate/src/runtimes/graphql.ts @@ -9,6 +9,9 @@ import { Kind } from "graphql"; import { OperationDefinitionNode, OperationTypeNode } from "graphql/ast"; import * as ForwardVars from "./utils/graphql_forward_vars.ts"; import * as InlineVars from "./utils/graphql_inline_vars.ts"; +import { getLogger } from "../log.ts"; + +const logger = getLogger(import.meta); export interface FromVars { (variables: Record): T; @@ -43,7 +46,7 @@ export class GraphQLRuntime extends Runtime { // TODO: filter variables - only include forwared variables const ret = await gq(this.endpoint, q, variables); if (ret.errors) { - console.error(ret.errors); + logger.error(ret.errors); throw new Error(`From remote graphql: ${ret.errors[0].message}`); } return path.reduce((r, field) => r[field], ret.data); @@ -112,7 +115,7 @@ export class GraphQLRuntime extends Runtime { })(); verbose && - console.log( + logger.debug( "remote graphql:", typeof query === "string" ? query : " with inlined vars", ); diff --git a/typegate/src/runtimes/prisma.ts b/typegate/src/runtimes/prisma.ts index ea0f449a1b..408194dcdb 100644 --- a/typegate/src/runtimes/prisma.ts +++ b/typegate/src/runtimes/prisma.ts @@ -11,6 +11,9 @@ import * as ast from "graphql/ast"; import { ComputeArg } from "../planner/args.ts"; import { buildRawQuery } from "./utils/graphql_inline_vars.ts"; import { Materializer } from "../types/typegraph.ts"; +import { getLogger } from "../log.ts"; + +const logger = getLogger(import.meta); export const makeDatasource = (uri: string) => { const scheme = new URL(uri).protocol.slice(0, -1); @@ -54,7 +57,6 @@ export class PrismaRuntime extends GraphQLRuntime { args.connection_string_secret as string, )); const schema = `${datasource}${args.datamodel}`; - //console.log(schema); const instance = new PrismaRuntime(schema); await instance.registerEngine(typegraph.types[0].title); return instance; @@ -100,7 +102,7 @@ export class PrismaRuntime extends GraphQLRuntime { return async ({ _: { variables } }) => { const startTime = performance.now(); const q = typeof query === "function" ? query(variables) : query; - console.log(`remote graphql: ${q}`); + logger.debug(`remote graphql: ${q}`); const ret = nativeResult( await native.prisma_query({ @@ -113,7 +115,7 @@ export class PrismaRuntime extends GraphQLRuntime { }), ); const endTime = performance.now(); - console.log(`queried prisma in ${(endTime - startTime).toFixed(2)}ms`); + logger.debug(`queried prisma in ${(endTime - startTime).toFixed(2)}ms`); const res = JSON.parse(ret.res); if ("errors" in res) { throw new ResolverError( diff --git a/typegate/src/runtimes/utils/deno-worker.ts b/typegate/src/runtimes/utils/deno-worker.ts index 8fcc30151e..dcbf9cf4cd 100644 --- a/typegate/src/runtimes/utils/deno-worker.ts +++ b/typegate/src/runtimes/utils/deno-worker.ts @@ -11,7 +11,6 @@ import { } from "./codes.ts"; let logger = getLogger("worker"); -logger.info("start webworker"); let initData = null as unknown as { name: string }; diff --git a/typegate/src/typegraph.ts b/typegate/src/typegraph.ts index 96a00edef0..7bd31f5708 100644 --- a/typegate/src/typegraph.ts +++ b/typegate/src/typegraph.ts @@ -46,11 +46,14 @@ import type { Typegraph as TypeGraphDS, } from "./types/typegraph.ts"; import { TemporalRuntime } from "./runtimes/temporal.ts"; +import { getLogger } from "./log.ts"; export { Cors, Rate, TypeGraphDS, TypeMaterializer, TypePolicy, TypeRuntime }; export type RuntimeResolver = Record; +const logger = getLogger(import.meta); + const runtimeInit: RuntimeInit = { s3: S3Runtime.init, graphql: GraphQLRuntime.init, @@ -180,7 +183,7 @@ export class TypeGraph { }`, ); - console.log(`init ${runtime.name} (${idx})`); + logger.debug(`init ${runtime.name} (${idx})`); return runtimeInit[runtime.name]({ typegraph, materializers: typegraph.materializers.filter( @@ -210,7 +213,7 @@ export class TypeGraph { (rt, i) => [i, rt] as const, ) ) { - console.log(`deinit runtime ${idx}`); + logger.debug(`deinit runtime ${idx}`); await runtime.deinit(); } if (this.introspection) { diff --git a/typegate/src/utils.ts b/typegate/src/utils.ts index d01fe64579..b586d7145c 100644 --- a/typegate/src/utils.ts +++ b/typegate/src/utils.ts @@ -1,9 +1,27 @@ // Copyright Metatype OÜ under the Elastic License 2.0 (ELv2). See LICENSE.md for usage. -import { ComputeStage } from "./engine.ts"; +import type { ComputeStage } from "./engine.ts"; import * as ast from "graphql/ast"; import * as base64 from "std/encoding/base64.ts"; import { None, Option, Some } from "monads"; +import { deepMerge } from "std/collections/deep_merge.ts"; +import { z } from "zod"; + +export const configOrExit = async ( + sources: Record[], + schema: T, +) => { + const parsing = await z.object(schema).safeParse( + sources.reduce((a, b) => deepMerge(a, b), {}), + ); + + if (!parsing.success) { + console.error(parsing.error); + Deno.exit(1); + } + + return parsing.data; +}; export type JSONValue = | string diff --git a/typegate/src/web/auth_debug.ts b/typegate/src/web/auth_debug.ts index 9dfd800e52..4f91904a90 100644 --- a/typegate/src/web/auth_debug.ts +++ b/typegate/src/web/auth_debug.ts @@ -31,7 +31,6 @@ export const renderDebugAuth = async ( let cookies = document.cookie.split(";"); for (let i = 0; i < cookies.length; i += 1) { var cookie = cookies[i]; - console.log(cookie) var idx = cookie.indexOf("="); var name = idx > -1 ? cookie.substr(0, idx): cookie; document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT"; diff --git a/typegate/tests/deno/ts/deno.ts b/typegate/tests/deno/ts/deno.ts index c83539b934..713712ddd7 100644 --- a/typegate/tests/deno/ts/deno.ts +++ b/typegate/tests/deno/ts/deno.ts @@ -3,7 +3,7 @@ let count = 0; export function counter(): number { - console.log("counter", { count }); + //console.log("counter", { count }); return ++count; } diff --git a/typegate/tests/http/http_content_type_test.ts b/typegate/tests/http/http_content_type_test.ts index ba6c1f9092..0246778d56 100644 --- a/typegate/tests/http/http_content_type_test.ts +++ b/typegate/tests/http/http_content_type_test.ts @@ -34,10 +34,6 @@ test("http custom content-type queries", async (t) => { mf.mock("POST@/api/sum_range", async (req) => { const formData: FormData = await req.formData(); // the boundary is expected to be randomized - console.log( - "content-type assigned: ", - req.headers.get("content-type"), - ); const start = Number(formData.get("start") ?? 0); const end = Number(formData.get("end") ?? 1); const result = removeRandomBoundary({ diff --git a/typegate/tests/policies/ts/policies.ts b/typegate/tests/policies/ts/policies.ts index 3b26a16fd0..7dd80e60c5 100644 --- a/typegate/tests/policies/ts/policies.ts +++ b/typegate/tests/policies/ts/policies.ts @@ -17,6 +17,5 @@ export function isAllowedToReadSecret( args: Record>, { context }: { context: Record }, ): boolean { - console.log("POLICY", { args }); return args.secret.username === context.username; } diff --git a/typegate/tests/prisma_migrate/prisma_migrate_test.ts b/typegate/tests/prisma_migrate/prisma_migrate_test.ts index b03aef3f8b..a87568e5cf 100644 --- a/typegate/tests/prisma_migrate/prisma_migrate_test.ts +++ b/typegate/tests/prisma_migrate/prisma_migrate_test.ts @@ -65,7 +65,6 @@ test("prisma migrations", async (t) => { "Authorization": "Basic YWRtaW46cGFzc3dvcmQ=", }) .expectBody(async (body) => { - console.log({ body }); const { createdMigrationName, appliedMigrations, @@ -161,7 +160,6 @@ test("prisma migrations", async (t) => { }) .expectBody((body) => { const { appliedMigrations, databaseReset } = body.data.apply; - console.log({ appliedMigrations, databaseReset }); assert(databaseReset); assertArrayIncludes( appliedMigrations, diff --git a/typegate/tests/rest/rest_test.ts b/typegate/tests/rest/rest_test.ts index 6ddc99b46c..78fc7cdac0 100644 --- a/typegate/tests/rest/rest_test.ts +++ b/typegate/tests/rest/rest_test.ts @@ -34,7 +34,6 @@ test("Rest queries", async (t) => { mf.mock("GET@/api/posts", (req) => { const tags = new URL(req.url).searchParams.getAll("tags"); - console.log({ tags }); const posts = tags.reduce((list, tag) => { switch (tag) { case "even": diff --git a/typegate/tests/utils.ts b/typegate/tests/utils.ts index 54dc289ded..63a83f4776 100644 --- a/typegate/tests/utils.ts +++ b/typegate/tests/utils.ts @@ -24,10 +24,13 @@ import { PrismaMigrate } from "../src/runtimes/prisma_migration.ts"; import { copy } from "std/streams/copy.ts"; import * as native from "native"; import { None } from "monads"; +import { init_native } from "native"; const thisDir = dirname(fromFileUrl(import.meta.url)); const metaCli = resolve(thisDir, "../../target/debug/meta"); +init_native(); + interface ResponseBodyError { message: string; } @@ -488,6 +491,7 @@ export async function recreateMigrations(engine: Engine) { const migrationsBaseDir = join(thisDir, "prisma-migrations"); for await (const runtime of runtimes) { + console.log(runtime); const prisma = new PrismaMigrate(engine, runtime, null); const { migrations } = await prisma.create({ name: "init", diff --git a/website/docs/reference/changelog.mdx b/website/docs/reference/changelog.mdx index 65e85762e1..460fae3c3f 100644 --- a/website/docs/reference/changelog.mdx +++ b/website/docs/reference/changelog.mdx @@ -338,6 +338,29 @@ comments: false +## [v0.0.3-dev.4](https://github.com/metatypedev/metatype/releases/tag/v0.0.3-dev.4) (2/22/2023) + + + +### What's Changed + +#### New features 🎉 + +* chore(meta-cli/codegen): make config file optional by @msga-mmm in [#125](https://github.com/metatypedev/metatype/pull/125) +* chore(deps): bump temporal-sdk-core-protos from `17ceab7` to `454cbea` by @dependabot in [#127](https://github.com/metatypedev/metatype/pull/127) +* chore(deps): bump clap from 4.1.4 to 4.1.6 by @dependabot in [#128](https://github.com/metatypedev/metatype/pull/128) +* chore(deps): bump temporal-sdk-core-protos from `454cbea` to `00fc0ff` by @dependabot in [#132](https://github.com/metatypedev/metatype/pull/132) +* chore(deps): bump temporal-client from `454cbea` to `00fc0ff` by @dependabot in [#131](https://github.com/metatypedev/metatype/pull/131) +* chore: prepare release 0.0.3-dev.4 by @github-actions in [#130](https://github.com/metatypedev/metatype/pull/130) +* chore: upgrade dependency and unify dependency management by @zifeo in [#140](https://github.com/metatypedev/metatype/pull/140) +* chore(deps): bump frozendict from 2.3.4 to 2.3.5 in /typegraph by @dependabot in [#137](https://github.com/metatypedev/metatype/pull/137) + +### New Contributors + +* @github-actions made their first contribution in [#130](https://github.com/metatypedev/metatype/pull/130) + +**Full Changelog**: [v0.0.3-dev.3...v0.0.3-dev.4](https://github.com/metatypedev/metatype/compare/v0.0.3-dev.3...v0.0.3-dev.4) + ## [v0.0.3-dev.3](https://github.com/metatypedev/metatype/releases/tag/v0.0.3-dev.3) (2/16/2023) diff --git a/website/docs/reference/typegate/prisma-migration/mutations.md b/website/docs/reference/typegate/prisma-migration/mutations.md index 5fecdfbee6..5eee6122b7 100644 --- a/website/docs/reference/typegate/prisma-migration/mutations.md +++ b/website/docs/reference/typegate/prisma-migration/mutations.md @@ -7,13 +7,11 @@ sidebar_position: 2 ## apply -**Type:** -[object_22!](/docs/reference/typegate/prisma-migration/objects#object_22) +**Type:** [object_22!](/docs/reference/typegate/prisma-migration/objects#object_22) apply field Policies: - - admin_only

Arguments

@@ -62,13 +60,11 @@ typegraph
## create -**Type:** -[object_31!](/docs/reference/typegate/prisma-migration/objects#object_31) +**Type:** [object_31!](/docs/reference/typegate/prisma-migration/objects#object_31) create field Policies: - - admin_only

Arguments

@@ -126,13 +122,11 @@ typegraph
## deploy -**Type:** -[object_37!](/docs/reference/typegate/prisma-migration/objects#object_37) +**Type:** [object_37!](/docs/reference/typegate/prisma-migration/objects#object_37) deploy field Policies: - - admin_only

Arguments

diff --git a/website/docs/reference/typegate/prisma-migration/queries.md b/website/docs/reference/typegate/prisma-migration/queries.md index 744e7569ad..0d3d89a9e8 100644 --- a/website/docs/reference/typegate/prisma-migration/queries.md +++ b/website/docs/reference/typegate/prisma-migration/queries.md @@ -7,13 +7,11 @@ sidebar_position: 1 ## diff -**Type:** -[object_16!](/docs/reference/typegate/prisma-migration/objects#object_16) +**Type:** [object_16!](/docs/reference/typegate/prisma-migration/objects#object_16) diff field Policies: - - admin_only

Arguments

diff --git a/website/docs/reference/typegate/prisma-migration/scalars.md b/website/docs/reference/typegate/prisma-migration/scalars.md index 470f958aba..da1921ee54 100644 --- a/website/docs/reference/typegate/prisma-migration/scalars.md +++ b/website/docs/reference/typegate/prisma-migration/scalars.md @@ -11,11 +11,8 @@ The `Boolean` scalar type represents `true` or `false`. ## Int -The `Int` scalar type represents non-fractional signed whole numeric values. Int -can represent values between -(2^31) and 2^31 - 1. +The `Int` scalar type represents non-fractional signed whole numeric values. Int can represent values between -(2^31) and 2^31 - 1. ## String -The `String` scalar type represents textual data, represented as UTF-8 character -sequences. The String type is most often used by GraphQL to represent free-form -human-readable text. +The `String` scalar type represents textual data, represented as UTF-8 character sequences. The String type is most often used by GraphQL to represent free-form human-readable text. diff --git a/website/docs/reference/typegate/typegate/mutations.md b/website/docs/reference/typegate/typegate/mutations.md index a7ee9d9732..4d639ed5b1 100644 --- a/website/docs/reference/typegate/typegate/mutations.md +++ b/website/docs/reference/typegate/typegate/mutations.md @@ -12,7 +12,6 @@ sidebar_position: 2 addTypegraph field Policies: - - admin_only

Arguments

@@ -39,7 +38,6 @@ fromString
removeTypegraph field Policies: - - admin_only

Arguments

diff --git a/website/docs/reference/typegate/typegate/queries.md b/website/docs/reference/typegate/typegate/queries.md index 8b6ef8fedf..e94afb61cb 100644 --- a/website/docs/reference/typegate/typegate/queries.md +++ b/website/docs/reference/typegate/typegate/queries.md @@ -12,7 +12,6 @@ sidebar_position: 1 typegraph field Policies: - - admin_only

Arguments

@@ -39,5 +38,4 @@ name
typegraphs field Policies: - - admin_only diff --git a/website/docs/reference/typegraph/typegraph/types.md b/website/docs/reference/typegraph/typegraph/types.md index 226354715d..fbe70358a7 100644 --- a/website/docs/reference/typegraph/typegraph/types.md +++ b/website/docs/reference/typegraph/typegraph/types.md @@ -30,3 +30,27 @@ class integer(number) ``` An integer. + +## union Objects + +```python +@frozen +class union(typedef) +``` + +A `union` type represents a general union with the variants provided. + +The `union` type is equivalent to the `anyOf` field in JSON Schema where +the given data must be valid against one or more of the given subschemas. + +## either Objects + +```python +@frozen +class either(typedef) +``` + +An `either` type represents a disjoint union with the variants provided. + +The `either` type is equivalent to the `oneOf` field in JSON Schema where +the given data must be valid against exactly one of the given subschemas. diff --git a/whiz.yaml b/whiz.yaml index 0e436d4890..fcf029017e 100644 --- a/whiz.yaml +++ b/whiz.yaml @@ -45,7 +45,7 @@ typegate2: depends_on: - typegate_native pipe: - '^.+\[http\].*$': whiz://http + "^.+http .*$": whiz://http http: command: "" @@ -118,7 +118,7 @@ website_docgen: npx docusaurus docs:generate:graphql:prisma-migration npx docusaurus docs:generate:changelog depends_on: - - typegate1 + - typegate_native install_website: workdir: website