webspresso 0.0.103 → 0.0.105
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.agents/AGENTS.md +6 -0
- package/.agents/ARCHITECTURE.md +23 -0
- package/.agents/CACHE.md +147 -0
- package/.agents/CLI.md +1 -1
- package/.agents/EARLY_HINTS.md +120 -0
- package/.agents/HEALTH.md +118 -0
- package/.agents/LIMITS.md +109 -0
- package/.agents/ORM.md +155 -1
- package/.agents/PLUGINS.md +28 -0
- package/.agents/RESILIENCE.md +235 -0
- package/AGENTS.md +6 -0
- package/README.md +2 -2
- package/bin/commands/add-docker.js +6 -6
- package/bin/commands/dev.js +4 -3
- package/bin/commands/new.js +5 -5
- package/bin/commands/openapi.js +1 -1
- package/bin/commands/start.js +1 -1
- package/bin/utils/orm-map-html.js +2 -8
- package/bin/utils/project.js +2 -2
- package/core/auth/hash.js +5 -4
- package/core/auth/jwt.js +6 -57
- package/core/auth/magic-link.js +4 -5
- package/core/auth/manager.js +3 -5
- package/core/auth/oauth.js +45 -30
- package/core/auth/totp.js +5 -16
- package/core/auth/user-agent.js +1 -21
- package/core/cache/byte-size.js +123 -0
- package/core/cache/index.js +21 -0
- package/core/cache/lru.js +477 -0
- package/core/cache/tagged-lru.js +346 -0
- package/core/commands/registry.js +6 -20
- package/core/content/renderer.js +1 -13
- package/core/early-hints/index.js +267 -0
- package/core/errors/domain.js +48 -0
- package/core/errors/http.js +31 -0
- package/core/errors/index.js +10 -0
- package/core/errors/middleware.js +2 -8
- package/core/errors/normalize.js +88 -2
- package/core/events/discovery.js +6 -24
- package/core/events/dispatcher.js +2 -7
- package/core/forms/form-builder.js +1 -9
- package/core/health/index.js +41 -0
- package/core/health/middleware.js +213 -0
- package/core/health/normalize.js +140 -0
- package/core/health/probes.js +203 -0
- package/core/limits/index.js +34 -0
- package/core/limits/middleware.js +317 -0
- package/core/limits/normalize.js +222 -0
- package/core/orm/batch.js +70 -0
- package/core/orm/cache/fingerprint.js +2 -2
- package/core/orm/cache/memory-provider.js +27 -110
- package/core/orm/index.js +76 -8
- package/core/orm/json-fields.js +22 -8
- package/core/orm/model.js +10 -0
- package/core/orm/query-builder.js +63 -9
- package/core/orm/query-filters.js +393 -0
- package/core/orm/repository.js +318 -19
- package/core/orm/schema-helpers.js +8 -10
- package/core/orm/scopes.js +321 -1
- package/core/orm/transaction.js +10 -2
- package/core/orm/utils.js +4 -86
- package/core/queue/adapters/database.js +4 -8
- package/core/queue/manager.js +55 -41
- package/core/resilience/circuit-breaker.js +391 -0
- package/core/resilience/errors.js +63 -0
- package/core/resilience/index.js +53 -0
- package/core/resilience/registry.js +97 -0
- package/core/resilience/retry.js +203 -0
- package/core/schema-cache.js +9 -2
- package/core/shutdown/http-adapter.js +4 -1
- package/core/shutdown/shutdown-manager.js +132 -31
- package/core/utils/array.js +12 -0
- package/core/utils/base64url.js +8 -0
- package/core/utils/crypto.js +191 -0
- package/core/utils/ensure-leading-slash.js +6 -0
- package/core/utils/escape-html.js +7 -0
- package/core/utils/escape-regexp.js +7 -0
- package/core/utils/fetch.js +121 -0
- package/core/utils/fs.js +144 -0
- package/core/utils/get-client-ip.js +6 -0
- package/core/utils/hmac.js +6 -0
- package/core/utils/html.js +72 -0
- package/core/utils/ip.js +86 -0
- package/core/utils/json.js +98 -0
- package/core/utils/object.js +106 -0
- package/core/utils/random.js +9 -0
- package/core/utils/regex.js +77 -0
- package/core/utils/safe-compare.js +3 -0
- package/core/utils/sha256.js +6 -0
- package/core/utils/string.js +87 -0
- package/core/utils/strip-trailing-slash.js +6 -0
- package/core/utils/time.js +96 -0
- package/core/utils/timeout.js +348 -0
- package/core/utils/url.js +106 -0
- package/core/utils/walk.js +7 -0
- package/index.d.ts +627 -2
- package/index.js +158 -0
- package/package.json +1 -2
- package/plugins/admin-panel/auth.js +15 -7
- package/plugins/admin-panel/client/parts/01-state-api-breadcrumb.js +82 -10
- package/plugins/admin-panel/client/parts/05-rich-text-file-helpers.js +4 -2
- package/plugins/admin-panel/client/parts/08-record-list.js +3 -2
- package/plugins/admin-panel/client/parts/10-export-registry.js +6 -0
- package/plugins/admin-panel/core/api-extensions.js +3 -80
- package/plugins/admin-panel/index.js +1 -1
- package/plugins/admin-panel/lib/login-rate-limiter.js +15 -13
- package/plugins/admin-panel/modules/menu.js +1 -1
- package/plugins/api-key/crypto.js +3 -26
- package/plugins/api-key/scopes.js +5 -7
- package/plugins/audit-log/api-handlers.js +8 -7
- package/plugins/audit-log/middleware.js +11 -2
- package/plugins/audit-log/parse.js +3 -3
- package/plugins/basic-auth/index.js +2 -26
- package/plugins/cors.js +2 -2
- package/plugins/csrf/index.js +7 -23
- package/plugins/dashboard/app.js +2 -2
- package/plugins/dashboard/index.js +5 -5
- package/plugins/data-exchange/record-selection.js +2 -5
- package/plugins/email/api-handlers.js +5 -18
- package/plugins/email/auth-bridge.js +3 -2
- package/plugins/file-manager/admin-component.js +3 -1
- package/plugins/file-manager/core.js +34 -4
- package/plugins/health-check.js +2 -1
- package/plugins/index.js +2 -0
- package/plugins/lazy.js +5 -6
- package/plugins/mcp/auth.js +1 -13
- package/plugins/mcp/discovery.js +18 -17
- package/plugins/mcp/index.js +23 -1
- package/plugins/mcp/transports/sse.js +10 -1
- package/plugins/orm-cache-admin/admin-component.js +3 -2
- package/plugins/polar/src/api.js +11 -3
- package/plugins/polar/src/webhooks.js +7 -13
- package/plugins/rate-limit/index.js +3 -1
- package/plugins/recaptcha/helpers.js +1 -7
- package/plugins/recaptcha/verify.js +37 -23
- package/plugins/redirect/index.js +57 -7
- package/plugins/rest-resources/index.js +1 -207
- package/plugins/rls/index.js +170 -0
- package/plugins/schema-explorer/admin-component.js +4 -2
- package/plugins/schema-explorer.js +40 -29
- package/plugins/seo-checker/index.js +5 -2
- package/plugins/site-analytics/tracking.js +21 -18
- package/plugins/sitemap.js +21 -17
- package/plugins/swagger.js +13 -17
- package/plugins/upload/index.js +4 -3
- package/plugins/upload/orphan-pruner.js +4 -3
- package/plugins/webhooks/crypto.js +6 -28
- package/plugins/webhooks/dispatcher.js +14 -9
- package/plugins/webhooks/index.js +6 -0
- package/plugins/webhooks/matcher.js +28 -17
- package/plugins/webhooks/sender.js +40 -13
- package/src/app-context.js +41 -5
- package/src/dev/banner.js +6 -2
- package/src/dev-reload/index.js +47 -6
- package/src/file-router.js +1 -3
- package/src/helpers.js +180 -33
- package/src/modules/module-discovery.js +1 -9
- package/src/pages/page-loader.js +53 -1
- package/src/plugin-manager.js +90 -17
- package/src/server.js +137 -26
- package/src/services/discovery.js +19 -40
- package/src/services/executor.js +86 -25
- package/src/services/memoize.js +3 -25
- package/src/services/registry.js +6 -0
- package/src/template/precompile.js +8 -19
package/src/server.js
CHANGED
|
@@ -11,13 +11,17 @@ const { AsyncLocalStorage } = require('async_hooks');
|
|
|
11
11
|
const express = require('express');
|
|
12
12
|
const helmet = require('helmet');
|
|
13
13
|
const nunjucks = require('nunjucks');
|
|
14
|
-
const
|
|
14
|
+
const {
|
|
15
|
+
DEFAULT_TIMEOUTS,
|
|
16
|
+
normalizeTimeouts,
|
|
17
|
+
createTimeoutMiddleware,
|
|
18
|
+
} = require('../core/utils/timeout');
|
|
15
19
|
|
|
16
20
|
const { setAppContext } = require('./app-context');
|
|
17
21
|
const { mountClientRuntime } = require('./client-runtime/mount');
|
|
18
22
|
const { resolveClientRuntime } = require('./client-runtime/resolve');
|
|
19
23
|
const { mountPages, detectLocale, loadI18n, createTranslator } = require('./file-router');
|
|
20
|
-
const { configureAssets, createHelpers, getScriptInjector } = require('./helpers');
|
|
24
|
+
const { configureAssets, createHelpers, getScriptInjector, AssetManager } = require('./helpers');
|
|
21
25
|
const { createDevReloadHub } = require('./dev-reload');
|
|
22
26
|
const { createDevBundler } = require('./bundle');
|
|
23
27
|
const { registerClearHook } = require('./njk-frontmatter');
|
|
@@ -31,6 +35,14 @@ const { mountDiscoveredRoutes } = require('./routing/mount-discovered-routes');
|
|
|
31
35
|
const { discoverModuleDetails } = require('./modules/module-discovery');
|
|
32
36
|
const { ShutdownManager, NodeHttpAdapter } = require('../core/shutdown');
|
|
33
37
|
const { createCompressionMiddleware } = require('../core/compression');
|
|
38
|
+
const { createEarlyHintsMiddleware } = require('../core/early-hints');
|
|
39
|
+
const {
|
|
40
|
+
CircuitBreakerRegistry,
|
|
41
|
+
circuitBreakerRegistry,
|
|
42
|
+
getBreaker,
|
|
43
|
+
retry,
|
|
44
|
+
withRetry,
|
|
45
|
+
} = require('../core/resilience');
|
|
34
46
|
const { createFlashMiddleware } = require('../core/forms/flash');
|
|
35
47
|
const { createBouncerMiddleware } = require('../core/auth/bouncer');
|
|
36
48
|
const {
|
|
@@ -46,10 +58,13 @@ const {
|
|
|
46
58
|
RouteNotFoundError,
|
|
47
59
|
RequestAbortedError,
|
|
48
60
|
ValidationError,
|
|
61
|
+
getStatusTitle,
|
|
49
62
|
normalizeError,
|
|
50
63
|
toErrorResponseObject,
|
|
51
64
|
preferJsonErrorResponse,
|
|
52
65
|
} = require('../core/errors');
|
|
66
|
+
const { setupLimitsMiddleware } = require('../core/limits');
|
|
67
|
+
const { escapeRegExp } = require('../core/utils/regex');
|
|
53
68
|
|
|
54
69
|
// Async storage for tracking template render call stacks (circular extends guard)
|
|
55
70
|
const renderStackStorage = new AsyncLocalStorage();
|
|
@@ -487,6 +502,8 @@ function default404Html() {
|
|
|
487
502
|
* Default 500 page HTML
|
|
488
503
|
*/
|
|
489
504
|
function default500Html(err, isDev) {
|
|
505
|
+
const status = (err && typeof err.status === 'number') ? err.status : 500;
|
|
506
|
+
const title = getStatusTitle(status);
|
|
490
507
|
const detail =
|
|
491
508
|
isDev && err
|
|
492
509
|
? `<pre>${String(err.stack || err.message)
|
|
@@ -499,15 +516,15 @@ function default500Html(err, isDev) {
|
|
|
499
516
|
<head>
|
|
500
517
|
<meta charset="UTF-8" />
|
|
501
518
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
502
|
-
<title
|
|
519
|
+
<title>${status} - ${title}</title>
|
|
503
520
|
<style>${defaultErrorPageStyles()}
|
|
504
521
|
</style>
|
|
505
522
|
</head>
|
|
506
523
|
<body>
|
|
507
524
|
<div class="container">
|
|
508
525
|
<div class="card">
|
|
509
|
-
<h1
|
|
510
|
-
<p class="muted"
|
|
526
|
+
<h1>${status}</h1>
|
|
527
|
+
<p class="muted">${title}</p>
|
|
511
528
|
${detail}
|
|
512
529
|
<a href="/">← Back to Home</a>
|
|
513
530
|
</div>
|
|
@@ -589,12 +606,18 @@ function createApp(options = {}) {
|
|
|
589
606
|
plugins = [],
|
|
590
607
|
assets: assetsConfig = {},
|
|
591
608
|
errorPages = {},
|
|
592
|
-
timeout: timeoutConfig
|
|
609
|
+
timeout: timeoutConfig,
|
|
610
|
+
timeouts: timeoutsConfig,
|
|
593
611
|
auth: authManager = null,
|
|
594
612
|
setupRoutes,
|
|
595
613
|
dev: devOpts = {},
|
|
614
|
+
limits: limitsConfig = null,
|
|
615
|
+
healthCheck: healthCheckConfig = null,
|
|
596
616
|
} = options;
|
|
597
617
|
|
|
618
|
+
// Centralized global timeout configuration
|
|
619
|
+
const timeouts = normalizeTimeouts(options);
|
|
620
|
+
|
|
598
621
|
// Auto-instrument Knex queries for dev profiler
|
|
599
622
|
if (options.db && options.db.knex) {
|
|
600
623
|
attachProfilerToKnex(options.db.knex);
|
|
@@ -626,24 +649,30 @@ function createApp(options = {}) {
|
|
|
626
649
|
}
|
|
627
650
|
}
|
|
628
651
|
|
|
652
|
+
// Create Express application instance
|
|
653
|
+
const app = express();
|
|
654
|
+
|
|
629
655
|
// Create plugin manager
|
|
630
656
|
const pluginManager = createPluginManager();
|
|
631
657
|
|
|
632
658
|
// Configure asset manager
|
|
633
659
|
const projectBase = publicDir ? path.dirname(path.resolve(publicDir)) : process.cwd();
|
|
634
|
-
|
|
660
|
+
const assetOpts = {
|
|
635
661
|
publicDir: publicDir || 'public',
|
|
636
662
|
srcDir: options.srcDir || path.join(projectBase, 'src'),
|
|
637
663
|
pagesDir: pagesDir || 'pages',
|
|
638
664
|
...assetsConfig
|
|
639
|
-
}
|
|
665
|
+
};
|
|
666
|
+
const appAssetManager = new AssetManager(assetOpts);
|
|
667
|
+
app.assetManager = appAssetManager;
|
|
668
|
+
configureAssets(assetOpts);
|
|
640
669
|
|
|
641
670
|
const clientRuntime = resolveClientRuntime(options);
|
|
642
671
|
|
|
643
672
|
const shutdownConfig = {
|
|
644
673
|
enabled: true,
|
|
645
|
-
mode: 'graceful',
|
|
646
|
-
timeout: 10_000,
|
|
674
|
+
mode: isDev ? 'force' : 'graceful',
|
|
675
|
+
timeout: isDev ? 1000 : (timeouts.shutdown !== false ? timeouts.shutdown : 10_000),
|
|
647
676
|
...(options.shutdown || options.server?.shutdown || {}),
|
|
648
677
|
};
|
|
649
678
|
|
|
@@ -652,6 +681,18 @@ function createApp(options = {}) {
|
|
|
652
681
|
logger: logging ? console : null,
|
|
653
682
|
});
|
|
654
683
|
|
|
684
|
+
try {
|
|
685
|
+
// Circuit Breakers Layer initialization (isolated per application instance)
|
|
686
|
+
const appBreakers = options.breakers instanceof CircuitBreakerRegistry
|
|
687
|
+
? options.breakers
|
|
688
|
+
: new CircuitBreakerRegistry();
|
|
689
|
+
app.breakers = appBreakers;
|
|
690
|
+
app.getBreaker = (name, opts) => appBreakers.getBreaker(name, opts);
|
|
691
|
+
app.breaker = (name, opts) => appBreakers.getBreaker(name, opts);
|
|
692
|
+
shutdownManager.onShutdown(() => {
|
|
693
|
+
appBreakers.resetAll();
|
|
694
|
+
});
|
|
695
|
+
|
|
655
696
|
// Services Layer initialization
|
|
656
697
|
const servicesDirOption = options.servicesDir ?? options.services?.dir;
|
|
657
698
|
const resolvedServicesDir = servicesDirOption
|
|
@@ -664,6 +705,7 @@ function createApp(options = {}) {
|
|
|
664
705
|
servicesDir: resolvedServicesDir,
|
|
665
706
|
isDev,
|
|
666
707
|
logger: logging ? console : null,
|
|
708
|
+
timeouts,
|
|
667
709
|
});
|
|
668
710
|
|
|
669
711
|
// Auto-register built-in auth services if database is present and service is not custom-defined
|
|
@@ -696,6 +738,9 @@ function createApp(options = {}) {
|
|
|
696
738
|
queue: options.queue || null,
|
|
697
739
|
logger: logging ? console : null,
|
|
698
740
|
});
|
|
741
|
+
shutdownManager.onShutdown(() => {
|
|
742
|
+
eventDispatcher.removeAllListeners();
|
|
743
|
+
});
|
|
699
744
|
|
|
700
745
|
// Auto-bridge ORM lifecycle events (ModelEvents) to app.events ('model:created', etc.)
|
|
701
746
|
if (options.db) {
|
|
@@ -714,14 +759,27 @@ function createApp(options = {}) {
|
|
|
714
759
|
loadListeners(resolvedListenersDir, eventDispatcher, { logger: logging ? console : null });
|
|
715
760
|
}
|
|
716
761
|
|
|
717
|
-
|
|
762
|
+
// Native High-Performance In-Memory Cache (LRU + Tagged Invalidation + Byte Budget)
|
|
763
|
+
const { createTaggedLruCache } = require('../core/cache');
|
|
764
|
+
const cacheOpt = options.cache ?? options.server?.cache;
|
|
765
|
+
const appCache = cacheOpt === false ? null : createTaggedLruCache(typeof cacheOpt === 'object' ? cacheOpt : {});
|
|
766
|
+
|
|
767
|
+
if (appCache) {
|
|
768
|
+
shutdownManager.onShutdown(() => appCache.clear());
|
|
769
|
+
}
|
|
718
770
|
|
|
719
|
-
setAppContext({
|
|
771
|
+
setAppContext({
|
|
772
|
+
db: options.db ?? null,
|
|
773
|
+
shutdownManager,
|
|
774
|
+
serviceRegistry,
|
|
775
|
+
events: eventDispatcher,
|
|
776
|
+
cache: appCache,
|
|
777
|
+
});
|
|
720
778
|
|
|
721
|
-
const app = express();
|
|
722
779
|
app.serviceRegistry = serviceRegistry;
|
|
723
780
|
app.pluginManager = pluginManager;
|
|
724
781
|
app.events = eventDispatcher;
|
|
782
|
+
app.cache = appCache;
|
|
725
783
|
if (options.queue) {
|
|
726
784
|
app.queue = options.queue;
|
|
727
785
|
}
|
|
@@ -730,8 +788,10 @@ function createApp(options = {}) {
|
|
|
730
788
|
const { renderStream } = require('../core/ssr/stream');
|
|
731
789
|
const { createSseStream } = require('../core/sse/stream');
|
|
732
790
|
app.use((req, res, next) => {
|
|
733
|
-
// 1. Request draining check during graceful shutdown
|
|
734
|
-
|
|
791
|
+
// 1. Request draining check during graceful shutdown (allow health/readiness probes through)
|
|
792
|
+
const isHealthEndpoint = req.path === '/healthz' || req.path === '/readyz' || req.path === '/health' ||
|
|
793
|
+
Boolean(app.healthManager?.config && (req.path === app.healthManager.config.path || req.path === app.healthManager.config.readyPath || req.path === app.healthManager.config.combinedPath));
|
|
794
|
+
if (shutdownManager.isShuttingDown && !isHealthEndpoint) {
|
|
735
795
|
res.set('Connection', 'close');
|
|
736
796
|
if (!res.headersSent) {
|
|
737
797
|
if (preferJsonErrorResponse(req)) {
|
|
@@ -761,13 +821,23 @@ function createApp(options = {}) {
|
|
|
761
821
|
req.queue = options.queue;
|
|
762
822
|
}
|
|
763
823
|
req.events = eventDispatcher;
|
|
824
|
+
req.cache = appCache;
|
|
825
|
+
req.breakers = appBreakers;
|
|
826
|
+
req.breaker = (name, opts) => appBreakers.getBreaker(name, opts);
|
|
827
|
+
req.retry = retry;
|
|
764
828
|
req.context = {
|
|
765
829
|
req,
|
|
766
830
|
res,
|
|
767
831
|
db: options.db ?? null,
|
|
768
832
|
queue: options.queue ?? null,
|
|
769
833
|
events: eventDispatcher,
|
|
834
|
+
cache: appCache,
|
|
835
|
+
breakers: appBreakers,
|
|
836
|
+
getBreaker: (name, opts) => appBreakers.getBreaker(name, opts),
|
|
837
|
+
breaker: (name, opts) => appBreakers.getBreaker(name, opts),
|
|
838
|
+
retry,
|
|
770
839
|
app,
|
|
840
|
+
assetManager: appAssetManager,
|
|
771
841
|
serviceRegistry,
|
|
772
842
|
...(req.context || {}),
|
|
773
843
|
};
|
|
@@ -926,7 +996,7 @@ function createApp(options = {}) {
|
|
|
926
996
|
regexStr += '(.*)';
|
|
927
997
|
hasWildcard = true;
|
|
928
998
|
} else {
|
|
929
|
-
regexStr += part
|
|
999
|
+
regexStr += escapeRegExp(part);
|
|
930
1000
|
}
|
|
931
1001
|
}
|
|
932
1002
|
|
|
@@ -1177,10 +1247,21 @@ function createApp(options = {}) {
|
|
|
1177
1247
|
app.use(createCompressionMiddleware(compressionConfig));
|
|
1178
1248
|
}
|
|
1179
1249
|
}
|
|
1250
|
+
|
|
1251
|
+
// HTTP 103 Early Hints
|
|
1252
|
+
const earlyHintsOpt = options.earlyHints ?? options.server?.earlyHints ?? false;
|
|
1253
|
+
app.use(createEarlyHintsMiddleware(earlyHintsOpt));
|
|
1180
1254
|
|
|
1255
|
+
// Attach normalized timeouts to app and incoming requests
|
|
1256
|
+
app.set('timeouts', timeouts);
|
|
1257
|
+
app.use((req, res, next) => {
|
|
1258
|
+
req.timeouts = timeouts;
|
|
1259
|
+
next();
|
|
1260
|
+
});
|
|
1261
|
+
|
|
1181
1262
|
// Request timeout middleware
|
|
1182
|
-
if (
|
|
1183
|
-
app.use(
|
|
1263
|
+
if (timeouts.request !== false) {
|
|
1264
|
+
app.use(createTimeoutMiddleware(timeouts.request));
|
|
1184
1265
|
}
|
|
1185
1266
|
|
|
1186
1267
|
// Trust proxy (for correct req.ip, req.protocol behind reverse proxy; configurable via options.trustProxy)
|
|
@@ -1210,9 +1291,9 @@ function createApp(options = {}) {
|
|
|
1210
1291
|
app.set('etag', etagSetting);
|
|
1211
1292
|
}
|
|
1212
1293
|
|
|
1213
|
-
//
|
|
1214
|
-
|
|
1215
|
-
|
|
1294
|
+
// Configurable payload size limits & DoS protection
|
|
1295
|
+
const limitsOpt = options.limits ?? options.server?.limits;
|
|
1296
|
+
const activeLimits = setupLimitsMiddleware(app, limitsOpt);
|
|
1216
1297
|
|
|
1217
1298
|
// Cookie parser & Flash messages (AdonisJS & Django-inspired old input and errors)
|
|
1218
1299
|
const cookieParser = require('cookie-parser');
|
|
@@ -1222,12 +1303,23 @@ function createApp(options = {}) {
|
|
|
1222
1303
|
// Ensure default empty object for body on mutating requests if not populated
|
|
1223
1304
|
// and halt processing if request has timed out (after body parsers)
|
|
1224
1305
|
app.use((req, res, next) => {
|
|
1225
|
-
if (
|
|
1306
|
+
if (timeouts.request !== false && req.timedout) return;
|
|
1226
1307
|
if (req.body === undefined && (req.method === 'POST' || req.method === 'PUT' || req.method === 'PATCH')) {
|
|
1227
|
-
req.
|
|
1308
|
+
if (!req._skipBodyDefault) {
|
|
1309
|
+
req.body = {};
|
|
1310
|
+
}
|
|
1228
1311
|
}
|
|
1229
1312
|
next();
|
|
1230
1313
|
});
|
|
1314
|
+
|
|
1315
|
+
// Native Health & Readiness Probes (/healthz & /readyz)
|
|
1316
|
+
const { setupHealthMiddleware } = require('../core/health');
|
|
1317
|
+
const healthOpt = options.healthCheck ?? options.server?.healthCheck;
|
|
1318
|
+
setupHealthMiddleware(app, healthOpt, {
|
|
1319
|
+
db: options.db,
|
|
1320
|
+
queue: options.queue,
|
|
1321
|
+
shutdownManager,
|
|
1322
|
+
});
|
|
1231
1323
|
|
|
1232
1324
|
// Authentication middleware (if auth manager provided)
|
|
1233
1325
|
let authMiddleware = null;
|
|
@@ -1637,7 +1729,7 @@ function createApp(options = {}) {
|
|
|
1637
1729
|
|
|
1638
1730
|
// Helper to create error page context with fsy
|
|
1639
1731
|
function createErrorContext(req, extraData = {}) {
|
|
1640
|
-
const baseUrl = process.env.BASE_URL || `http://localhost:${process.env.PORT ||
|
|
1732
|
+
const baseUrl = process.env.BASE_URL || `http://localhost:${process.env.PORT || 7331}`;
|
|
1641
1733
|
const locale = detectLocale(req);
|
|
1642
1734
|
|
|
1643
1735
|
// Create fsy helpers
|
|
@@ -1664,7 +1756,8 @@ function createApp(options = {}) {
|
|
|
1664
1756
|
locale,
|
|
1665
1757
|
t,
|
|
1666
1758
|
service: (name, input, opts) =>
|
|
1667
|
-
serviceRegistry.call(name, input, { req, res: {}, fsy, locale, t, db: options.db ?? null }, opts),
|
|
1759
|
+
serviceRegistry.call(name, input, { req, res: {}, fsy, locale, t, db: options.db ?? null, timeouts }, opts),
|
|
1760
|
+
timeouts,
|
|
1668
1761
|
isDev,
|
|
1669
1762
|
url: req.url,
|
|
1670
1763
|
method: req.method,
|
|
@@ -1970,7 +2063,25 @@ function createApp(options = {}) {
|
|
|
1970
2063
|
});
|
|
1971
2064
|
};
|
|
1972
2065
|
|
|
1973
|
-
|
|
2066
|
+
Object.assign(app, {
|
|
2067
|
+
app,
|
|
2068
|
+
nunjucksEnv,
|
|
2069
|
+
pluginManager,
|
|
2070
|
+
authMiddleware,
|
|
2071
|
+
shutdownManager,
|
|
2072
|
+
events: eventDispatcher,
|
|
2073
|
+
timeouts,
|
|
2074
|
+
close: (reason) => shutdownManager.close(reason),
|
|
2075
|
+
});
|
|
2076
|
+
return app;
|
|
2077
|
+
} catch (err) {
|
|
2078
|
+
try {
|
|
2079
|
+
shutdownManager.close('startup_failure');
|
|
2080
|
+
} catch (cleanupErr) {
|
|
2081
|
+
console.warn('[webspresso] Cleanup error after startup failure:', cleanupErr?.message);
|
|
2082
|
+
}
|
|
2083
|
+
throw err;
|
|
2084
|
+
}
|
|
1974
2085
|
}
|
|
1975
2086
|
|
|
1976
2087
|
// Export for use as library
|
|
@@ -8,21 +8,10 @@ const fs = require('fs');
|
|
|
8
8
|
const path = require('path');
|
|
9
9
|
const { trimUrlPathSlashes } = require('../../core/url-path-normalize');
|
|
10
10
|
|
|
11
|
-
const
|
|
11
|
+
const { walkDirectoryDetailed } = require('../../core/utils/fs');
|
|
12
|
+
const { toCamelCase } = require('../../core/utils/string');
|
|
12
13
|
|
|
13
|
-
|
|
14
|
-
* Convert kebab-case or snake_case segment to camelCase
|
|
15
|
-
* @param {string} str
|
|
16
|
-
* @returns {string}
|
|
17
|
-
*/
|
|
18
|
-
function toCamelCase(str) {
|
|
19
|
-
if (!str) return '';
|
|
20
|
-
const parts = str.split(/[-_]+/);
|
|
21
|
-
return parts.map((part, index) => {
|
|
22
|
-
if (!part) return '';
|
|
23
|
-
return index === 0 ? part : part.charAt(0).toUpperCase() + part.slice(1);
|
|
24
|
-
}).join('');
|
|
25
|
-
}
|
|
14
|
+
const VALID_EXTENSIONS = new Set(['.js', '.mjs', '.cjs']);
|
|
26
15
|
|
|
27
16
|
/**
|
|
28
17
|
* Check if a file should be included as a service
|
|
@@ -105,36 +94,26 @@ function discoverServices(servicesDir) {
|
|
|
105
94
|
return [];
|
|
106
95
|
}
|
|
107
96
|
|
|
108
|
-
const
|
|
97
|
+
const items = walkDirectoryDetailed(servicesDir, {
|
|
98
|
+
extensions: VALID_EXTENSIONS,
|
|
99
|
+
ignorePrefixes: ['.', '_'],
|
|
100
|
+
ignoreNames: ['node_modules'],
|
|
101
|
+
ignoreTests: true,
|
|
102
|
+
});
|
|
109
103
|
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
if (entry.isDirectory()) {
|
|
122
|
-
scan(fullPath, relPath);
|
|
123
|
-
} else if (entry.isFile() && isValidServiceFile(entry.name)) {
|
|
124
|
-
const { name, aliases } = filePathToServiceName(relPath);
|
|
125
|
-
if (name) {
|
|
126
|
-
results.push({
|
|
127
|
-
name,
|
|
128
|
-
aliases,
|
|
129
|
-
filePath: fullPath,
|
|
130
|
-
relativePath: relPath.replace(/\\/g, '/'),
|
|
131
|
-
});
|
|
132
|
-
}
|
|
133
|
-
}
|
|
104
|
+
const results = [];
|
|
105
|
+
for (const item of items) {
|
|
106
|
+
const { name, aliases } = filePathToServiceName(item.relativePath);
|
|
107
|
+
if (name) {
|
|
108
|
+
results.push({
|
|
109
|
+
name,
|
|
110
|
+
aliases,
|
|
111
|
+
filePath: item.absolutePath,
|
|
112
|
+
relativePath: item.relativePath,
|
|
113
|
+
});
|
|
134
114
|
}
|
|
135
115
|
}
|
|
136
116
|
|
|
137
|
-
scan(path.resolve(servicesDir));
|
|
138
117
|
return results;
|
|
139
118
|
}
|
|
140
119
|
|
package/src/services/executor.js
CHANGED
|
@@ -17,6 +17,12 @@ const {
|
|
|
17
17
|
runWithAmbientTransaction,
|
|
18
18
|
hasAmbientTransaction,
|
|
19
19
|
} = require('../../core/orm/transaction');
|
|
20
|
+
const { ensureArray } = require('../../core/utils/object');
|
|
21
|
+
const {
|
|
22
|
+
CircuitBreaker,
|
|
23
|
+
circuitBreakerRegistry,
|
|
24
|
+
retry,
|
|
25
|
+
} = require('../../core/resilience');
|
|
20
26
|
|
|
21
27
|
const SERVICE_CALL_STACK_SYMBOL = Symbol.for('webspresso.service.call_stack');
|
|
22
28
|
|
|
@@ -93,7 +99,7 @@ async function checkServiceAuth(serviceDef, ctx, options = {}) {
|
|
|
93
99
|
if (!user) {
|
|
94
100
|
throw new UnauthorizedError(`Authentication required to execute service '${serviceDef.name}'`);
|
|
95
101
|
}
|
|
96
|
-
const roles =
|
|
102
|
+
const roles = ensureArray(user.roles || user.role);
|
|
97
103
|
if (!roles.includes(authRequirement)) {
|
|
98
104
|
throw new ForbiddenError(
|
|
99
105
|
`Insufficient permissions to execute service '${serviceDef.name}' (required role: '${authRequirement}')`
|
|
@@ -107,7 +113,7 @@ async function checkServiceAuth(serviceDef, ctx, options = {}) {
|
|
|
107
113
|
if (!user) {
|
|
108
114
|
throw new UnauthorizedError(`Authentication required to execute service '${serviceDef.name}'`);
|
|
109
115
|
}
|
|
110
|
-
const roles =
|
|
116
|
+
const roles = ensureArray(user.roles || user.role);
|
|
111
117
|
const hasAny = authRequirement.some(r => roles.includes(r));
|
|
112
118
|
if (!hasAny) {
|
|
113
119
|
throw new ForbiddenError(
|
|
@@ -185,6 +191,9 @@ async function executeService(registry, name, input = {}, ctx = {}, options = {}
|
|
|
185
191
|
registry.invalidate(subName, subInput, subCtx || executionContext);
|
|
186
192
|
executionContext.service.clearCache = (subName) =>
|
|
187
193
|
registry.clearCache(subName);
|
|
194
|
+
executionContext.breaker = (bName, bOpts) =>
|
|
195
|
+
circuitBreakerRegistry.getBreaker(bName, bOpts);
|
|
196
|
+
executionContext.retry = retry;
|
|
188
197
|
|
|
189
198
|
// Validate input
|
|
190
199
|
const validatedInput = await validateServiceInput(serviceDef.schema, input, name);
|
|
@@ -192,8 +201,52 @@ async function executeService(registry, name, input = {}, ctx = {}, options = {}
|
|
|
192
201
|
const startTime = Date.now();
|
|
193
202
|
const logger = executionContext.logger || registry.logger || null;
|
|
194
203
|
|
|
195
|
-
const timeoutConfig = options.timeout ?? serviceDef.timeout;
|
|
196
|
-
const timeoutMs = timeoutConfig
|
|
204
|
+
const timeoutConfig = options.timeout ?? serviceDef.timeout ?? executionContext?.timeouts?.service ?? registry?.timeouts?.service ?? registry?.timeout;
|
|
205
|
+
const timeoutMs = (timeoutConfig !== undefined && timeoutConfig !== null && timeoutConfig !== false)
|
|
206
|
+
? parseTtlMs(timeoutConfig)
|
|
207
|
+
: null;
|
|
208
|
+
|
|
209
|
+
// Resolve circuit breaker configuration
|
|
210
|
+
let breaker = null;
|
|
211
|
+
const cbConfig = options.skipCircuitBreaker === true
|
|
212
|
+
? null
|
|
213
|
+
: (options.circuitBreaker !== undefined ? options.circuitBreaker : serviceDef.circuitBreaker);
|
|
214
|
+
|
|
215
|
+
if (cbConfig) {
|
|
216
|
+
if (cbConfig instanceof CircuitBreaker) {
|
|
217
|
+
breaker = cbConfig;
|
|
218
|
+
} else if (typeof cbConfig === 'string') {
|
|
219
|
+
breaker = circuitBreakerRegistry.getBreaker(cbConfig);
|
|
220
|
+
} else if (typeof cbConfig === 'object' && cbConfig !== null) {
|
|
221
|
+
const breakerName = cbConfig.name || name;
|
|
222
|
+
breaker = circuitBreakerRegistry.getBreaker(breakerName, cbConfig);
|
|
223
|
+
} else if (cbConfig === true) {
|
|
224
|
+
breaker = circuitBreakerRegistry.getBreaker(name);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
// Resolve retry configuration
|
|
229
|
+
const retryConfig = options.skipRetry === true
|
|
230
|
+
? null
|
|
231
|
+
: (options.retry !== undefined ? options.retry : serviceDef.retry);
|
|
232
|
+
|
|
233
|
+
const runWithRetry = async (fn) => {
|
|
234
|
+
if (!retryConfig) {
|
|
235
|
+
return await fn();
|
|
236
|
+
}
|
|
237
|
+
const retryOpts = typeof retryConfig === 'number'
|
|
238
|
+
? { retries: retryConfig }
|
|
239
|
+
: (typeof retryConfig === 'object' && retryConfig !== null ? retryConfig : { retries: 3 });
|
|
240
|
+
|
|
241
|
+
return await retry((attempt) => fn(attempt), retryOpts);
|
|
242
|
+
};
|
|
243
|
+
|
|
244
|
+
const runWithBreaker = async (fn) => {
|
|
245
|
+
if (!breaker) {
|
|
246
|
+
return await fn(validatedInput, executionContext);
|
|
247
|
+
}
|
|
248
|
+
return await breaker.execute(fn, validatedInput, executionContext);
|
|
249
|
+
};
|
|
197
250
|
|
|
198
251
|
// Helper to execute handler with optional database transaction
|
|
199
252
|
const executeHandler = async (activeCtx) => {
|
|
@@ -227,6 +280,9 @@ async function executeService(registry, name, input = {}, ctx = {}, options = {}
|
|
|
227
280
|
registry.invalidate(subName, subInput, subCtx || txCtx);
|
|
228
281
|
txCtx.service.clearCache = (subName) =>
|
|
229
282
|
registry.clearCache(subName);
|
|
283
|
+
txCtx.breaker = (bName, bOpts) =>
|
|
284
|
+
circuitBreakerRegistry.getBreaker(bName, bOpts);
|
|
285
|
+
txCtx.retry = retry;
|
|
230
286
|
return await serviceDef.handler(validatedInput, txCtx);
|
|
231
287
|
});
|
|
232
288
|
});
|
|
@@ -236,31 +292,36 @@ async function executeService(registry, name, input = {}, ctx = {}, options = {}
|
|
|
236
292
|
};
|
|
237
293
|
|
|
238
294
|
try {
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
295
|
+
const invokeOperation = () => {
|
|
296
|
+
if (timeoutMs && timeoutMs > 0) {
|
|
297
|
+
let timerId;
|
|
298
|
+
const timeoutPromise = new Promise((_, reject) => {
|
|
299
|
+
timerId = setTimeout(() => {
|
|
300
|
+
const timeoutErr = new WebspressoError(`Service '${name}' timed out after ${timeoutMs}ms`);
|
|
301
|
+
timeoutErr.code = 'SERVICE_TIMEOUT';
|
|
302
|
+
timeoutErr.statusCode = 504;
|
|
303
|
+
timeoutErr.service = name;
|
|
304
|
+
reject(timeoutErr);
|
|
305
|
+
}, timeoutMs);
|
|
306
|
+
if (timerId && typeof timerId.unref === 'function') {
|
|
307
|
+
timerId.unref();
|
|
308
|
+
}
|
|
309
|
+
});
|
|
252
310
|
|
|
253
|
-
|
|
254
|
-
result = await Promise.race([
|
|
311
|
+
return Promise.race([
|
|
255
312
|
executeHandler(executionContext),
|
|
256
313
|
timeoutPromise,
|
|
257
|
-
])
|
|
258
|
-
|
|
259
|
-
|
|
314
|
+
]).finally(() => {
|
|
315
|
+
if (timerId) {
|
|
316
|
+
clearTimeout(timerId);
|
|
317
|
+
}
|
|
318
|
+
});
|
|
260
319
|
}
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
}
|
|
320
|
+
|
|
321
|
+
return executeHandler(executionContext);
|
|
322
|
+
};
|
|
323
|
+
|
|
324
|
+
const result = await runWithBreaker(() => runWithRetry(invokeOperation));
|
|
264
325
|
|
|
265
326
|
const duration = Date.now() - startTime;
|
|
266
327
|
if (logger && typeof logger.debug === 'function') {
|
package/src/services/memoize.js
CHANGED
|
@@ -4,36 +4,14 @@
|
|
|
4
4
|
* @module src/services/memoize
|
|
5
5
|
*/
|
|
6
6
|
|
|
7
|
+
const { parseDurationMs } = require('../../core/utils/time');
|
|
8
|
+
|
|
7
9
|
/**
|
|
8
10
|
* Parse TTL duration into milliseconds
|
|
9
11
|
* @param {string|number|boolean} ttl - Duration string ('5s', '1m', '5m', '1h', '1d'), ms number, or boolean
|
|
10
12
|
* @returns {number} Milliseconds
|
|
11
13
|
*/
|
|
12
|
-
|
|
13
|
-
if (typeof ttl === 'number') {
|
|
14
|
-
return ttl > 0 ? ttl : 60_000;
|
|
15
|
-
}
|
|
16
|
-
if (ttl === true || !ttl) {
|
|
17
|
-
return 60_000; // Default 1 minute
|
|
18
|
-
}
|
|
19
|
-
if (typeof ttl === 'string') {
|
|
20
|
-
const match = ttl.trim().match(/^(\d+)\s*([smhd])?$/i);
|
|
21
|
-
if (match) {
|
|
22
|
-
const val = parseInt(match[1], 10);
|
|
23
|
-
const unit = (match[2] || 's').toLowerCase();
|
|
24
|
-
switch (unit) {
|
|
25
|
-
case 's': return val * 1_000;
|
|
26
|
-
case 'm': return val * 60_000;
|
|
27
|
-
case 'h': return val * 3_600_000;
|
|
28
|
-
case 'd': return val * 86_400_000;
|
|
29
|
-
default: return val * 1_000;
|
|
30
|
-
}
|
|
31
|
-
}
|
|
32
|
-
const num = parseInt(ttl, 10);
|
|
33
|
-
return !Number.isNaN(num) && num > 0 ? num : 60_000;
|
|
34
|
-
}
|
|
35
|
-
return 60_000;
|
|
36
|
-
}
|
|
14
|
+
const parseTtlMs = parseDurationMs;
|
|
37
15
|
|
|
38
16
|
/**
|
|
39
17
|
* Safely deep clone an object or array to prevent cache mutation
|
package/src/services/registry.js
CHANGED
|
@@ -21,6 +21,8 @@ class ServiceRegistry {
|
|
|
21
21
|
this.servicesDir = options.servicesDir ? path.resolve(options.servicesDir) : null;
|
|
22
22
|
this.isDev = Boolean(options.isDev);
|
|
23
23
|
this.logger = options.logger || null;
|
|
24
|
+
this.timeouts = options.timeouts || null;
|
|
25
|
+
this.timeout = options.timeout !== undefined ? options.timeout : null;
|
|
24
26
|
|
|
25
27
|
/** @type {Map<string, Object>} */
|
|
26
28
|
this.services = new Map();
|
|
@@ -107,6 +109,8 @@ class ServiceRegistry {
|
|
|
107
109
|
cache: definition.cache,
|
|
108
110
|
timeout: definition.timeout,
|
|
109
111
|
transaction: definition.transaction,
|
|
112
|
+
circuitBreaker: definition.circuitBreaker,
|
|
113
|
+
retry: definition.retry,
|
|
110
114
|
};
|
|
111
115
|
|
|
112
116
|
this.services.set(name, serviceDef);
|
|
@@ -164,6 +168,8 @@ class ServiceRegistry {
|
|
|
164
168
|
cache: def.cache,
|
|
165
169
|
timeout: def.timeout,
|
|
166
170
|
transaction: def.transaction,
|
|
171
|
+
circuitBreaker: def.circuitBreaker,
|
|
172
|
+
retry: def.retry,
|
|
167
173
|
};
|
|
168
174
|
|
|
169
175
|
this.services.set(name, serviceDef);
|