Skip to content

Commit

Permalink
PivotHandlerServerConfigurator
Browse files Browse the repository at this point in the history
  • Loading branch information
michielbdejong committed Dec 4, 2024
1 parent 596e2c7 commit 202a385
Show file tree
Hide file tree
Showing 5 changed files with 95 additions and 0 deletions.
11 changes: 11 additions & 0 deletions config/dev.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,17 @@
"@type": "StaticAssetEntry",
"filePath": "www/index.html"
}
},
{
"comment": "Redirect to add/remove trailing slash where it helps",
"@type": "Override",
"overrideInstance": { "@id": "urn:solid-server:default:HandlerServerConfigurator" },
"overrideParameters": {
"@type": "PivotHandlerServerConfigurator",
"comment": "Handles all request events from the server.",
"handler": { "@id": "urn:solid-server:default:HttpHandler" },
"showStackTrace": { "@id": "urn:solid-server:default:variable:showStackTrace" }
}
}
]
}
8 changes: 8 additions & 0 deletions config/prod.json
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,14 @@
"@type": "StaticAssetEntry",
"filePath": "www/index.html"
}
},
{
"comment": "Redirect to add/remove trailing slash where it helps",
"@type": "Override",
"overrideInstance": { "@id": "urn:solid-server:default:HandlerServerConfigurator" },
"overrideParameters": {
"@type": "PivotHandlerServerConfigurator"
}
}
]
}
8 changes: 8 additions & 0 deletions config/test.json
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,14 @@
"@type": "StaticAssetEntry",
"filePath": "www/index.html"
}
},
{
"comment": "Redirect to add/remove trailing slash where it helps",
"@type": "Override",
"overrideInstance": { "@id": "urn:solid-server:default:HandlerServerConfigurator" },
"overrideParameters": {
"@type": "PivotHandlerServerConfigurator"
}
}
]
}
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@ export * from "./storage/RedirectingStore";
export * from "./storage/RdfPatchingStore";
export * from "./storage/patch/ThrowingN3Patcher";
export * from './FedcmHttpHandler'
export * from './server/PivotHandlerServerConfigurator';
67 changes: 67 additions & 0 deletions src/server/PivotHandlerServerConfigurator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import type { IncomingMessage, Server, ServerResponse } from 'node:http';
import { getLoggerFor, isError, guardStream, HttpHandler, ServerConfigurator } from '@solid/community-server';

/**
* A {@link ServerConfigurator} that attaches an {@link HttpHandler} to the `request` event of a {@link Server}.
* All incoming requests will be sent to the provided handler.
* Failsafes are added to make sure a valid response is sent in case something goes wrong.
*
* The `showStackTrace` parameter can be used to add stack traces to error outputs.
*/
export class PivotHandlerServerConfigurator extends ServerConfigurator {
protected readonly logger = getLoggerFor(this);
protected readonly errorLogger = (error: Error): void => {
this.logger.error(`Request error: ${error.message}`);
};

/** The main HttpHandler */
private readonly handler: HttpHandler;
private readonly showStackTrace: boolean;

public constructor(handler: HttpHandler, showStackTrace = false) {
super();
this.handler = handler;
this.showStackTrace = showStackTrace;
}

public async handle(server: Server): Promise<void> {
server.on(
'request',
// eslint-disable-next-line ts/no-misused-promises
async(request: IncomingMessage, response: ServerResponse): Promise<void> => {
try {
this.logger.info(`Pivot received ${request.method} request for ${request.url}`);
const guardedRequest = guardStream(request);
guardedRequest.on('error', this.errorLogger);
await this.handler.handleSafe({ request: guardedRequest, response });
} catch (error: unknown) {
const errMsg = this.createErrorMessage(error);
this.logger.error(errMsg);
if (response.headersSent) {
response.end();
} else {
response.setHeader('Content-Type', 'text/plain; charset=utf-8');
response.writeHead(500).end(errMsg);
}
} finally {
if (!response.headersSent) {
response.writeHead(404).end();
}
}
},
);
}

/**
* Creates a readable error message based on the error and the `showStackTrace` parameter.
*/
private createErrorMessage(error: unknown): string {
if (!isError(error)) {
return `Unknown error: ${error as string}.\n`;
}
if (this.showStackTrace && isError(error) && error.stack) {
return `${error.stack}\n`;
}
return `${error.name}: ${error.message}\n`;
}
}

0 comments on commit 202a385

Please sign in to comment.