Skip to content

feat: Quickjs4J integration - #1656

Merged
lbroudoux merged 4 commits into
microcks:1.13.xfrom
andreaTP:js-scripting
Aug 27, 2025
Merged

lbroudoux merged 4 commits into
microcks:1.13.xfrom
andreaTP:js-scripting

Conversation

@andreaTP

Copy link
Copy Markdown
Contributor

Description

This is a POC to demonstrate one possible approach to have a JavaScript engine to evaluate the script in dispatch.
The current implementation is for demo purposes, early questions:

  • do we expect people to(only) upload little snippets? In Quickjs4J we invested in the DX to provide the script as a "library"
  • I added a DispatchStyle but I'm unsure it's a good idea, any preference on how to roll this forward?
  • is the proposed JsApi reasonable? any specific preference for accessing fields etc.? or high level guidance like: "should be as familiar as possible to JS/TS devs"
  • the current script doesn't have access to FileSystem/Network and similar, so, it fall short on calling external APIs, do you want to make it possible dynamically in the script? Would it be ok to provide a bespoke HTTP invocation API?
  • ... I have more questions, but let's iterate 🙂

Happy to hear feedback!

Related issue(s)

See also #1559

@github-actions

Copy link
Copy Markdown

👋 @andreaTP

Welcome to the Microcks community! 💖

Thanks and congrats 🎉 for opening your first pull request here! Be sure to follow the pull request template or please update it accordingly.

Hope you have a great time there!

🌟 ~~~~~~~~~ 🌟

📢 If you like Microcks, please ⭐ star ⭐ our repo to support it!

🙏 It really helps the project to gain momentum and credibility. It's a small contribution back to the project with a big impact.

@andreaTP andreaTP changed the title feat: Quickjs4J demo integratio feat: Quickjs4J demo integration Jul 14, 2025

@lbroudoux lbroudoux left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Implementation is crystal clear and very elegant. I love it!
I have some other comments and concerns but at a more general level so pursing in regular comments in the PR.

Comment on lines +123 to +155
public JsonNode get(String key) {
return mapper.convertValue(delegate.get(key), JsonNode.class);
}

@HostFunction
public void set(String key, Object value) {
delegate.put(key, value);
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I assume this is because of the JS representation of an object, but shouldn't we also convert on the set() method? Should we have a mapper.readTree() or something?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's possible, I was unsure about what we need to expose to the JS environment from the requestContext.
When I have a few meaningful examples of RequestContext I'm happy to revisit and iterate on tests to figure out the best user experience.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

went back to the original implementation, rationale:

  • we set plain object from Java
  • we get the values from JS

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not really. The script inserts data or facts into the requestContext so that this data can be used later during the response rendering step. So typically, script will compute stuff, insert them in the context and the response will include it.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

oh, ok, do you have an example so that I'm sure I'm testing the right use-case?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think that's ok. The only missing part here is that later on, foo can be reused as a variable in the response template for example:

{
   "foo": "{{ foo }}"
}

Then the mock controller will inject the request context into the rendering engine to get the final {"foo": "bar"} response.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the context, in this case I believe the current implementation is "good enough" as the value out of the map is the expected one:
https://github.com/microcks/microcks/pull/1656/files#diff-1c89164c15586f6c599cedee5c6ca2c74546b94fa59ced69cb71869b5c0a8fc1R120

e.g. trying to store values as JsonNode produces double quoting of the strings value

Comment thread webapp/src/main/webapp/angular.json Resolved
@lbroudoux

Copy link
Copy Markdown
Member

Hey @andreaTP

I've reviewed the code on this PR, and I like it! The approach is very elegant and clear. I think the "code part" of this proposition is really good, so I'll follow up here on more global questions and concerns.

Regarding your initial questions:

do we expect people to(only) upload little snippets? In Quickjs4J we invested in the DX to provide the script as a "library"

IMHO, little snippets are the most common way of doing things. This is for mocking purposes so it shouldn't end in a full implementation 😉 That said, having the ability to reuse modules can be nice, and it is actually done (see https://microcks.io/blog/extend-microcks-with-custom-libs/). It requires additional operations, though, like mounting a file volume in the container image or rebuilding a custom image, embedding your modules. Do you confirm we could keep the same principles as those described in this blog post?

I added a DispatchStyle but I'm unsure it's a good idea, any preference on how to roll this forward?

Ideally, I think it could be nice to keep SCRIPT and then dynamically detect if it's old Groovy or JS (or others?).

is the proposed JsApi reasonable? any specific preference for accessing fields etc.? or high level guidance like: "should be as familiar as possible to JS/TS devs"

It looks simple and neat to me. I think "should be as familiar as possible to JS/TS devs" is very good guidance. I'd like to keep it as idiomatic as possible.

the current script doesn't have access to FileSystem/Network and similar, so, it fall short on calling external APIs, do you want to make it possible dynamically in the script? Would it be ok to provide a bespoke HTTP invocation API?

Yes, that's a requirement. Regarding the above question, and as stated elsewhere, having the ability to use fetch() would be super convenient. It could be an adapted version of fetch() that is indeed a HostFunction. I assume that we would also have to adapt or get rid of the async/await semantics, but this is one of my other questions 😉

Some of my questions and concerns:

  • How does QuickJS (or QuickJS4J) deal with async/await semantics? Would we have to restrict or forbid their usage? Is there a graceful fallback? I can imagine that this is a common question, even more so if you allow reusing a complete module that may use this.

  • How QuickJS/QuickJS4J compares to GraalJS in terms of:

    • JS/TS/EcmaScript support?
    • Sandboxing model?
    • Weight/size of the library?
  • QuickJS4J mentions being Native-image friendly. Is there any specific guidance other than traditional class registration for reflection?

  • Is it possible to cache script evaluation between different calls? Recently, we activated caching on Groovy evaluation using the JSR233 mechanisms with nice results (see Improve SCRIPT dispatcher performance enabling caching #1543). Is there some way of doing this in QuickJS4J?

And yes: let's iterate!

@andreaTP

Copy link
Copy Markdown
Contributor Author

Thanks a lot for the in depth answer @lbroudoux , I hope this is a complete enough answer 🤞 :

IMHO, little snippets are the most common way of doing things.

Ok, agreed, let's keep focusing on code snippets 👍

Do you confirm we could keep the same principles as those described in this blog post?

As far as I understand it there are no limitations here, the JS "library" file can be picked up at runtime and executed dynamically(even in native-mode as we are using a compiled js interpreter).

dynamically detect

That's possible, but I don't have a great way to do it efficiently, do you have suggestions?
Maybe deprecating SCRIPT and adding GROOVY_SCRIPT and JS_SCRIPT? Or having an additional field for the language selection?

I'd like to keep it as idiomatic as possible.

Cool 👍

fetch()

Added a demo fetch implementation and usage here.

async/await

QuickJs does support async/await, but it was not enabled in QuickJs4J, fixing it here.
By doing it I noticed that things like setTimeout are not supported though, I don't think we should limit or forbid the usage, but we need to keep an eye at "how it is used" by the initial use-cases.

  • How QuickJS/QuickJS4J compares to GraalJS in terms of:
  • JS/TS/EcmaScript support?

The support of EcmaScript is pretty complete according to the docs, and we already stressed it with biggish chunks of JS.
There is no native TS support, but compilers and bundlers are doing an excellent job here, I haven't attempted to compile TS "on the fly" as it would be required by a "barebone script".
GraalJS is a full fledged Node(V8) alternative, QuickJs is a pure JS runtime and you don't have any Node or browser specific API; the trade offs are very different.

  • Sandboxing model?

QuickJs is executed in a Wasm sandbox:

  • the memory is isolated and stored on the Java heap (there is no chance of data corruption caused by a module on the java host), you can also define bounds of it
  • the execution honors Threads interruptions, and, by default, the Runner timeouts the plugin execution after a few seconds (configurable)
    In GraalJS there is a concept of isolates.
  • Weight/size of the library?

QuickJs4J is, currently ~700Kb of distributable jar containing QuickJs plus the bindings to it.
This comes with additional transitive dependencies on e.g. Jackson and Chicory.
GraalJS is a very complete runtime and, if you want decent performance, you need to have GraalJIT available, last time I measured GraalJIT was ~7/8Mb.
That's the default for Graal JDK distros, but might complicate the setup for other Java distributions.

Is there any specific guidance other than traditional class registration for reflection?

The expectation is that everything should work out of the box with native-image by design, anything else is going to be treated as a bug. (FYI we are testing this aspect in the Quarkus integration )

Is it possible to cache script evaluation between different calls?

Yes, I have just done it here, but I think we should wait a little to stabilize the design before optimizing this aspect (it might look slightly different depending on how things unroll).

@lbroudoux

Copy link
Copy Markdown
Member

Awesome! Thanks for the answers. It's super clear now!
The only remaining issue on which I have to form an opinion is the question of SCRIPT vs. GROOVY_SCRIPT and JS_SCRIPT. Groovy scripts could contain very specific constructs like def or java.* classes usage but those are far from being mandatory, so it wouldn't be enough to decide... Let me think about it.

@lbroudoux

Copy link
Copy Markdown
Member

Unfortunately, we got an issue on unit tests;

[INFO] Running io.github.microcks.util.script.JsScriptEngineBinderTest
14:00:48.396 [main] INFO  i.g.m.u.script.JsScriptEngineBinder - fetch status: 503
14:00:48.545 [main] INFO  i.g.m.u.script.JsScriptEngineBinder - header: bar
14:00:48.601 [main] INFO  i.g.m.u.script.JsScriptEngineBinder - uri parameter: bar
Error:  Tests run: 6, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 1.908 s <<< FAILURE! -- in io.github.microcks.util.script.JsScriptEngineBinderTest
Error:  io.github.microcks.util.script.JsScriptEngineBinderTest.testFetchApiWorks -- Time elapsed: 1.282 s <<< FAILURE!
org.opentest4j.AssertionFailedError: expected: <true> but was: <false>
	at org.junit.jupiter.api.AssertionFailureBuilder.build(AssertionFailureBuilder.java:151)
	at org.junit.jupiter.api.AssertionFailureBuilder.buildAndThrow(AssertionFailureBuilder.java:132)
	at org.junit.jupiter.api.AssertTrue.failNotTrue(AssertTrue.java:63)
	at org.junit.jupiter.api.AssertTrue.assertTrue(AssertTrue.java:36)
	at org.junit.jupiter.api.AssertTrue.assertTrue(AssertTrue.java:31)
	at org.junit.jupiter.api.Assertions.assertTrue(Assertions.java:183)
	at io.github.microcks.util.script.JsScriptEngineBinderTest.testFetchApiWorks(JsScriptEngineBinderTest.java:206)
	at java.base/java.lang.reflect.Method.invoke(Method.java:580)
	at java.base/java.util.ArrayList.forEach(ArrayList.java:1596)
	at java.base/java.util.ArrayList.forEach(ArrayList.java:1596)

@andreaTP Can you check this one?

@andreaTP

Copy link
Copy Markdown
Contributor Author

Unfortunately, we got an issue on unit tests;

On it 👍 , please don't consider this PR final just yet, with this I'm mostly gathering feedback and will tight it up later on 🙂

@lbroudoux lbroudoux left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@andreaTP

Copy link
Copy Markdown
Contributor Author

@lbroudoux I'll make soon another iteration or two on this PR to (start) bridge the gap on the subjects we discussed and try to finalize it 🙂

@andreaTP
andreaTP force-pushed the js-scripting branch 3 times, most recently from a63decf to 11e41eb Compare July 21, 2025 15:54
@andreaTP

Copy link
Copy Markdown
Contributor Author

Done an iteration on the code, and I think that most things are in place now.
Notes:

  • I went down deprecating SCRIPT in favor of GROOVY: I though a bit at dynamically parsing, but it seems a bit too much of a guess, and it opens the door to questions like: what if we don't recognize the script?
  • The Node fetch implementation is pretty dumb atm, but I think this can be improved with iterations and in response to issues, alternatively, I can cover a finite number of use cases 🙂

Not fussy on anything here though 🙂

@andreaTP
andreaTP marked this pull request as ready for review July 21, 2025 16:13
@andreaTP
andreaTP requested a review from yada as a code owner July 21, 2025 16:13
@andreaTP andreaTP changed the title feat: Quickjs4J demo integration feat: Quickjs4J integration Jul 21, 2025
@andreaTP
andreaTP force-pushed the js-scripting branch 2 times, most recently from 02731b7 to f82161d Compare July 21, 2025 17:02
@andreaTP

Copy link
Copy Markdown
Contributor Author

Sorry for the noise on the repo, the CI workflows should be fine now 🤞


/**
* Utility class that holds methods for creating binding environments and evaluation context for a JSR 233 ScriptEngine.
* @author laurent

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please put your name here 😉

* @return A JS object with status and text() method
*/
@HostFunction
public Object fetch(String url) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Saw your answers on JavaScript polymorphism and actual fetch() implementation. I agree this one can be completed later on but shouldn't we - at least - make more arguments available to avoid too many fetch*() methods later on and regression on existing consumers?

Maybe a simple signature like:

public Object fetch(String url, String method, String body, Map<String, String> headers) {
   // ... 
}

will do the trick?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sounds good, I can implement the proposed signature 👍

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done, the handling of JSON should likely be improved, but there is a baseline now.

@lbroudoux lbroudoux left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Got 2 comments left ;-)

@lbroudoux

Copy link
Copy Markdown
Member

Hi @andreaTP thanks for the great submission! No noise here: only good stuff!

I have one more question regarding script caching: earlier on, you pointed to a change that was related to JSR233 support (but still a draft PR), and I also see this commit related to JS module.

Is there any caching enabled at the time of your latest 0.0.7 release or is it a WIP that is planned?

@andreaTP

Copy link
Copy Markdown
Contributor Author

Is there any caching enabled at the time of your latest 0.0.7 release or is it a WIP that is planned?

I forgot to say it, but I already took care of caching with this change:
https://github.com/microcks/microcks/pull/1656/files#diff-ea5b79b063e2e16bf6ea94e55b0b08f809eab7894662f089eaf19caeeabef23aR54

With the bump to 0.0.7 you get first class async support instead 🙂

@lbroudoux

Copy link
Copy Markdown
Member

I forgot to say it, but I already took care of caching with this change

Ok! I'm reading https://github.com/roastedroot/quickjs4j/blob/main/core/src/main/java/io/roastedroot/quickjs4j/core/ScriptCache.java and the Engine, and I see no eviction policy in case the digested key is missing. Imagine the script being updated and replaced many times by people iterating on it via the UI or other means.

Wouldn't it be nice to use at least a LinkedHashMap as the internal cache to implement something like a LRU policy via removeEldestEntry()?

@andreaTP

Copy link
Copy Markdown
Contributor Author

Imagine the script being updated and replaced many times by people iterating on it via the UI or other means.

Expecting very small scripts, and the fact that the cache only retains the QuickJs "compiled" version of those I thought it would be a "day 2" issue to clear the cache 😅
But you are correct, and hooking up an LRU or something is easy, I'll improve on this aspect!

@andreaTP

Copy link
Copy Markdown
Contributor Author

Updated the PR:

  • Added the LRUCache using: org.codehaus.groovy.runtime.memoize.LRUCache.
  • Implemented the requested fetch signature (still missing proper handling of JSON, this PR is growing and I'd prefer to do a follow up in case requested)

I took the opportunity to make things nicer/easier starting in QuickJs4J, hence the version bump 🙂

@andreaTP

andreaTP commented Aug 4, 2025

Copy link
Copy Markdown
Contributor Author

Hi 👋 I'm back from vacation and able to iterate again on this when requested.
Looking through the comments I think that everything has been addressed, let me know if I missed anything 🙏

@lbroudoux

Copy link
Copy Markdown
Member

Hey @andreaTP
I'm also now back from vacations and ready to merge that! I plan to integrate this into the next 1.13.0 and just started a 1.13.x development branch. Would you mind rebasing your work in 1.13.x and change the PR to target this branch?

@andreaTP
andreaTP changed the base branch from master to 1.13.x August 26, 2025 10:37
@andreaTP

Copy link
Copy Markdown
Contributor Author

Welcome back @lbroudoux and thanks for picking this up again 🙂

Rebased and re-targeted, should be good 👍

@andreaTP

Copy link
Copy Markdown
Contributor Author

The Sonar check requires access to secrets, it's not going to pass, I opened #1690 to workaround it.

@lbroudoux lbroudoux left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Got a re-read and added a final concern / change request.

@lbroudoux lbroudoux left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks all good to me! Go!

@lbroudoux
lbroudoux merged commit 290b6c7 into microcks:1.13.x Aug 27, 2025
@andreaTP

Copy link
Copy Markdown
Contributor Author

@lbroudoux thanks for the support in this initiative 🙂

Should we plan follow ups? On top of mind I have:

  • json support in the fetch clone
  • missing docs

@lbroudoux

Copy link
Copy Markdown
Member

Yes absolutely!

Documentation is the top priority IMHO and we should add something like we did for Groovy here: https://microcks.io/documentation/explanations/dispatching/#script-dispatcher. Documentation is living in the microcks/microcks.io Github repository.

JSON support is also more than welcome!

It would be awesome if you created an issue for each follow-up idea you have in mind so that we can keep them in sight!

Thanks a lot!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants