@empyria/restate 0.4.17 → 0.4.18

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.md CHANGED
@@ -79,11 +79,11 @@ may observe an already-mocked value. See `test/Admin.test.js`.
79
79
  same address registers again, but only `force: true` updates its handler list. Check both against a live server when
80
80
  touching them.
81
81
 
82
- `setupRestate` registers the single complete `serviceURL` it is given (scheme included — never assemble a URL from
83
- host + port, the scheme and any proxy mapping are the caller's to state). `port` is only the listen port. `host` is a
84
- deprecated fallback (`http://host:port`) kept for consumers pinned to older call sites; the URL decision is
85
- `resolveServiceURL` (unit tested). `createRestateAdmin().setupRestate` must forward every option to `setupRestate` — it
86
- once dropped `keepDeploymentOnShutdown`/`forceRegistration`/`registrationCallbackFn`.
82
+ `setupRestate` takes ONE complete `serviceURL` (scheme and explicit port included): it is registered as given and the
83
+ endpoint listens on its port. There is deliberately no `host` or `port` option — never assemble a URL from parts, the
84
+ scheme and any mapping are the caller's to state. `parseServiceURL` validates it (unit tested).
85
+ `createRestateAdmin().setupRestate` must forward every option to `setupRestate` — it once dropped
86
+ `keepDeploymentOnShutdown`/`forceRegistration`/`registrationCallbackFn`.
87
87
 
88
88
  `setupRestate` (in `lib/Admin.js`) is not unit tested: it binds real HTTP/2 + health-check
89
89
  ports, installs process-wide `SIGTERM`/`SIGINT` handlers, and its returned `forceClose` calls
package/README.md CHANGED
@@ -122,14 +122,14 @@ endpoint, then create jobs with either:
122
122
  Cron expressions are `croner` patterns (five fields, or six with seconds for tests). The target handler is sent the
123
123
  `payload` as its input, or no input when there is none.
124
124
 
125
- ### An endpoint that does not register itself
125
+ ### Serving and registering an endpoint
126
126
 
127
- Tell `setupRestate` where Restate reaches the endpoint with one complete URL, scheme included:
128
- `setupRestate({ restateAdminURL, port: 9080, serviceURL: 'https://agent-service.internal:9080', services })`. `port` is only
129
- what the process listens on; `serviceURL` is what gets registered (it may differ behind a proxy). Without `serviceURL`
130
- nothing is registered. The old `host` option still works (registers `http://<host>:<port>`) but is deprecated.
127
+ `setupRestate({ restateAdminURL, serviceURL: 'https://agent-service.internal:9080', services })` takes one complete URL, the
128
+ address Restate reaches the endpoint at. It is registered as given and the endpoint listens on its port, so the scheme and
129
+ an explicit port are required (there is no separate host or port option); the health endpoint listens on the next port
130
+ unless `healthPort` is set.
131
131
 
132
- `setupRestate` serves, registers the deployment, and deletes it again on SIGINT/SIGTERM. Invocations in flight are
132
+ It serves, registers the deployment, and deletes it again on SIGINT/SIGTERM. Invocations in flight are
133
133
  pinned to their deployment, so deleting it strands them: a restarted process cannot finish them and they can only be
134
134
  killed. For a process restarted at the same address, pass `keepDeploymentOnShutdown: true` and `forceRegistration: true`:
135
135
  Restate keeps the deployment ID when the same address registers again (checked against Restate 1.7), running
@@ -137,8 +137,7 @@ invocations resume on the new process, and `force` updates the services and hand
137
137
  re-registration keeps the old handler list). Only compatible changes are safe this way: an invocation of a removed or
138
138
  renamed handler cannot resume.
139
139
 
140
- When something else owns
141
- registration (a supervisor that registers a process's address once and restarts the process), use
140
+ To serve without registering: when something else owns registration (a supervisor that registers a process's address once and restarts the process), use
142
141
  `serveEndpoint({port, services})` instead: it only serves. Invocations already running on a deployment are pinned to its
143
142
  address, so the deployment must survive the process stopping and come back at the same address.
144
143
 
package/lib/Admin.js CHANGED
@@ -550,7 +550,7 @@ export function sendMessageAsyncWithDiscovery({ restateAdminURL }) {
550
550
  }
551
551
 
552
552
  /**
553
- * @typedef {import('node:http2').Http2Server & {deploymentId: string, services: string[], forceClose: () => void}} RestateServer
553
+ * @typedef {import('node:http2').Http2Server & {deploymentId: string|undefined, services: string[]|undefined, forceClose: () => void}} RestateServer
554
554
  */
555
555
 
556
556
  /**
@@ -592,12 +592,9 @@ export function defineObject(def) {
592
592
  * that was removed or renamed cannot resume.
593
593
  * @param {Object} params
594
594
  * @param {string} params.restateAdminURL
595
- * @param {number} params.port Port this endpoint listens on (the bind, not the advertised address).
596
- * @param {string} [params.serviceURL] Complete URL Restate uses to reach this endpoint, scheme included
597
- * (e.g. `https://agent-service.internal:9080`). Registration happens only when it is set — the scheme and
598
- * any proxy/port mapping are the caller's to state, never guessed here.
599
- * @param {string} [params.host] @deprecated Use `serviceURL`. Only when `serviceURL` is absent: registers as
600
- * `http://<host>:<port>` (plain HTTP is assumed).
595
+ * @param {string} params.serviceURL Complete URL Restate uses to reach this endpoint, scheme and port included
596
+ * (e.g. `https://agent-service.internal:9080`). It is registered as given, and the endpoint listens on its port, so
597
+ * the port must be explicit. Scheme and port are the caller's to state, never guessed here.
601
598
  * @param {number} [params.healthPort] - Defaults to `port + 1`.
602
599
  * @param {Parameters<typeof restate.createEndpointHandler>[0]['services']} [params.services]
603
600
  * @param {() => void} [params.shutdownCallbackFn]
@@ -610,15 +607,16 @@ export function defineObject(def) {
610
607
  export async function setupRestate({
611
608
  restateAdminURL,
612
609
  serviceURL: serviceURLParam,
613
- host,
614
- port,
615
- healthPort = port + 1,
610
+ healthPort: healthPortParam,
616
611
  services = [],
617
612
  shutdownCallbackFn,
618
613
  registrationCallbackFn,
619
614
  keepDeploymentOnShutdown = false,
620
615
  forceRegistration = false,
621
616
  }) {
617
+ const { serviceURL, port } = parseServiceURL(serviceURLParam)
618
+ const healthPort = healthPortParam ?? port + 1
619
+
622
620
  const handler = restate.createEndpointHandler({ services })
623
621
 
624
622
  const server = http2.createServer(handler)
@@ -689,125 +687,121 @@ export async function setupRestate({
689
687
 
690
688
  server.listen(port, () => console.log(`Server running on ${port}`))
691
689
 
692
- const serviceURL = resolveServiceURL({ serviceURL: serviceURLParam, host, port })
693
- if (serviceURL) {
694
- /**
695
- * @param {Object} params
696
- * @param {string} params.restateAdminURL
697
- * @param {string} params.serviceURL
698
- * @param {number} [params.attempts=5]
699
- * @param {number} [params.baseDelayMs=3000]
700
- * @returns {Promise<RegisterDeploymentResponse>}
701
- */
702
- async function registerDeploymentWithRetry({
703
- restateAdminURL,
704
- serviceURL,
705
- attempts = 5,
706
- baseDelayMs = 3_000,
707
- }) {
708
- let lastErr
709
-
710
- for (let attempt = 1; attempt <= attempts; attempt++) {
690
+ /**
691
+ * @param {Object} params
692
+ * @param {string} params.restateAdminURL
693
+ * @param {string} params.serviceURL
694
+ * @param {number} [params.attempts=5]
695
+ * @param {number} [params.baseDelayMs=3000]
696
+ * @returns {Promise<RegisterDeploymentResponse>}
697
+ */
698
+ async function registerDeploymentWithRetry({
699
+ restateAdminURL,
700
+ serviceURL,
701
+ attempts = 5,
702
+ baseDelayMs = 3_000,
703
+ }) {
704
+ let lastErr
705
+
706
+ for (let attempt = 1; attempt <= attempts; attempt++) {
707
+ try {
708
+ const result = await registerDeployment({
709
+ restateAdminURL,
710
+ serviceURL,
711
+ force: forceRegistration,
712
+ })
713
+
711
714
  try {
712
- const result = await registerDeployment({
713
- restateAdminURL,
714
- serviceURL,
715
- force: forceRegistration,
716
- })
717
-
718
- try {
719
- registrationCallbackFn?.(result.id)
720
- } catch (err) {
721
- console.error(
722
- `Error in registration callback for deployment ${result.id}: ${
723
- err instanceof Error ? err.message : String(err)
724
- }`,
725
- )
726
- }
727
-
728
- return result
715
+ registrationCallbackFn?.(result.id)
729
716
  } catch (err) {
730
- lastErr = err
731
-
732
- // Deterministic — retrying won't help. Bail immediately.
733
- if (err instanceof Error && err.message.includes('META0004')) {
734
- throw err
735
- }
736
-
737
- if (attempt < attempts) {
738
- const delay = Math.min(baseDelayMs * 2 ** (attempt - 1), DELAY_CAP)
739
- console.log(
740
- `Registration attempt ${attempt}/${attempts} failed, retrying in ${delay}ms: ${
741
- err instanceof Error ? err.message : String(err)
742
- }`,
743
- )
744
- await sleep(delay)
745
- }
717
+ console.error(
718
+ `Error in registration callback for deployment ${result.id}: ${
719
+ err instanceof Error ? err.message : String(err)
720
+ }`,
721
+ )
746
722
  }
747
- }
748
723
 
749
- throw new Error(
750
- `Failed to register deployment after ${attempts} attempts: ${
751
- lastErr instanceof Error ? lastErr.message : String(lastErr)
752
- }`,
753
- )
754
- }
755
- const deployment = await registerDeploymentWithRetry({
756
- restateAdminURL,
757
- serviceURL,
758
- }).catch(console.error)
724
+ return result
725
+ } catch (err) {
726
+ lastErr = err
759
727
 
760
- isHealthy = !!deployment // Only healthy once registered
728
+ // Deterministic — retrying won't help. Bail immediately.
729
+ if (err instanceof Error && err.message.includes('META0004')) {
730
+ throw err
731
+ }
761
732
 
762
- return Object.assign(server, {
763
- deploymentId: deployment?.id,
764
- services: deployment?.services?.map((s) => s.name),
765
- forceClose,
766
- })
767
- } else {
768
- isHealthy = true
733
+ if (attempt < attempts) {
734
+ const delay = Math.min(baseDelayMs * 2 ** (attempt - 1), DELAY_CAP)
735
+ console.log(
736
+ `Registration attempt ${attempt}/${attempts} failed, retrying in ${delay}ms: ${
737
+ err instanceof Error ? err.message : String(err)
738
+ }`,
739
+ )
740
+ await sleep(delay)
741
+ }
742
+ }
743
+ }
744
+
745
+ throw new Error(
746
+ `Failed to register deployment after ${attempts} attempts: ${
747
+ lastErr instanceof Error ? lastErr.message : String(lastErr)
748
+ }`,
749
+ )
769
750
  }
751
+ const deployment = await registerDeploymentWithRetry({
752
+ restateAdminURL,
753
+ serviceURL,
754
+ }).catch(console.error)
755
+
756
+ isHealthy = !!deployment // Only healthy once registered
770
757
 
771
758
  return Object.assign(server, {
772
- deploymentId: 'NA',
773
- services: [],
759
+ deploymentId: deployment?.id,
760
+ services: deployment?.services?.map((s) => s.name),
774
761
  forceClose,
775
762
  })
776
763
  }
777
764
 
778
765
  /**
779
- * The URL `setupRestate` registers with Restate: `serviceURL` as given (validated as an absolute http(s) URL),
780
- * else the deprecated `host` + `port` pair as `http://host:port`, else `undefined` (no registration).
781
- * @param {{serviceURL?: string, host?: string, port?: number}} params
782
- * @returns {string|undefined}
783
- * @throws {Error} If `serviceURL` is not an absolute http(s) URL
766
+ * Validates the URL `setupRestate` registers with Restate and returns it with the port the endpoint listens on.
767
+ * @param {string} serviceURL Complete http(s) URL including an explicit port
768
+ * @returns {{serviceURL: string, port: number}} `serviceURL` unchanged
769
+ * @throws {Error} If it is missing, not an absolute http(s) URL, or has no explicit port (the scheme's default would
770
+ * be a guess)
784
771
  */
785
- export function resolveServiceURL({ serviceURL, host, port }) {
786
- if (serviceURL) {
787
- let url
788
- try {
789
- url = new URL(serviceURL)
790
- } catch {
791
- throw new Error(
792
- `serviceURL must be a complete URL including http:// or https://, got '${serviceURL}'`,
793
- )
794
- }
795
- if (url.protocol !== 'http:' && url.protocol !== 'https:') {
796
- throw new Error(`serviceURL must use http or https, got '${serviceURL}'`)
797
- }
798
- return serviceURL
772
+ export function parseServiceURL(serviceURL) {
773
+ if (!serviceURL) {
774
+ throw new Error(
775
+ 'setupRestate needs `serviceURL`: the complete URL (scheme and port) Restate reaches this endpoint at',
776
+ )
777
+ }
778
+ let url
779
+ try {
780
+ url = new URL(serviceURL)
781
+ } catch {
782
+ throw new Error(
783
+ `serviceURL must be a complete URL including http:// or https://, got '${serviceURL}'`,
784
+ )
785
+ }
786
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') {
787
+ throw new Error(`serviceURL must use http or https, got '${serviceURL}'`)
788
+ }
789
+ if (!url.port) {
790
+ throw new Error(
791
+ `serviceURL '${serviceURL}' has no explicit port: the endpoint listens on the port in the URL`,
792
+ )
799
793
  }
800
- return host && port ? `http://${host}:${port}` : undefined
794
+ return { serviceURL, port: Number(url.port) }
801
795
  }
802
796
 
803
797
  /**
804
- * Whether `setupRestate`'s shutdown removes the deployment: only a real one (registered, not `'NA'`), and not when the
805
- * caller keeps it for the next start.
798
+ * Whether `setupRestate`'s shutdown removes the deployment: only one that registered (`deploymentId` is undefined when registration
799
+ * failed), and not when the caller keeps it for the next start.
806
800
  * @param {{deploymentId: string|undefined, keepDeploymentOnShutdown?: boolean}} params
807
801
  * @returns {boolean}
808
802
  */
809
803
  export function shouldDeleteOnShutdown({ deploymentId, keepDeploymentOnShutdown = false }) {
810
- return Boolean(deploymentId) && deploymentId !== 'NA' && !keepDeploymentOnShutdown
804
+ return Boolean(deploymentId) && !keepDeploymentOnShutdown
811
805
  }
812
806
 
813
807
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@empyria/restate",
3
- "version": "0.4.17",
3
+ "version": "0.4.18",
4
4
  "description": "Restate.dev helpers for the Empyria nanoservice framework",
5
5
  "license": "MIT",
6
6
  "author": "Imre Fazekas <imre.fazekas@icloud.com>",
@@ -21,7 +21,7 @@ import {
21
21
  sendMessageAsyncWithDiscovery,
22
22
  registerDeployment,
23
23
  shouldDeleteOnShutdown,
24
- resolveServiceURL,
24
+ parseServiceURL,
25
25
  sendMessageAsynSafe,
26
26
  defineWorkflow,
27
27
  defineService,
@@ -543,28 +543,32 @@ describe('registerDeployment', () => {
543
543
  })
544
544
  })
545
545
 
546
- describe('resolveServiceURL', () => {
547
- test('uses a complete serviceURL as given, scheme included', () => {
548
- expect(
549
- resolveServiceURL({ serviceURL: 'https://svc.example.com:9443/base', port: 9080 }),
550
- ).toBe('https://svc.example.com:9443/base')
551
- })
552
-
553
- test('serviceURL wins over the deprecated host', () => {
554
- expect(resolveServiceURL({ serviceURL: 'https://a', host: 'b', port: 1 })).toBe('https://a')
546
+ describe('parseServiceURL', () => {
547
+ test('returns the URL unchanged with the port it carries', () => {
548
+ expect(parseServiceURL('http://agent-service:9080')).toEqual({
549
+ serviceURL: 'http://agent-service:9080',
550
+ port: 9080,
551
+ })
552
+ expect(parseServiceURL('https://svc.example.com:9443/base')).toEqual({
553
+ serviceURL: 'https://svc.example.com:9443/base',
554
+ port: 9443,
555
+ })
555
556
  })
556
557
 
557
- test('falls back to http://host:port for the deprecated host', () => {
558
- expect(resolveServiceURL({ host: 'svc', port: 9080 })).toBe('http://svc:9080')
558
+ test('requires a serviceURL', () => {
559
+ expect(() => parseServiceURL(undefined)).toThrow(/needs `serviceURL`/)
560
+ expect(() => parseServiceURL('')).toThrow(/needs `serviceURL`/)
559
561
  })
560
562
 
561
- test('returns undefined (no registration) when nothing is given', () => {
562
- expect(resolveServiceURL({ port: 9080 })).toBeUndefined()
563
+ test('rejects a URL without a scheme or with a non-http scheme', () => {
564
+ expect(() => parseServiceURL('agent-service:9080')).toThrow(/http/)
565
+ expect(() => parseServiceURL('not a url')).toThrow(/complete URL/)
566
+ expect(() => parseServiceURL('ftp://svc:21')).toThrow(/http or https/)
563
567
  })
564
568
 
565
- test('rejects a URL without a scheme or with a non-http scheme', () => {
566
- expect(() => resolveServiceURL({ serviceURL: 'svc:9080' })).toThrow(/complete URL|http/)
567
- expect(() => resolveServiceURL({ serviceURL: 'ftp://svc' })).toThrow(/http or https/)
569
+ test('refuses to guess the scheme default when the URL has no explicit port', () => {
570
+ expect(() => parseServiceURL('https://svc.example.com')).toThrow(/no explicit port/)
571
+ expect(() => parseServiceURL('http://svc:80')).toThrow(/no explicit port/)
568
572
  })
569
573
  })
570
574
 
@@ -580,7 +584,7 @@ describe('shouldDeleteOnShutdown', () => {
580
584
  })
581
585
 
582
586
  test('never deletes without a real deployment', () => {
583
- for (const deploymentId of [undefined, '', 'NA']) {
587
+ for (const deploymentId of [undefined, '']) {
584
588
  expect(shouldDeleteOnShutdown({ deploymentId })).toBe(false)
585
589
  }
586
590
  })