Using Server-Sent Events on Domino

Mar 30, 2021, 12:57 PM

Tags: jakartaee java

Though Domino's HTTP stack infamously doesn't support WebSocket, WebSocket isn't the only game in town when it comes to getting push-type information to HTTP clients. HTML5 also brought with it the less-famous Server-Sent Events standard, which is basically half of WebSocket: it allows the server to push events to the client, but it's still a one-way communication channel.

The Standard

The technique that SSE uses is almost ludicrously simple: the client makes a request and the server replies that it will provide text/event-stream content and keeps the connection open. Then, it starts emitting events delimited by blank lines:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
HTTP/1.1 200 OK
Content-Type: text/event-stream;charset=UTF-8



event: timeline
data: hello

event: timeline
data: hello

Unlike WebSocket, there's no Upgrade header, no two-way communication, and thereby no special requirements on the server. It's so simple that you don't even really need a server-side library to use it, though it still helps.

In Practice

I've found that, though SSE is intentionally far less capable than WebSocket, it actually provides what I want in almost all cases: the client can receive messages instantaneously from the server, while the server can receive messages from the client by traditional means like POST requests. Though this is less efficient and flexible than WebSocket, it suits perfectly the needs of apps like server monitors, chat rooms, and so forth.

Using SSE on Domino

JAX-RS, the Java REST service framework, provides a mechanism for working with server-sent events pretty nicely. Baeldung, as usual, has a splendid tutorial covering the API, and a chunk of what I say here will be essentially rehashing that.

However, though Domino ships with JAX-RS by way of the ExtLib, the library only implements JAX-RS 1.x, which predates SSE support. Fortunately, newer JAX-RS implementations work pretty well on Domino, as long as you bring them in in a compatible way. In my XPages Jakarta EE Support project, I did this by way of RESTEasy, and there did the legwork to make it work in Domino's OSGi environment. For our example today, though, I'm going to skip that and build a small webapp using the com.ibm.pvc.webcontainer.application extension point. In theory, this should also work XPages-side with my project, though I haven't tested that; it might require messing with the Servlet response cache.

The Example

I've uploaded my example to GitHub, so the code is available there. I've aimed to make it pretty simple, though there's always some extra scaffolding to get this stuff working on Domino. The bulk of the "pom.xml" file is devoted to two main things: packaging an app as an OSGi bundle (with RESTEasy embedded) and generating an update site with site.xml to import into Domino.

Server Side

The real work happens in TimeStreamResource, the JAX-RS resource that manages client connections and also, in this case, happens to emit the messages as well.

This resource, when constructed, spawns two threads. The first one monitors a BlockingQueue for new messages and passes them along to the SseBroadcaster:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
try {
    String message;
    while((message = messageQueue.take()) != null) {
        // The producer below may send a message before setSse is called the first time
        if(this.sseBroadcaster != null) {
            this.sseBroadcaster.broadcast(this.sse.newEvent("timeline", message)); //$NON-NLS-1$
        }
    }
} catch(InterruptedException e) {
    // Then we're shutting down
} finally {
    this.sseBroadcaster.close();
}

Here, I'm using the Sse#newEvent convenience method to send a basic text message. In practice, you'll likely want to use the builder you get from Sse#newEventBuilder to construct more-complicated events with IDs and structured data types (usually JSON).

A BlockingQueue implementation (such as LinkedBlockingDeque) is ideal for this task, as it provides a simple API to add objects to the queue and then wait for new ones to arrive.

The second one emits a new message every 10 seconds. This is just for the example's sake, and would normally be actually looking something up or would itself be a listener for events it would like to broadcast.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
try {
    while(true) {
        String eventContent = "- At the tone, the Domino time will be " + OffsetDateTime.now();
        messageQueue.offer(eventContent);

        // Note: any sleeping should be short enough that it doesn't block HTTP restart
        TimeUnit.SECONDS.sleep(10);
    }
} catch(InterruptedException e) {
    // Then we're shutting down
}

Browsers can register as listeners just by issuing a GET request to the API endpoint:

1
2
3
4
5
@GET
@Produces(MediaType.SERVER_SENT_EVENTS)
public void get(@Context SseEventSink sseEventSink) {
    this.sseBroadcaster.register(sseEventSink);
}

That will register them as an available listener when broadcast events are sent out.

Additionally, to simulate something like a chat room, I added a POST endpoint to send new messages beyond the periodic ten-second broadcast:

1
2
3
4
5
6
@POST
@Produces(MediaType.TEXT_PLAIN)
public String sendMessage(String message) throws InterruptedException {
    messageQueue.offer(message);
    return "Received message";
}

That's really what there is to it as far as "business logic" goes. There's some scaffolding in the Servlet implementation to get RestEasy working nicely and manage the ExecutorService and the obligatory "plugin.xml" to register the app with Domino and "web.xml" to account for Domino's old Servlet spec, but that's about it.

Client Side

On the client side, everything you need is built into every modern browser. In fact, the bulk of "index.html" is CSS and basic HTML. The JavaScript involved in blessedly slight:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
function sendMessage() {
    const cmd = document.getElementById("message").value;
    document.getElementById("message").value = "";
    fetch("api/time", {
        method: "POST",
        body: cmd
    });
    return false;
}
function appendLogLine(line) {
    const output = document.getElementById("output");
    output.innerText += line + "\n";
    output.scrollTop = output.scrollHeight;
}
function subscribe() {
    const eventSource = new EventSource("api/time");
    eventSource.addEventListener("timeline",  (event) => {
        appendLogLine(event.data);
    });
    eventSource.onerror = function (err) {
        console.error("EventSource failed:", err);
    };
}

window.addEventListener("load", () => subscribe());

The EventSource object is the core of it and is a standard browser component. You give it a path to watch and then listen for events and errors. fetch is also standard and is a much-nicer API for dealing with HTTP requests. In a real app, things might get a bit more complicated if you want to pass along credentials and the like, but this is really it.

Gotchas

The biggest thing to keep in mind when working with this is that you have to be very careful to not block Domino's HTTP task from restarting. If you don't keep everything in an ExecutorService and account for InterruptedExceptions as I do here, you're highly likely to run into a situation where a thread will keep chugging along indefinitely, leading to the dreaded "waiting for session to finish" loop. The ExecutorService's shutdownNow method helps you manage this - as long as your threads have escape hatches for the InterruptedException they'll receive, you should be good.

I also, admittedly, have not yet tested this at scale. I've tried it out here and there for clients, but haven't pulled the trigger on actually shipping anything with it. It should work fine, since it's using standard JAX-RS stuff, but there's always the chance that, say, the broadcaster registry will fill up with never-ending requests and will eventually bloat up. The stack should handle that properly, but you never know.

Beyond any worries about the web container, it's also just a minefield of potential threading and duplicated-work trouble. For example, when I first wrote the example, I found that messages weren't shared, and then that the time messages could get doubled up. That's because JAX-RS, by default, creates a new instance of the resource class for each request. Moving the declaration from the Application class's getClasses() method (which creates new objects) to getSingletons() (which reuses single objects) fixed the first problem. After that, I found that the setSse method was called multiple times even for the singleton, and so I moved the thread spawning to the constructor to ensure that they're only launched once.

Once you have the threading sorted out, though, this ends up being a pretty-practical path to accomplishing the bulk of what you would normally do with WebSocket, even with an aging HTTP stack like Domino's.

What To Do With All This XSP Markup?

Mar 29, 2021, 6:51 PM

Tags: xpages

In some previous posts, I've started talking about some steps one can take to make a complicated XPages app more platform-independent. There's a lot to be done there, refactoring code to bridge differences between runtime environments and to lessen dependencies on XPages-specifics things, but there's a huge elephant in the room: all that XSP markup.

Even if you have a cleanly-structured application where all of your logic is in Java and all of that code doesn't make expectations about the UI, there's still bound to be a big pile of XPages XML markup around, and that's not going anywhere. That's the best case, too: most XPages apps, even Java-based ones, are riddled with all sorts of expectations about the UI, from FacesContext to ExtLibUtil to the DominoDocument model layer.

This is a sticky problem, made all the moreso by the fact that, although XPages is a fork of JSF underneath, the XSP layer is its own special language and isn't really how stock JSF pages were ever written.

There's no really-great answer, but I've never been one to shy away from writing a list of possibilities. These range from actual things one can do right now to hypothetical speculation about what one could build to deal with it. This all starts from the assumption that you want to do something to lessen or remove your XPages dependency. You can instead choose, I suppose, to keep chugging along with it.

Practical Steps

Throw It All Out

This scenario is pretty straightforward: dump your XPages code and never look back. While this could take the form of dumping the stack entirely, I think in practice it will generally take the form of first refactoring your logic (if you haven't already) and then exposing it with REST services. Then, you let your XPages app chug along as-is while you build a new app in whatever else you want, and then swap over when your new app is complete enough.

Throw It All Out, But Slowly

This is similar to above, but you rebuild your app piecemeal, either in place or by sending users to a different app for some parts. This is a very-practical route for large, sprawling applications, and it's what we're doing with one of my clients.

The way it's specifically taking form there is that, when it comes time to write a new module or rewrite an existing one, we build that individual component as an Angular app using REST services and served from an OSGi bundle, and then host it in an <iframe> inside the XPage. So the app continues on as it is, but every once in a while a big chunk of it is deleted and replaced. The use of an <iframe> means that the JS app doesn't have to worry about clashes with the surrounding JavaScript libraries included on the XPage, but gets to share the authentication session. Over time, the XPages app will become essentially a master of ceremonies for the individual modules, and then one day we'll probably swap out that shell too.

Run It In A Webapp

This is a path that would really best be combined with something else, and, admittedly, is essentially specific to me personally. In this case, you use the xpages-runtime project to run your XPages inside a normal WAR container on a good server, and then use that as your base of operations for rebuilding.

My instinct with this project is always to say "well, it's really just an experimental thing", but I use it as my primary means of XPages development and as part of my client's CI chain to host testing builds deployed by Jenkins. There are some minor down sides involved in that you have to really know the innards of the stack inside and out if something goes wrong, and it's also absolutely unsupported by anyone. So... your mileage may vary.

That all said, it makes transforming your XPages app into a modern Java app a dream. You get the full Maven experience for dependencies, and you can use newer technologies without the hassle inherent in trying to cram them onto Domino. And, practicality-wise, it'd really just take a small amount of "abetted but not supported" tweaks on HCL's side to make it less me-specific.

Hypothetical Projects

These hypothetical approaches are naturally on a much-larger scale, and aren't really the sort of thing that one would do to solve their dilemma for an individual project. Really, they'd be HCL-led product decisions, and I'm spitballing even more than usual here.

Transform It To JSF

So I mentioned earlier that JSF markup isn't the same as XSP. The immediate difference between the two is the starting conceit: where an XPage is a fully-composed entity starting at xp:view, JSF syntax evolved from JSP and takes an "embedded in XHTML" approach, like this "hello world":

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:f="http://java.sun.com/jsf/core"      
      xmlns:h="http://java.sun.com/jsf/html">
    
    <h:head>
        <title>JSF 2.0 Hello World</title>
    </h:head>
    <h:body>
    	<h2>JSF 2.0 Hello World Example - hello.xhtml</h2>
    	<h:form>
    	   <h:inputText value="#{helloBean.name}"></h:inputText>
    	   <h:commandButton value="Welcome Me" action="welcome"></h:commandButton>
    	</h:form>
    </h:body>
</html>

If you're starting from an equivalent XPage, it wouldn't be too difficult to get here, and you might even be able to do it with XSLT. Take the xp:view pageTitle and move it to the <title> element, swap out xp:inputText for h:inputText, and so forth, and you're good to go.

That is... not what your average XPage looks like, though, and it doesn't take long for the notion of a clean transformation to crash and burn. SSJS aside, there are all sorts of gotchas: themes, custom controls, xp:eventHandler, any component outside of the core, on-page data sources, and so forth. You'd constantly hit things that are either too different in JSF or don't have equivalents at all.

Though I'm not a JSF master, I expect that it'd be essentially impractical to transform the source fully in this way. That said, you could use it as a starting point: auto-convert what you can and leave commented-out versions of the rest as TODOs for the developer.

Write A Driver For JSF

The other route would be to essentially re-implement XSP on top of JSF. All the XSP is there to do is to describe the XPage as a tree of components, and something could certainly interpret the XML into components slightly more easily than a source translation.

Still, though, this would essentially be equivalent in effort to the "update JSF" requests that the community has been making for years. That's easy to say, but much harder to actually do. Additionally, it'd be more implementation work than the above: while components like h:inputText and xp:inputText share a common ancestor, they're not perfectly compatible, and so there'd have to be a parallel component tree in the JSF runtime.

A Mix of Both

By this, I mean that you could take the "transform the XML to normal JSF" approach as above, converting compatible components over to their stock equivalents, but then re-basing the truly-XPages-specific parts into jakarta.faces classes and including them as a component package so that they'd coexist. This is essentially the "dominoFaces" idea.

While I'm skeptical of the value that this would provide to the larger world, it would be a practical hybrid approach, limiting the amount of code that would break to the stuff that really gets into the weeds of XPages-specific assumptions.

And maybe this is how I'd do it if I was tasked with the job. This would run into more-explicable edge cases than trying to transform the source and wouldn't implicitly encourage writing more pure XSP markup like the second option would.

Transform It To Something Else

Of course, JSF isn't the only game in town, so one could hypothetically try to convert these apps to something else entirely. I'm a little skeptical of the options here, admittedly. An approach that would try to split it to be more client-side than XPages is now would essentially require running the stack on the server anyway to handle all the server-side bindings, so I'm not sure what you'd gain. Moving it to a non-JSF server-side framework would avoid some of that trouble, but I'm not sure what you'd gain that would be worth the nightmare of edge cases.

Still, I want to give the option a mention, since it wouldn't be impossible to do something very clever and functional in this way. I just have my doubts about how worth it it would be. In my mind, moving back to mainline JSF on a good app container would be simpler to do while also leaving the door fully open for working with other tools alongside it much more easily than Domino has offered to date.

The Rest of the Work

This is all musing about the task of dealing with XSP markup specifically, and presupposes that you're willing to at least rewrite a bunch of logic as REST services or (more enjoyably) move to a non-Domino app server. While I have my various projects to make this sort of thing easier, I recognize that (for some reason) there's a big difference between "Jesse said this is possible" and "my company is investing heavily into doing this". Just getting a viable, supportable deployment environment that isn't another dead end would be a project of its own.

One big chunk of the work outside of the XSP markup itself and its relation to JSF is the way that "XPages" as such really represents a whole application stack, not just a UI framework. While there is a slice of it that remains essentially a distinct UI kit, there's a tremendous amount of stuff that lives nebulously in the realm between a root web server and the application framework. The HttpService stuff that I've talked about recently is one such part, sitting below the "web container" portion but being (at this point) an XPages-specific thing. Not all of that would need to come along for the ride, but some of it would, or at least some apps would have to account for it going missing.

Anyway, it's admittedly all a big ball of wax, and no option is really perfect. Still, I think it's important to consider and, ideally, execute on something.

Domino HttpService and the NSF Router Project

Mar 18, 2021, 7:27 PM

Tags: domino java

In my last post and its predecessor, I talked about my tinkering at the XspCmdManager level of Domino's HTTP stack and then more specifically about the com.ibm.designer.runtime.domino.adapter.HttpService class.

The Stack

Now, HttpService is about as generic a name as you can get for this sort of thing, and it doesn't really tell you what it represents. You can think of Domino's HTTP stack since at least the 8.5 era as having two cooperating parts: the core native portion that handles HTTP requests in basically the same way as Domino always did, plus the Java layer as organized by XspCmdManager. The Java layer gets "right of first refusal" for any incoming request that wasn't handled by a DSAPI plugin: before routing the request to the legacy HTTP code, Domino asks XspCmdManager if it'd like to handle it, and only takes care of it at the native layer if Java says no.

XspCmdManager on its own doesn't do much. It accepts the JNI calls from the native side, but otherwise quickly passes the buck to LCDEnvironment (I assume the "LCD" here stands for "Lotus Component Designer"). LCDEnvironment, in turn, really just aggregates registered handlers and dispatches requests. It does a little work to handle exception cases more cleanly than XspCmdManager would, but it's mostly just a dispatcher.

The things that it dispatches to, though, are the HttpServices. These are registered by using the com.ibm.xsp.adapter.serviceFactory IBM Commons extension point, such as here in the plugin.xml form:

1
2
3
<extension point="com.ibm.commons.Extension">
  <service type="com.ibm.xsp.adapter.serviceFactory" class="org.openntf.nsfrouter.NSFRouterServiceFactory" />
</extension>

The class you register there is an implementation of IServiceFactory, which supplies zero or more HttpService implementations on request.

As a side note, I've been using this extension point for years and years, but never before to actually handle HTTP requests. It's extremely convenient in that it's something you can register that is loaded up immediately when the HTTP task starts and is notified as it's terminating, giving you a useful lifecycle without having to wait for a request to come in. I learned about it from the OpenNTF Domino API team and it's been a regular part of my toolkit since.

The HttpService

So that brings us to the HttpService implementation classes themselves. Once LCDEnvironment has gathered them all together, it asks each one in turn (via #isXspUrl) if it can handle a given URL. If any of them say that they can, then it calls the #doService method on each in turn (based on the #getPriority method's return value) until one says that it handled it.

There are a few main HttpService implementations in action on Domino:

  • com.ibm.domino.xsp.module.nsf.NSFService, which handles in-NSF XPages and resources
  • com.ibm.domino.xsp.adapter.osgi.OSGIService, which handles OSGi-registered servlets and webapps
  • com.ibm.domino.xsp.module.nsf.StaticResourcesService, which helps serve static resources

These services also tend to go another layer deeper, passing actual requests off to ComponentModule implementations like NSFComponentModule. That's beyond the scope of what I'm talking about today, but it's interesting to see just how much the Domino stack is basically one giant webapp that contains progressively smaller bounded webapps, like a Matryoshka doll.

For those keeping track, we're about here on a typical XPages call stack:

     at com.ibm.domino.xsp.module.nsf.NSFComponentModule.doService(NSFComponentModule.java:1336)
     at com.ibm.domino.xsp.module.nsf.NSFService.doServiceInternal(NSFService.java:662)
     at com.ibm.domino.xsp.module.nsf.NSFService.doService(NSFService.java:482)
     at com.ibm.designer.runtime.domino.adapter.LCDEnvironment.doService(LCDEnvironment.java:357)
     at com.ibm.designer.runtime.domino.adapter.LCDEnvironment.service(LCDEnvironment.java:313)
     at com.ibm.domino.xsp.bridge.http.engine.XspCmdManager.service(XspCmdManager.java:272)

For our purposes this week, the #isXspUrl and #doService methods on HttpService are our stopping points.

NSF Router Service

In a Twitter conversation yesterday, Per Lausten gave me the idea of using this low level of access to implement improved in-NSF routing. That is to say, if you want "foo.nsf/some/nice/url/here" to actually load up "index.xsp?path=nice/url/here" or the like. Generally, if you want to do this, you either have to set up Web Site rules in names.nsf or settle for next-best options like "index.xsp/nice/url/here".

Since an HttpService comes in at a low-enough level to tackle this, though, it's entirely doable to improve this situation there. So, this morning, I did just that. This new project is a pretty simple one, with all of the action going on in one class.

The way it works is that it looks for a ".nsf" URL and, when it finds one, attempts to load a file or classpath resource named "nsfrouter.properties". The contents of this is a Java Properties file enumerating regex-based routing you'd like. For example:

1
2
foo/(\\w+)=somepage.xsp?bit=bar
baz=somepage.xsp

When found, the class loads up the rules and then uses them to check incoming URLs.

The #doService method then picks up that URL, does a String#replaceAll call to map it to the target, and then redirects the browser over:

NSF Router in action

The user still ends up at the "uglier" URL, but that's the safest way to do it without breaking on-page references.

I felt like that was a neat little exercise, and one that's not only potentially useful on its own but also serves as a good way to play around with these somewhat-lower-level Domino components.

Rapid Progress in Open-Liberty-Runtime Land

Mar 16, 2021, 10:07 PM

Tags: liberty
  1. Options for the Future of the Domino Open Liberty Runtime
  2. Next Steps With the Open Liberty Runtime
  3. Rapid Progress in Open-Liberty-Runtime Land

After my work implementing a reverse proxy the other day, my mental gears kept churning, and I've made some great progress on some new ideas and some ones I had had kicking around for a while.

Domino-Hosted Reverse Proxy

In my last post, I described the new auto-configuring reverse proxy I added, which uses Undertow on a separate port, supporting HTTP/2 and WebSocket. This gives you a unified layout that points to your configured webapps first and then, for all other URLs, points to Domino.

After that, though, I realized that there'd be some convenience value in doing that kind of thing in Domino's HTTP stack itself. The HttpService classes that hook into the XspCmdManager class are designed for just this sort of purpose: listen for designated URLs and handle them in a custom way. I realized that I could watch for incoming requests in the webapps' context roots and direct to them from Domino itself. So that's just what I did. When enabled, you can go to a URL for a configured webapp path (say, "/exampleapp") right on Domino's HTTP/HTTPS port like normal and it'll proxy transparently to the backing app. Better still, it picks up on the mechanisms that Liberty provides to work with X-Forwarded-* headers and $WS* headers to pass along incoming request information and authenticated-user context.

The way I'm describing this may sound a bit dry and abstract, but I think this has a lot of potential, at least when you don't need HTTP/2. With this setup, you can attach fully-modern WAR files in an NSF, configure a server with the very latest Java server technologies and any Java version of your choosing, and have it appear like any other web app on Domino. /foo.nsf goes to your NSF, /fancyapp goes to a modern Java app. Proper webapps, no OSGi dependency nightmare, no Domino-toolchain miasma (well, less of one), deployed seamlessly via NSF - I think it's pretty neat.

Mix-and-Match Runtimes and Java Versions

Historically, the project has had a single configuration document where you specify the version of Open Liberty and your Java version and flavor of choice for all configured apps. Now, though, I've added the ability to pick those on a per-server basis. This can come in handy if you want to use Java 11 (the current LTS version) for complicated apps, but try out the just-released Java 16 for a new app.

Progress on Genericizing the Tooling

Though the project is named after Open Liberty, there's not really anything about the concept that's specific to Liberty as such. Liberty is extremely good and it's particularly well-suited to this purpose, but there's no reason I couldn't adapt this to run any app server, or really any generic process.

Actually supporting anything else is a big task - every server or task would have its own concept of what an "app" is, how configuration is done, how to monitor logs, how to identify open ports, etc. - but the first step is to at least lay the groundwork. So that I did: I've embarked on the path of separating the core runtime loop (start/stop/restart/refresh/etc.) from the specifics of Liberty.

There's still tons of work to do there, and I'm not fully convinced that it'd be worth it (since you should really be writing Java webapps anyway), but that potential future path is smoother now.

Overall

I think this is getting close to the point where it'll be a proper 3.0 release, and it's also getting to a point where the "why is this good?" pitch should be an easier sell for people who aren't already me. I still have vague plans to do a video or webcast on this, and this should make for a less-arcane time of that. So, we'll see! In the mean time, this should all make my own uses all the better.

Next Steps With the Open Liberty Runtime

Mar 12, 2021, 4:37 PM

Tags: liberty
  1. Options for the Future of the Domino Open Liberty Runtime
  2. Next Steps With the Open Liberty Runtime
  3. Rapid Progress in Open-Liberty-Runtime Land

About a year and a half ago, I wrote a post musing about my options with the future of the Domino Open Liberty Runtime project. It's been serving me well - I still use it here and with a client CI setup - but it hasn't quite hit its full potential yet.

Its short-term goal was easy enough to accomplish: I wanted a good way to run modern Servlet apps using an active Domino runtime, and that works great. Its long-term goal takes more work, though: becoming the clear best way to do "web stuff" on Domino. There are a lot of definitions for what that might be, and that "on Domino" bit may not even be the way one would want to go about doing it. Still, I think there's potential there.

So, this week, I decided to go back in and see if I could spruce it up a bit.

The Core of Domino Java HTTP

This started with me musing a bit on Twitter about the true lowest-level entrypoint in Domino's HTTP stack is, and where the border between native and Java lies. After overthinking it a bit, I found that the answer was obvious from any stack trace: XspCmdManager.

From what I gather, the native HTTP task (which is much more opaque than the Java part) loads up its JVM, uses the code in xsp.http.bootstrap.jar to initialize the OSGi environment, asks that environment for the com.ibm.domino.xsp.bridge.http bundle, and uses XspCmdManager in there to handle the layering.

That class has a couple public methods, but two are of immediate interest: isXspUrl and service. The isXspUrl is called for each incoming HTTP request. If that returns false, then nHTTP goes about its normal business like it always did; if it returns true, then nHTTP calls service with a bunch of handle parameters and lets the Java runtime take it from there.

That got me to tinkering. Since that class is in an OSGi bundle, you can readily "outrank" it by having another bundle with the same name and a higher version available. Then, since the class and its methods are just called by strings (more or less), you can have other classes with the same names and APIs in place to do whatever you want. And, such as it is, that works well: you can pretty readily inject whatever code you want into the isXspUrl and service methods and have it take over.

However, that doesn't actually buy you much. What I'd really want to do would be to improve on the actual HTTP server - HTTP/2 support, web sockets, all that - and the Java layer only comes into play after nHTTP has received and started interpreting the connection as an HTTP request. You're not given the raw incoming stream. Additionally, there's not actually any real need to override this low level: the HttpService classes you can register via the com.ibm.xsp.adapter.serviceFactory extension point can choose to handle any incoming URL directly at essentially the same low level as XspCmdManager.

So, while that was fun to poke around with, I don't think there's anything really to be gained there.

Reverse Proxy Improvements

So I went back to an older idea I had kicking around for spawning an all-encompassing reverse proxy. The project has had a lesser version of this for a good while, originally as a WAR file you could add to a Liberty server and then later as a lower-level Liberty feature. However, the way that worked was limited: it would allow you to proxy non-matched requests to a Liberty server to Domino, but didn't do anything to coordinate multiple servers beyond that. Additionally, being a Liberty feature, it limited my future options, such as genericizing the project to work with other app servers.

For my next swing at the problem, I went with Undertow, which is an embeddable Java web server in many ways similar to Jetty, and which is (I gather) the core HTTP part of Wildfly. What made Undertow appealing to me was its modern standards compliance, its relatively-low dependency footprint, and its built-in reverse proxy handler. Additionally, since it's Java, that meant I could embed it in the running JVM without spawning yet another process, hopefully making things all the more reliable.

To go with this, the config DB sprouted some more configuration options:

Reverse proxy config

Along with configuration you explicitly set there and in the individual Liberty server configurations, I have the proxy pick up Domino connection information from names.nsf, allowing it to avoid inconvenient extra environment variables or flags.

And, so far, this has been working splendidly. Undertow's configuration is pretty straightforward, and it wasn't too bad to configure it with prefix matching for the context roots of opted-in apps.

The Next Overall Goal

There's more work to do, beyond just finishing the basic implementation here. I'd really like to get it to a point where you can use this to deploy (at least) WAR-based apps "to Domino" without having to think too much about it, like how you don't have to think about deploying an NSF-based app. It should be thoroughly doable to have the reverse proxy pick up its certificate chain from Domino if desired (especially with the revamped capabilities coming in V12), and some recent changes I made make app deployment noticeably smoother than previously.

Certainly, this sort of project has some inherent limitations compared to nHTTP, but this feels like it's getting a lot closer to a direct upgrade and less like a janky proof-of-concept.