Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

refactor(sdk): move post-processing functions to the typegate #586

Merged
merged 29 commits into from
Feb 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
89136c6
feat(sdk/prisma): prepare interfaces
afmika Feb 5, 2024
89e5021
fix(sdk/python): bad types, missing print
afmika Feb 5, 2024
469ae4a
feat(sdk/prisma): handle migrations (wip)
afmika Feb 5, 2024
a5c3b9e
Merge branch 'main' into test-framework-integration-prisma
afmika Feb 6, 2024
7ab2a76
feat(sdk/prisma): finalize fs ops
afmika Feb 6, 2024
16c36b6
feat(sdk/prisma): handle migrations
afmika Feb 6, 2024
c501db9
fix(sdk/prisma): minor bugs, some polishing
afmika Feb 7, 2024
d640bf3
feat(sdk): tg_remove
afmika Feb 7, 2024
9a7002b
fix(sdk/website): use cwd, add missing values in website typegraphs
afmika Feb 7, 2024
3a9b266
feat(sdk): make cwd configurable + test
afmika Feb 7, 2024
fff48aa
fix(test/examples): same port issue, removed some comments
afmika Feb 8, 2024
e0433f4
fix(test): same port issue
afmika Feb 8, 2024
330ed2b
refactor(sdk): move typescript transpile to gate
afmika Feb 8, 2024
f578769
test(refactor): better use case
afmika Feb 9, 2024
fae24e3
refactor(tg_deploy): always return serialized typegraph
afmika Feb 9, 2024
e9c0377
fix(test): try *dumb* fix for coverage
afmika Feb 9, 2024
451e354
Merge branch 'main' into move-post-processing-functions-to-the-typegate
afmika Feb 9, 2024
3a2976e
Merge branch 'main' into test-framework-integration-prisma
afmika Feb 11, 2024
60a7300
Merge branch 'main' into move-post-processing-functions-to-the-typegate
afmika Feb 12, 2024
b3edd31
fix(test): outdated target version
afmika Feb 12, 2024
0f842fd
Merge branch 'test-framework-integration-prisma' into move-post-proce…
afmika Feb 12, 2024
68b3b30
fix(examples): outdated version
afmika Feb 12, 2024
deb9f5a
sync with branch 'test-framework-integration-prisma'
afmika Feb 12, 2024
fbf8cae
refactor(cli): remove transpile postproc
afmika Feb 12, 2024
5859be9
refactor(test/gate): fix website_test, postproc at runtime init => po…
afmika Feb 13, 2024
5efebc5
docs(CONTRIBUTING.md): add local Local typegraph setup with Nodejs
afmika Feb 13, 2024
5e87633
fix(test): reuse previous output and prettify
afmika Feb 13, 2024
f9bece0
Merge branch 'main' into move-post-processing-functions-to-the-typegate
Natoandro Feb 14, 2024
71f7a70
fix: merge conflict
afmika Feb 16, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
16 changes: 15 additions & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,8 @@ steps in advance to help us fix any potential bug as fast as possible.
you might want to check [this section](#i-have-a-question)).
- To see if other users have experienced (and potentially already solved) the
same issue you are having, check if there is not already a bug report existing
for your bug or error in the [bug tracker](https://github.com/metatypedev/metatype/issues?q=label%3Abug).
for your bug or error in the
[bug tracker](https://github.com/metatypedev/metatype/issues?q=label%3Abug).
- Also make sure to search the internet (including Stack Overflow) to see if
users outside the GitHub community have discussed the issue.
- Collect information about the bug:
Expand Down Expand Up @@ -230,3 +231,16 @@ rustflags = [
"-C", "link-arg=-fuse-ld=mold"
]
```

#### Local typegraph with Nodejs

Currently, the `typegraph/sdk/node/dist` project is generated dynamically.
Depending on your package manager, the protocol used may differ.

```bash
# uses the `file:..` protocol
npm install path/to/typegraph/sdk/node/dist

# uses the `link:..` protocol (equivalent to `file:..` but for directories only)
pnpm install path/to/typegraph/sdk/node/dist
```
1 change: 0 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 1 addition & 4 deletions meta-cli/src/typegraph/loader/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,7 @@ impl LoaderPool {
pub fn new(config: Arc<Config>, max_parallel_loads: usize) -> Self {
Self {
config,
postprocessors: vec![
postprocess::Validator.into(),
postprocess::ReformatScripts.into(),
],
postprocessors: vec![postprocess::Validator.into()],
semaphore: Semaphore::new(max_parallel_loads),
}
}
Expand Down
48 changes: 2 additions & 46 deletions meta-cli/src/typegraph/postprocess.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,10 @@ use colored::Colorize;
use common::archive::archive_entries;
use common::typegraph::utils::{map_from_object, object_from_map};
use common::typegraph::validator::validate_typegraph;
use common::typegraph::{Materializer, Typegraph};
use common::typegraph::Typegraph;
use ignore::WalkBuilder;
use log::error;
use std::path::Path;
use typescript::parser::transform_script;

pub trait PostProcessor {
fn postprocess(&self, tg: &mut Typegraph, config: &Config) -> Result<()>;
Expand All @@ -35,14 +34,6 @@ where
#[derive(Clone)]
pub struct PostProcessorWrapper(Arc<RwLock<Box<dyn PostProcessor + Sync + Send>>>);

impl PostProcessorWrapper {
pub fn generic(
pp: impl Fn(&mut Typegraph, &Config) -> Result<()> + Sync + Send + 'static,
) -> Self {
PostProcessorWrapper::from(GenericPostProcessor(pp))
}
}

impl<T> From<T> for PostProcessorWrapper
where
T: PostProcessor + Send + Sync + 'static,
Expand Down Expand Up @@ -112,7 +103,6 @@ fn compress_and_encode(main_path: &Path, tg_path: &Path) -> Result<String> {
}

pub use deno_rt::DenoModules;
pub use deno_rt::ReformatScripts;
pub use prisma_rt::EmbedPrismaMigrations;
pub use prisma_rt::EmbeddedPrismaMigrationOptionsPatch;
pub use python_rt::PythonModules;
Expand Down Expand Up @@ -141,44 +131,10 @@ impl PostProcessor for Validator {
pub mod deno_rt {
use std::fs;

use common::typegraph::runtimes::deno::{FunctionMatData, ModuleMatData};
use common::typegraph::runtimes::{KnownRuntime, TGRuntime};

use common::typegraph::utils::{find_runtimes, get_materializers};
use common::typegraph::runtimes::deno::ModuleMatData;

use super::*;

pub struct ReformatScripts;

impl From<ReformatScripts> for PostProcessorWrapper {
fn from(_val: ReformatScripts) -> Self {
PostProcessorWrapper::generic(reformat_scripts)
}
}

fn reformat_materializer_script(mat: &mut Materializer) -> Result<()> {
if mat.name.as_str() == "function" {
let mut mat_data: FunctionMatData = object_from_map(std::mem::take(&mut mat.data))?;
// TODO check variable `_my_lambda` exists and is a function expression/lambda
mat_data.script = transform_script(mat_data.script)?;
mat.data = map_from_object(mat_data)?;
}
Ok(())
}

fn reformat_scripts(typegraph: &mut Typegraph, _c: &Config) -> Result<()> {
for rt_idx in find_runtimes(typegraph, |rt| {
matches!(rt, TGRuntime::Known(KnownRuntime::Deno(_)))
})
.into_iter()
{
for mat_idx in get_materializers(typegraph, rt_idx as u32) {
reformat_materializer_script(&mut typegraph.materializers[mat_idx])?;
}
}
Ok(())
}

#[derive(Default, Debug, Clone)]
pub struct DenoModules {
codegen: bool,
Expand Down
4 changes: 4 additions & 0 deletions typegate/engine/bindings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -570,3 +570,7 @@ export function archive(a0: ArchiveInp): ArchiveResult {
return { Err: { message: err.toString() } };
}
}

export function transformTypescript(a0: string): string {
return Meta.deno.transformTypescript(a0);
}
4 changes: 4 additions & 0 deletions typegate/engine/runtime.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -198,4 +198,8 @@ declare namespace Meta {
function registerModule(inp: PythonRegisterInp): string;
function unregisterModule(inp: PythonUnregisterInp): string;
}

namespace deno {
function transformTypescript(inp: string): string;
}
}
3 changes: 3 additions & 0 deletions typegate/engine/runtime.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,9 @@ globalThis.Meta = {
registerModule: ops.op_register_module,
unregisterModule: ops.op_unregister_module,
},
deno: {
transformTypescript: ops.op_deno_transform_typescript,
},
version: ops.op_get_version,
typescriptFormatCode: ops.op_typescript_format_code,
typegraphValidate: ops.op_typegraph_validate,
Expand Down
3 changes: 2 additions & 1 deletion typegate/engine/src/ext.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

use crate::interlude::*;
use crate::{
runtimes::{prisma, python::python_bindings, temporal, wasmedge},
runtimes::{deno_rt, prisma, python::python_bindings, temporal, wasmedge},
typegraph, typescript,
};

Expand Down Expand Up @@ -49,6 +49,7 @@ deno_core::extension!(
prisma::op_prisma_reset,
prisma::op_unpack,
prisma::op_archive,
deno_rt::op_deno_transform_typescript
],
esm_entry_point = "ext:tg_metatype_ext/runtime.js",
esm = ["runtime.js"],
Expand Down
1 change: 1 addition & 0 deletions typegate/engine/src/runtimes.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Copyright Metatype OÜ, licensed under the Elastic License 2.0.
// SPDX-License-Identifier: Elastic-2.0

pub mod deno_rt;
pub mod prisma;
pub mod python;
pub mod temporal;
Expand Down
16 changes: 16 additions & 0 deletions typegate/engine/src/runtimes/deno_rt.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
#![allow(clippy::not_unsafe_ptr_arg_deref)]

// Copyright Metatype OÜ, licensed under the Elastic License 2.0.
// SPDX-License-Identifier: Elastic-2.0

use crate::interlude::*;

#[rustfmt::skip]
use deno_core as deno_core; // necessary for re-exported macros to work
use typescript::parser::transform_script;

#[deno_core::op2]
#[string]
pub fn op_deno_transform_typescript(#[string] script: String) -> Result<String> {
transform_script(script)
}
34 changes: 34 additions & 0 deletions typegate/src/postprocess.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// Copyright Metatype OÜ, licensed under the Elastic License 2.0.
// SPDX-License-Identifier: Elastic-2.0

import { transformTypescript, typescript_format_code } from "native";
import { nativeResult } from "./utils.ts";
import { TypeGraphDS } from "./typegraph/mod.ts";

abstract class PostProcessor {
/** Postprocess the provided typegraph reference */
abstract postprocess(tg: TypeGraphDS): void;
}

class DenoPostProcess extends PostProcessor {
postprocess(tg: TypeGraphDS): void {
for (const mat of tg.materializers) {
if (mat.name == "function") {
const jsScript = transformTypescript(mat.data.script as string);
mat.data.script = nativeResult(
typescript_format_code({ source: jsScript }),
)
?.formatted_code!;
}
}
}
}

export function applyPostProcessors(typegraphRefs: TypeGraphDS[]): void {
const postprocesses = [new DenoPostProcess()] as Array<PostProcessor>;
for (const postprocess of postprocesses) {
for (const tgJson of typegraphRefs) {
postprocess.postprocess(tgJson);
}
}
}
1 change: 0 additions & 1 deletion typegate/src/runtimes/deno/deno.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,6 @@ export class DenoRuntime extends Runtime {
for (const mat of materializers) {
if (mat.name === "function") {
const code = mat.data.script as string;

ops.set(registryCount, {
type: "register_func",
fnCode: code,
Expand Down
3 changes: 3 additions & 0 deletions typegate/src/runtimes/typegate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { closestWord } from "../utils.ts";
import { Type, TypeNode } from "../typegraph/type_node.ts";
import { StringFormat } from "../typegraph/types.ts";
import { mapValues } from "std/collections/map_values.ts";
import { applyPostProcessors } from "../postprocess.ts";

const logger = getLogger(import.meta);

Expand Down Expand Up @@ -148,6 +149,8 @@ export class TypeGateRuntime extends Runtime {
}

const tgJson = await TypeGraph.parseJson(fromString);
applyPostProcessors([tgJson]);

const { engine, response, name } = await this.typegate.pushTypegraph(
tgJson,
JSON.parse(secrets),
Expand Down