@restatedev/sessions 0.11.1 → 0.12.0

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.
Files changed (96) hide show
  1. package/README.md +330 -178
  2. package/dist/addon.d.ts +1 -0
  3. package/dist/addon.d.ts.map +1 -1
  4. package/dist/addon.js.map +1 -1
  5. package/dist/calls.d.ts +28 -28
  6. package/dist/calls.d.ts.map +1 -1
  7. package/dist/calls.js +25 -25
  8. package/dist/calls.js.map +1 -1
  9. package/dist/database.d.ts +90 -166
  10. package/dist/database.d.ts.map +1 -1
  11. package/dist/database.js +137 -249
  12. package/dist/database.js.map +1 -1
  13. package/dist/driver.d.ts +129 -126
  14. package/dist/driver.d.ts.map +1 -1
  15. package/dist/driver.js +337 -276
  16. package/dist/driver.js.map +1 -1
  17. package/dist/endpoint.d.ts +47 -5
  18. package/dist/endpoint.d.ts.map +1 -1
  19. package/dist/endpoint.js +175 -60
  20. package/dist/endpoint.js.map +1 -1
  21. package/dist/handler.d.ts +20 -17
  22. package/dist/handler.d.ts.map +1 -1
  23. package/dist/handler.js +161 -127
  24. package/dist/handler.js.map +1 -1
  25. package/dist/host.d.ts +29 -0
  26. package/dist/host.d.ts.map +1 -0
  27. package/dist/host.js +2 -0
  28. package/dist/host.js.map +1 -0
  29. package/dist/index.d.ts +1 -1
  30. package/dist/index.d.ts.map +1 -1
  31. package/dist/index.js +5 -26
  32. package/dist/index.js.map +1 -1
  33. package/dist/internal.d.ts +11 -11
  34. package/dist/internal.d.ts.map +1 -1
  35. package/dist/internal.js +20 -16
  36. package/dist/internal.js.map +1 -1
  37. package/dist/link.d.ts +1 -2
  38. package/dist/link.d.ts.map +1 -1
  39. package/dist/link.js +4 -5
  40. package/dist/link.js.map +1 -1
  41. package/dist/log.d.ts +14 -0
  42. package/dist/log.d.ts.map +1 -0
  43. package/dist/log.js +21 -0
  44. package/dist/log.js.map +1 -0
  45. package/dist/object.d.ts +217 -142
  46. package/dist/object.d.ts.map +1 -1
  47. package/dist/object.js +195 -241
  48. package/dist/object.js.map +1 -1
  49. package/dist/platform.d.ts +0 -1
  50. package/dist/platform.d.ts.map +1 -1
  51. package/dist/platform.js +4 -6
  52. package/dist/platform.js.map +1 -1
  53. package/dist/schema.d.ts +14 -22
  54. package/dist/schema.d.ts.map +1 -1
  55. package/dist/schema.js +31 -69
  56. package/dist/schema.js.map +1 -1
  57. package/dist/serve.d.ts +11 -17
  58. package/dist/serve.d.ts.map +1 -1
  59. package/dist/serve.js +21 -39
  60. package/dist/serve.js.map +1 -1
  61. package/dist/session.d.ts +58 -236
  62. package/dist/session.d.ts.map +1 -1
  63. package/dist/session.js +206 -513
  64. package/dist/session.js.map +1 -1
  65. package/dist/stop.d.ts +59 -0
  66. package/dist/stop.d.ts.map +1 -0
  67. package/dist/stop.js +220 -0
  68. package/dist/stop.js.map +1 -0
  69. package/dist/vm.d.ts +108 -29
  70. package/dist/vm.d.ts.map +1 -1
  71. package/dist/vm.js +43 -10
  72. package/dist/vm.js.map +1 -1
  73. package/package.json +4 -4
  74. package/src/addon.ts +1 -0
  75. package/src/calls.ts +51 -47
  76. package/src/database.ts +195 -339
  77. package/src/driver.ts +379 -315
  78. package/src/endpoint.ts +217 -62
  79. package/src/handler.ts +183 -164
  80. package/src/host.ts +28 -0
  81. package/src/index.ts +6 -26
  82. package/src/internal.ts +28 -39
  83. package/src/link.ts +4 -5
  84. package/src/log.ts +42 -0
  85. package/src/object.ts +379 -335
  86. package/src/platform.ts +4 -6
  87. package/src/schema.ts +37 -103
  88. package/src/serve.ts +20 -41
  89. package/src/session.ts +236 -613
  90. package/src/stop.ts +225 -0
  91. package/src/vm.ts +151 -55
  92. package/dist/scope.d.ts +0 -38
  93. package/dist/scope.d.ts.map +0 -1
  94. package/dist/scope.js +0 -55
  95. package/dist/scope.js.map +0 -1
  96. package/src/scope.ts +0 -78
package/dist/internal.js CHANGED
@@ -1,19 +1,23 @@
1
- // For tests: an attempt's session over a context of their own, the store's
2
- // fault injection, and a database over a store of their own. For this
3
- // repository's libraries: the schemas their tables are in,
4
- // databases of their own, and the Restate SDK as @restatedev/sessions runs it (its
5
- // own copy, so that a library's journaled handlers serve beside its objects).
1
+ // Internal exports. For tests: attempts and databases over their own hosts
2
+ // and stores. For the libraries in this repository: schemas, extra databases,
3
+ // keep-alive scopes, and the copy of the Restate SDK that @restatedev/sessions
4
+ // runs, so that journaled handlers of a library serve beside its objects.
6
5
  export * as sdk from '@restatedev/restate-sdk';
7
6
  export { ensureSchemas, Schema } from './schema.js';
8
- export { asDatabase, lazyDatabase, database, reset, deferSql, undeferSql, rideCommit, flushRiders, Attempt, withAttempt, } from './session.js';
9
- export { Link } from './link.js';
10
- export { ScopeKey } from './scope.js';
11
- export { open } from './database.js';
12
- // The attempt on the explicit recovery VM, for the tests that drive one.
13
- export { AttemptDriver, AttemptFailed, AttemptShutDown } from './driver.js';
14
- export { Vm, isShutDown } from './vm.js';
15
- export { serveSession, servedHere } from './handler.js';
16
- export { needing, served } from './serve.js';
17
- export { invokeRoute, patchEndpoint } from './endpoint.js';
18
- export { attach, cancelCalls, cancelled, configOf, contextOf, definitionOf, HEAD_KEY, invoke, start, withStoreWrapper, } from './object.js';
7
+ export { asDatabase, lazyDatabase, database, Attempt } from './session.js';
8
+ export { open, } from './database.js';
9
+ // For tests that drive an attempt on the VM.
10
+ export { AttemptDriver, AttemptShutDown } from './driver.js';
11
+ // For test attempts, and for integrations whose framework hooks hold scopes open (see stop.ts).
12
+ export { locateScopes, Stop } from './stop.js';
13
+ export { Vm } from './vm.js';
14
+ export { served } from './serve.js';
15
+ export { configOf, contextOf, HEAD_KEY, invoke, openScope, withAttempt } from './object.js';
16
+ // The explicit recovery protocol: its content type, the discovery manifest
17
+ // this package serves, and the end of the attempts a process serves when it
18
+ // goes away (endpoint.ts).
19
+ export { goAway, CONTENT_TYPE } from './handler.js';
20
+ export { manifestV6 } from './endpoint.js';
21
+ // What the protocol adds beyond calls and sends, for libraries (provisional).
22
+ export { invocationState, readSignal, sendSignal, flush } from './object.js';
19
23
  //# sourceMappingURL=internal.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"internal.js","sourceRoot":"","sources":["../src/internal.ts"],"names":[],"mappings":"AAAA,2EAA2E;AAC3E,sEAAsE;AACtE,2DAA2D;AAC3D,mFAAmF;AACnF,8EAA8E;AAC9E,OAAO,KAAK,GAAG,MAAM,yBAAyB,CAAC;AAC/C,OAAO,EAAE,aAAa,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACpD,OAAO,EACL,UAAU,EACV,YAAY,EACZ,QAAQ,EACR,KAAK,EACL,QAAQ,EACR,UAAU,EACV,UAAU,EACV,WAAW,EACX,OAAO,EACP,WAAW,GACZ,MAAM,cAAc,CAAC;AAEtB,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AACtC,OAAO,EAAE,IAAI,EAAyE,MAAM,eAAe,CAAC;AAC5G,yEAAyE;AACzE,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAC5E,OAAO,EAAE,EAAE,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACzC,OAAO,EAAE,YAAY,EAAE,UAAU,EAAe,MAAM,cAAc,CAAC;AACrE,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,YAAY,CAAC;AAC7C,OAAO,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAC3D,OAAO,EACL,MAAM,EACN,WAAW,EACX,SAAS,EACT,QAAQ,EACR,SAAS,EACT,YAAY,EACZ,QAAQ,EACR,MAAM,EACN,KAAK,EACL,gBAAgB,GAEjB,MAAM,aAAa,CAAC"}
1
+ {"version":3,"file":"internal.js","sourceRoot":"","sources":["../src/internal.ts"],"names":[],"mappings":"AAAA,2EAA2E;AAC3E,8EAA8E;AAC9E,+EAA+E;AAC/E,0EAA0E;AAC1E,OAAO,KAAK,GAAG,MAAM,yBAAyB,CAAC;AAC/C,OAAO,EAAE,aAAa,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACpD,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAC3E,OAAO,EACL,IAAI,GAOL,MAAM,eAAe,CAAC;AACvB,6CAA6C;AAC7C,OAAO,EAAE,aAAa,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAE7D,gGAAgG;AAChG,OAAO,EAAE,YAAY,EAAc,IAAI,EAAE,MAAM,WAAW,CAAC;AAC3D,OAAO,EAAE,EAAE,EAAE,MAAM,SAAS,CAAC;AAC7B,OAAO,EAAE,MAAM,EAAE,MAAM,YAAY,CAAC;AACpC,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC5F,2EAA2E;AAC3E,4EAA4E;AAC5E,2BAA2B;AAC3B,OAAO,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AACpD,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC3C,8EAA8E;AAC9E,OAAO,EAAE,eAAe,EAAE,UAAU,EAAE,UAAU,EAAE,KAAK,EAAwB,MAAM,aAAa,CAAC"}
package/dist/link.d.ts CHANGED
@@ -1,8 +1,7 @@
1
- /** A link of one kind, on the objects that have one. */
2
1
  export declare class Link<T> {
3
2
  private readonly key;
4
3
  constructor(what: string);
5
- /** `owner`, linked to `value`: once, as it is made (before it is frozen). */
4
+ /** Link `owner` to `value`, once, before it is frozen. */
6
5
  on<O extends object>(owner: O, value: T): O;
7
6
  /** What `owner` is linked to, if it has this link. */
8
7
  of(owner: object): T | undefined;
@@ -1 +1 @@
1
- {"version":3,"file":"link.d.ts","sourceRoot":"","sources":["../src/link.ts"],"names":[],"mappings":"AAIA,wDAAwD;AACxD,qBAAa,IAAI,CAAC,CAAC;IACjB,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAS;IAE7B,YAAY,IAAI,EAAE,MAAM,EAEvB;IAED,6EAA6E;IAC7E,EAAE,CAAC,CAAC,SAAS,MAAM,EAAE,KAAK,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,GAAG,CAAC,CAE1C;IAED,sDAAsD;IACtD,EAAE,CAAC,KAAK,EAAE,MAAM,GAAG,CAAC,GAAG,SAAS,CAE/B;CACF"}
1
+ {"version":3,"file":"link.d.ts","sourceRoot":"","sources":["../src/link.ts"],"names":[],"mappings":"AAIA,qBAAa,IAAI,CAAC,CAAC;IACjB,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAS;IAE7B,YAAY,IAAI,EAAE,MAAM,EAEvB;IAED,0DAA0D;IAC1D,EAAE,CAAC,CAAC,SAAS,MAAM,EAAE,KAAK,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,GAAG,CAAC,CAE1C;IAED,sDAAsD;IACtD,EAAE,CAAC,KAAK,EAAE,MAAM,GAAG,CAAC,GAAG,SAAS,CAE/B;CACF"}
package/dist/link.js CHANGED
@@ -1,13 +1,12 @@
1
- // A private link on the objects this code makes: set once, as it makes one,
2
- // and read by its code alone (a database's session, a transaction's reset, a
3
- // definition's own). Not enumerable, so the object reads as its fields alone.
4
- /** A link of one kind, on the objects that have one. */
1
+ // A private link from an object this package makes to a value (the attempt
2
+ // behind a `ctx.db`, the stop of a context): set once at creation and read
3
+ // only by this package. Not enumerable, so the object shows only its fields.
5
4
  export class Link {
6
5
  key;
7
6
  constructor(what) {
8
7
  this.key = Symbol(what);
9
8
  }
10
- /** `owner`, linked to `value`: once, as it is made (before it is frozen). */
9
+ /** Link `owner` to `value`, once, before it is frozen. */
11
10
  on(owner, value) {
12
11
  return Object.defineProperty(owner, this.key, { value });
13
12
  }
package/dist/link.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"link.js","sourceRoot":"","sources":["../src/link.ts"],"names":[],"mappings":"AAAA,4EAA4E;AAC5E,6EAA6E;AAC7E,8EAA8E;AAE9E,wDAAwD;AACxD,MAAM,OAAO,IAAI;IACE,GAAG,CAAS;IAE7B,YAAY,IAAY;QACtB,IAAI,CAAC,GAAG,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC;IAC1B,CAAC;IAED,6EAA6E;IAC7E,EAAE,CAAmB,KAAQ,EAAE,KAAQ;QACrC,OAAO,MAAM,CAAC,cAAc,CAAC,KAAK,EAAE,IAAI,CAAC,GAAG,EAAE,EAAE,KAAK,EAAE,CAAC,CAAC;IAC3D,CAAC;IAED,sDAAsD;IACtD,EAAE,CAAC,KAAa;QACd,OAAQ,KAAuC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IAC5D,CAAC;CACF"}
1
+ {"version":3,"file":"link.js","sourceRoot":"","sources":["../src/link.ts"],"names":[],"mappings":"AAAA,2EAA2E;AAC3E,2EAA2E;AAC3E,6EAA6E;AAE7E,MAAM,OAAO,IAAI;IACE,GAAG,CAAS;IAE7B,YAAY,IAAY;QACtB,IAAI,CAAC,GAAG,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC;IAC1B,CAAC;IAED,0DAA0D;IAC1D,EAAE,CAAmB,KAAQ,EAAE,KAAQ;QACrC,OAAO,MAAM,CAAC,cAAc,CAAC,KAAK,EAAE,IAAI,CAAC,GAAG,EAAE,EAAE,KAAK,EAAE,CAAC,CAAC;IAC3D,CAAC;IAED,sDAAsD;IACtD,EAAE,CAAC,KAAa;QACd,OAAQ,KAAuC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IAC5D,CAAC;CACF"}
package/dist/log.d.ts ADDED
@@ -0,0 +1,14 @@
1
+ import type * as restate from '@restatedev/restate-sdk';
2
+ /** The invocation a line is about. */
3
+ export interface Invocation {
4
+ id: string;
5
+ service: string;
6
+ handler: string;
7
+ }
8
+ /** A line at `level`, about `invocation` if there is one. */
9
+ export type Log = (level: 'info' | 'warn' | 'error', message: string, invocation?: Invocation) => void;
10
+ /** Lines through `transport`, as the SDK's own system lines go, with the invocation as the SDK names one. */
11
+ export declare function logOf(transport: restate.LoggerTransport): Log;
12
+ /** Logs nothing: for a caller that gives no logger (a test's). */
13
+ export declare const silent: Log;
14
+ //# sourceMappingURL=log.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"log.d.ts","sourceRoot":"","sources":["../src/log.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,KAAK,OAAO,MAAM,yBAAyB,CAAC;AAExD,sCAAsC;AACtC,MAAM,WAAW,UAAU;IACzB,EAAE,EAAE,MAAM,CAAC;IACX,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,6DAA6D;AAC7D,MAAM,MAAM,GAAG,GAAG,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,UAAU,KAAK,IAAI,CAAC;AAEvG,6GAA6G;AAC7G,wBAAgB,KAAK,CAAC,SAAS,EAAE,OAAO,CAAC,eAAe,GAAG,GAAG,CAoB7D;AAED,kEAAkE;AAClE,eAAO,MAAM,MAAM,EAAE,GAAc,CAAC"}
package/dist/log.js ADDED
@@ -0,0 +1,21 @@
1
+ /** Lines through `transport`, as the SDK's own system lines go, with the invocation as the SDK names one. */
2
+ export function logOf(transport) {
3
+ return (level, message, invocation) => transport({
4
+ source: 'SYSTEM',
5
+ level: level,
6
+ replaying: false,
7
+ ...(invocation === undefined
8
+ ? {}
9
+ : {
10
+ context: {
11
+ invocationId: invocation.id,
12
+ serviceName: invocation.service,
13
+ handlerName: invocation.handler,
14
+ invocationTarget: `${invocation.service}/${invocation.handler}`,
15
+ },
16
+ }),
17
+ }, `@restatedev/sessions: ${message}`);
18
+ }
19
+ /** Logs nothing: for a caller that gives no logger (a test's). */
20
+ export const silent = () => { };
21
+ //# sourceMappingURL=log.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"log.js","sourceRoot":"","sources":["../src/log.ts"],"names":[],"mappings":"AAiBA,6GAA6G;AAC7G,MAAM,UAAU,KAAK,CAAC,SAAkC;IACtD,OAAO,CAAC,KAAK,EAAE,OAAO,EAAE,UAAU,EAAE,EAAE,CACpC,SAAS,CACP;QACE,MAAM,EAAE,QAA6B;QACrC,KAAK,EAAE,KAAgC;QACvC,SAAS,EAAE,KAAK;QAChB,GAAG,CAAC,UAAU,KAAK,SAAS;YAC1B,CAAC,CAAC,EAAE;YACJ,CAAC,CAAC;gBACE,OAAO,EAAE;oBACP,YAAY,EAAE,UAAU,CAAC,EAAE;oBAC3B,WAAW,EAAE,UAAU,CAAC,OAAO;oBAC/B,WAAW,EAAE,UAAU,CAAC,OAAO;oBAC/B,gBAAgB,EAAE,GAAG,UAAU,CAAC,OAAO,IAAI,UAAU,CAAC,OAAO,EAAE;iBAChE;aACF,CAAC;KACP,EACD,yBAAyB,OAAO,EAAE,CACnC,CAAC;AACN,CAAC;AAED,kEAAkE;AAClE,MAAM,CAAC,MAAM,MAAM,GAAQ,GAAG,EAAE,GAAE,CAAC,CAAC"}
package/dist/object.d.ts CHANGED
@@ -1,185 +1,270 @@
1
1
  import * as restate from '@restatedev/restate-sdk';
2
- import type { Serde, VirtualObjectDefinition } from '@restatedev/restate-sdk-core';
3
- import { type CallOptions, type Rpc, type Send, type Target } from './calls.ts';
4
- import type { DatabaseReader, Store, Working } from './database.ts';
2
+ import { type Serde, type VirtualObjectDefinition } from '@restatedev/restate-sdk-core';
3
+ import { type Rpc, type Send } from './calls.ts';
4
+ import type { DatabaseReader, Stoppable, Suspendable, Working } from './database.ts';
5
5
  import { type Step } from './schema.ts';
6
- import { type Database, type ObjectConfig, type SqlHost } from './session.ts';
6
+ import type { AttemptHost } from './host.ts';
7
+ import { type Database, Attempt, type ObjectConfig } from './session.ts';
8
+ import type { Scope } from './stop.ts';
9
+ /** A session object's request: the SDK's, with the number of the attempt, from 1. */
10
+ export type SessionRequest = restate.Request & {
11
+ readonly attempt: number;
12
+ };
7
13
  /**
8
- * The context of a session object's handler. A handler runs in attempts:
9
- * Restate starts a new one after a crash, a retryable error or a
10
- * suspension, and each runs the handler from its first line, finding what
11
- * the attempts before it committed. Its operations can be awaited together
14
+ * The context of a session object's handler. A handler runs in attempts.
15
+ * Restate starts a new attempt after a crash, a retryable error or a
16
+ * shutdown of the attempt. Each attempt runs the handler from its first
17
+ * line and finds what earlier attempts committed. Operations can be awaited together
12
18
  * (`Promise.all`, `Promise.race`).
13
19
  */
14
20
  export interface SessionContext {
15
- /** The session's key. */
21
+ /** The key of this session object. */
16
22
  readonly key: string;
17
- /** The request: its id (the same on every attempt), headers, target, and the attempt's signal. */
18
- readonly request: restate.Request;
23
+ /** The request: id (the same on every attempt), headers, target, the attempt's number and `attemptCompletedSignal`. */
24
+ readonly request: SessionRequest;
19
25
  /**
20
26
  * The key's database. Each statement outside a transaction is its own
21
- * commit, and `db.transaction` groups several; a commit is durable when
27
+ * commit, and `db.transaction` groups several. A commit is durable when
22
28
  * its promise resolves. Calls run one at a time, in call order.
23
29
  */
24
30
  readonly db: Database;
25
31
  /** Calls, typed (`ctx.rpc(object, key).handler(input)`) or literal. */
26
32
  readonly rpc: Rpc;
27
- /** Sends, made at once; a transaction's (`tx.send`) are made once it commits. */
33
+ /** Sends, made immediately. A transaction's sends (`tx.send`) are made when it commits. */
28
34
  readonly send: Send;
29
- /** Cancel an invocation, by its id: see {@link Cancel}. */
35
+ /** Cancel an invocation by its id: see {@link Cancel}. */
30
36
  readonly cancel: Cancel;
31
37
  /**
32
- * Run `fn`, keeping the attempt alive while it runs: for work outside
33
- * Restate that may outlast Restate's inactivity timeout (a minute, by
34
- * default), such as a model's request.
38
+ * Run `fn` and keep the attempt alive while it runs: for work outside
39
+ * Restate that may outlast Restate's inactivity timeout (a minute by
40
+ * default), such as a model request.
35
41
  *
36
42
  * const reply = await ctx.working(() => model.generate(prompt));
37
43
  *
38
- * Outside it, an attempt Restate hears nothing from for that long is shut
39
- * down: it suspends on the calls it waits for, and a new attempt runs the
40
- * handler from the start when one answers (or at once, if it waits for
41
- * none). So a wait of days holds no process, and work cut off that way is
42
- * done again. Inside it, the attempt sends a heartbeat every 20 seconds
43
- * (`RESTATE_SESSIONS_HEARTBEAT`, in milliseconds), whatever it waits for:
44
- * keep a long wait on Restate (a call, a signal) out of it. The database's
45
- * own calls keep the attempt alive by themselves.
44
+ * The work runs to its end. A cancellation reaches the handler as a
45
+ * `CancelledError`: pending `ctx.rpc` results reject with it, or else the
46
+ * next database call or `ctx.rpc` fails with it, before anything is
47
+ * written or sent. `ctx.send` never fails with it. To stop the work
48
+ * itself, use {@link stoppable}.
49
+ *
50
+ * Outside `working`, Restate shuts down an attempt it hears nothing from
51
+ * for that timeout. The attempt suspends on the calls it waits for, and a
52
+ * new attempt runs the handler from the start when one answers (or
53
+ * immediately, if it waits for none). So a wait of days holds no process,
54
+ * and work cut off this way is done again.
55
+ *
56
+ * Inside `working`, the attempt sends a heartbeat whenever it has been
57
+ * silent for a third of the handler's inactivity timeout (20 seconds for
58
+ * the default minute; `RESTATE_SESSIONS_HEARTBEAT`, in milliseconds,
59
+ * overrides it), whatever it waits for.
60
+ * Keep a long wait on Restate (a call, a signal) out of it, or wrap it in
61
+ * {@link suspendable}. Database calls keep the attempt alive by themselves.
46
62
  */
47
63
  readonly working: Working;
64
+ /**
65
+ * {@link working}, with a signal that stops the work:
66
+ *
67
+ * const reply = await ctx.stoppable((signal) => model.generate(prompt, { signal }));
68
+ *
69
+ * The signal aborts with the `CancelledError` when Restate cancels the
70
+ * invocation, or with the error that ended the attempt if that comes
71
+ * first. It aborts only once: after a cancellation,
72
+ * `request.attemptCompletedSignal` tells when the attempt ends. A scope
73
+ * opened after either event gets an aborted signal.
74
+ *
75
+ * A cancellation that arrives while a scope is open, or is still owed when
76
+ * one opens, goes to the work through the signal, and not to the next
77
+ * database call or `ctx.rpc`. So the database calls the work makes as it
78
+ * stops are stored.
79
+ *
80
+ * Once a cancellation reaches the handler (through this signal or a failed
81
+ * call), a handler that then fails ends the invocation as cancelled,
82
+ * whatever it threw. One that returns answers it. With
83
+ * `explicitCancellation`, the signal aborts and nothing else happens: the
84
+ * handler decides how it ends.
85
+ */
86
+ readonly stoppable: Stoppable;
87
+ /**
88
+ * Run `fn` while the {@link working} and {@link stoppable} scopes around
89
+ * the call (at any depth) do not keep the attempt alive, until `fn`
90
+ * settles: for a wait on Restate inside kept-alive work, such as a
91
+ * framework tool that calls another service.
92
+ *
93
+ * await ctx.working(async () => {
94
+ * const order = await model.generate(prompt);
95
+ * return ctx.suspendable(() => ctx.rpc(shop, 'main', { idempotencyKey: ctx.request.id }).place(order));
96
+ * });
97
+ *
98
+ * If no other scope keeps the attempt alive, Restate may suspend it on
99
+ * what it waits for, and run the handler again from its first line when
100
+ * that answers. The work before the `suspendable` is done again, and a
101
+ * call inside it needs an idempotency key to reach the same invocation.
102
+ * Other work in the same scope, running meanwhile, is not kept alive
103
+ * either. A scope opened inside `fn` (a `ctx.working`, a database call)
104
+ * still keeps the attempt alive. Outside any scope, `fn` just runs.
105
+ * Cancellation is unchanged: a call result inside it rejects with the
106
+ * cancellation, and a `stoppable` scope around it gets its signal.
107
+ */
108
+ readonly suspendable: Suspendable;
109
+ /**
110
+ * Run `fn` inside a span `name`, shown in Restate's UI: the calls, sends and
111
+ * commits it makes are nested under it. It ends with `fn`, with its failure
112
+ * if it throws. On an attempt not served by Restate (a test's), just `fn`.
113
+ * A `db.transaction` opens no span of its own: its commit is inside the
114
+ * span it runs in, if any. To show a transaction as a span, wrap it:
115
+ *
116
+ * await ctx.span('save', () => ctx.db.transaction(async (tx) => { … }));
117
+ */
118
+ span<T>(name: string, fn: () => Promise<T>): Promise<T>;
48
119
  }
49
120
  /**
50
- * The context of a session object's view: it runs beside the handlers, and
51
- * reads the database as committed when its invocation started, whatever they
52
- * commit meanwhile. It writes nothing, and sends nothing, but it can cancel an
53
- * invocation: a handler of its own object's, say, as a Stop button does.
121
+ * The context of a session object's view. A view runs beside the handlers
122
+ * and reads the database as committed when its invocation started, whatever
123
+ * the handlers commit meanwhile. It writes and sends nothing, but it can
124
+ * cancel an invocation, such as a handler of the same object (a Stop button).
54
125
  */
55
126
  export interface ViewContext {
56
127
  readonly key: string;
57
- readonly request: restate.Request;
128
+ readonly request: SessionRequest;
58
129
  readonly db: DatabaseReader;
59
130
  readonly rpc: Rpc;
60
131
  readonly cancel: Cancel;
61
132
  }
62
133
  /**
63
- * Cancel invocation `invocationId` (such as `inv_1f…`), as Restate's admin
64
- * API does: made at once, and not awaited. Cancelling an invocation that
65
- * already ended does nothing, so a new attempt that cancels it again is
66
- * harmless.
134
+ * Cancel the invocation `invocationId` (such as `inv_1f…`), as the Restate
135
+ * admin API does. The cancel is sent immediately and is not awaited.
136
+ * Cancelling an invocation that already ended does nothing, so a retry that
137
+ * cancels it again is harmless. An `invocationId` that is not an invocation
138
+ * id throws a `TerminalError` (400): nothing is sent, and the handler may
139
+ * catch it and go on.
67
140
  *
68
141
  * ctx.cancel(turn.invocationId);
69
142
  */
70
143
  export type Cancel = (invocationId: string) => void;
71
- /** A handler of `C`: its input, if any, annotated. */
72
144
  type Fn<C> = (ctx: C, input: any) => Promise<unknown>;
73
- /** The SDK's options of a handler (`input`, `output`, `description`, `ingressPrivate`, ...). */
145
+ /** The SDK handler options (`input`, `output`, `description`, `ingressPrivate`, ...). */
74
146
  export type HandlerOptions = restate.ObjectHandlerOpts<any, any>;
75
- /** A handler or a view: a function, or one with options. */
147
+ /** A handler or a view: a function, or `{ handler, ...options }`. */
76
148
  export type Entry<C> = Fn<C> | ({
77
149
  handler: Fn<C>;
78
150
  } & HandlerOptions);
79
- /** Each entry's function, as clients see it; none for entries left out (inferred as the constraint). */
151
+ /** Each entry's function, as clients see it. Unknown when the entries are not inferred. */
80
152
  type Functions<H> = string extends keyof H ? unknown : {
81
153
  [K in keyof H]: H[K] extends {
82
154
  handler: infer F;
83
155
  } ? F : H[K];
84
156
  };
85
- /**
86
- * The key of the object database's head, its first read as it opens:
87
- * `HEAD_KEY` in the addon's state format
88
- * (`packages/sessions/native/src/state/format.rs`).
89
- */
157
+ /** The state key of the database head, the first read of an open (`HEAD_KEY` in shared-core `src/state/format.rs`). */
90
158
  export declare const HEAD_KEY = "v22/head";
91
- /**
92
- * The options every session object has: an invocation starts with the
93
- * database's head only, not with every page. The rest of the database it
94
- * reads as it needs it: its tail entries and packs change keys with each
95
- * flush, so only the head can be named.
96
- */
159
+ /** Preload only the database head: tail and pack keys change with each flush. */
97
160
  export declare const sqlOptions: {
98
161
  state: {
99
162
  preload: string[];
100
163
  };
101
164
  };
102
165
  /**
103
- * The metadata every session object has: Restate's UI hides the database
104
- * from the journal view (its head, tail, manifests and packs in the object's
105
- * state, `v22/...`; and the `sync` runs after its writes).
166
+ * Marks a session object's handlers for discovery: they are on the explicit
167
+ * recovery protocol (`protocolFamily` in manifest v6, endpoint.ts). The
168
+ * database's actions are recorded as nothing, so Restate's UI shows none of
169
+ * its pages.
106
170
  */
107
- export declare const sqlMetadata: {
108
- 'dev.restate.tooling.journal.hidden.names': string;
109
- 'dev.restate.tooling.journal.hidden.name.prefix': string;
110
- };
111
- export declare const recovery: () => restate.internal.ExplicitRecoveryOptions;
112
- /** The SDK's runtime context, as far as the session needs it beyond its public type. */
113
- type Runtime = {
114
- invocationEndPromise: SqlHost['invocationEndPromise'];
115
- defaultSerde: SqlHost['defaultSerde'];
116
- };
117
- /** What an attempt needs of the SDK's context: a test's fake has these. */
118
- export type AttemptContext = Pick<restate.ObjectContext, 'key' | 'request' | 'get' | 'set' | 'clear' | 'stateKeys' | 'run' | 'genericSend' | 'genericCall' | 'invocation'> & Runtime;
119
- /** What an attempt's session needs of the SDK's context `ctx`. */
120
- export declare function host(ctx: restate.ObjectContext | restate.ObjectSharedContext | AttemptContext, shared: boolean): SqlHost;
171
+ export declare const PROTOCOL_FAMILY = "EXPLICIT_RECOVERY";
121
172
  /**
122
- * The handler or view `name` of `definition`, if it is a session object's:
123
- * what {@link serveSession} needs to run an attempt of it on the VM.
173
+ * What an attempt of an entry runs with: its options resolved as the SDK
174
+ * resolves a handler's (`createExecutionOptions`, `registerHandlerIO` and
175
+ * discovery in the SDK's `endpoint/components.js`), the handler's own first,
176
+ * then its object's, then the endpoint's default service options.
124
177
  */
125
- export declare function handlerEntry(definition: object, name: string): {
178
+ export interface ResolvedEntry {
126
179
  view: boolean;
180
+ /** `explicitCancellation`. */
127
181
  explicit: boolean;
182
+ /** `serde`: what `input` and `output` default to, and the typed clients' calls and sends. */
183
+ defaultSerde: Serde<unknown>;
128
184
  inputSerde: Serde<unknown>;
129
185
  outputSerde: Serde<unknown>;
130
- asTerminalError?: (error: unknown) => Error | undefined;
131
- } | undefined;
132
- /** Whether `definition` is a session object: it has handlers this package runs. */
133
- export declare const isSessionObject: (definition: object) => boolean;
186
+ /** Which errors end the invocation instead of being retried. */
187
+ asTerminalError?: (error: unknown) => restate.TerminalError | undefined;
188
+ /** The object's hooks (else the endpoint's default), then the handler's. */
189
+ hooks: readonly restate.HooksProvider[];
190
+ /** Restate's inactivity timeout, in milliseconds, as the handler, else its object, else the endpoint's defaults set it. */
191
+ inactivityTimeoutMs?: number;
192
+ }
134
193
  /**
135
- * The definition (`sessionObject`'s) of the object whose handler or view
136
- * `ctx` is the context of: what a library keeps per object lives on it.
194
+ * What {@link serveSession} needs to run entry `name`, if `definition` is a
195
+ * session object, on an endpoint whose default service options are
196
+ * `defaults`.
137
197
  */
138
- export declare const definitionOf: (ctx: SessionContext | ViewContext) => object | undefined;
139
- /** What `definition`'s attempts get, if it is a session object: for a test's attempts of its own. */
198
+ export declare function handlerEntry(definition: object, name: string, defaults?: restate.DefaultServiceOptions): ResolvedEntry | undefined;
199
+ export declare const isSessionObject: (definition: object) => boolean;
200
+ /** For tests that run attempts without Restate. */
140
201
  export declare const configOf: (definition: object) => ObjectConfig | undefined;
202
+ /** What {@link contextOf} takes beside its host and database. */
203
+ interface ContextOptions {
204
+ /** The serde of a typed client's calls and sends to a handler that declares none: the `serde` option, JSON by default. */
205
+ serde?: Serde<unknown>;
206
+ }
207
+ /** The context of a handler (or, with `view`, of a view) over `host`. Tests use it too. */
208
+ export declare function contextOf(host: AttemptHost, db: Database, options: {
209
+ view: true;
210
+ } & ContextOptions): ViewContext;
211
+ export declare function contextOf(host: AttemptHost, db: Database, options?: {
212
+ view?: false;
213
+ } & ContextOptions): SessionContext;
141
214
  /**
142
- * Wrap the stores of `definition`'s attempts with `wrap`: fault injection, in
143
- * tests. A definition that is no session object has no store: it is left as
144
- * it is.
215
+ * Open a `ctx.stoppable` scope until `scope.release()`, for framework hooks. A
216
+ * `pinned` scope is not paused by `ctx.suspendable`: for a framework whose next
217
+ * attempt would lose the result of work suspended inside it.
145
218
  */
146
- export declare function withStoreWrapper<D extends object>(definition: D, wrapper: (store: Store) => Store): D;
219
+ export declare function openScope(ctx: SessionContext, { pinned }?: {
220
+ pinned?: boolean;
221
+ }): Scope;
147
222
  /**
148
- * The context of a handler (or, with `view`, of a view) over the SDK's
149
- * context `ctx`, with the database `db`: what an attempt gets, and a test's
150
- * over a context of its own. With `explicitCancellation`, a handler's with
151
- * that option, which {@link cancelled} and {@link cancelCalls} take.
223
+ * Run `handler`, then end `session`. A handler that fails after the
224
+ * cancellation was delivered fails with `CancelledError`, decided when the
225
+ * handler settles, not after the session is saved.
152
226
  */
153
- export declare function contextOf(ctx: AttemptContext, db: Database, options: {
154
- view: true;
155
- definition?: object;
156
- }): ViewContext;
157
- export declare function contextOf(ctx: AttemptContext, db: Database, options?: {
158
- view?: false;
159
- explicitCancellation?: boolean;
160
- definition?: object;
161
- }): SessionContext;
227
+ export declare function withAttempt<T>(handler: () => Promise<T>, session: Attempt, stop: AttemptHost['stop']): Promise<T>;
162
228
  /**
163
- * Run handler or view `name` of `definition` for one attempt over `ctx`, a
164
- * context of a test's own, without Restate: for tests.
229
+ * Run entry `name` of `definition` for one attempt over `host`: from
230
+ * handler.ts, with its options as {@link handlerEntry} resolved them on the
231
+ * endpoint, or from a test.
165
232
  */
166
233
  export declare function invoke(definition: {
167
234
  name: string;
168
- }, name: string, ctx: AttemptContext, input?: unknown): Promise<unknown>;
235
+ }, name: string, host: AttemptHost, input?: unknown, run?: ResolvedEntry): Promise<unknown>;
236
+ /**
237
+ * The SDK options a session object refuses, where `options` sets them: the
238
+ * state options, which it sets itself (the database owns the state), and
239
+ * `onJournalMismatchErrors`, which has nothing to act on (an attempt is never
240
+ * replayed, so no journal mismatches).
241
+ */
242
+ export declare function refuseOptions(where: string, options: object | undefined): void;
169
243
  /**
170
244
  * A virtual object whose state is a SQL database per key.
171
245
  *
172
246
  * - `schema`: the steps that make each key's database, in order, applied
173
- * once per key by the first handler that uses it. A step that ran never
174
- * changes: a change is a step of its own.
175
- * - `handlers`: they run one at a time per key, each with a
176
- * {@link SessionContext}.
177
- * - `views`: they run beside the handlers, each with a {@link ViewContext}:
178
- * they read, and write nothing.
247
+ * once per key. A step that ran never changes: a change is a new step.
248
+ * - `handlers`: run one at a time per key, each with a {@link SessionContext}.
249
+ * - `views`: run beside the handlers, each with a {@link ViewContext}. They
250
+ * only read.
179
251
  *
180
- * Each is a function, or `{ handler, ...options }` with the SDK's handler
252
+ * Each entry is a function, or `{ handler, ...options }` with SDK handler
181
253
  * options. A name is a handler or a view, not both. `description`,
182
- * `metadata` and `options` are the SDK's object fields.
254
+ * `metadata` and `options` are the SDK object fields.
255
+ *
256
+ * const notes = restate.sessionObject({
257
+ * name: 'notes',
258
+ * schema: ['CREATE TABLE notes (text TEXT NOT NULL)'],
259
+ * handlers: {
260
+ * add: async (ctx, text: string) => {
261
+ * await ctx.db.execute('INSERT INTO notes (text) VALUES (?)', [text]);
262
+ * },
263
+ * },
264
+ * views: {
265
+ * list: async (ctx) => ctx.db.query<{ text: string }>('SELECT text FROM notes'),
266
+ * },
267
+ * });
183
268
  */
184
269
  export declare function sessionObject<P extends string, H extends Record<string, Entry<SessionContext>>, V extends Record<string, Entry<ViewContext>>>(definition: {
185
270
  name: P;
@@ -191,49 +276,39 @@ export declare function sessionObject<P extends string, H extends Record<string,
191
276
  options?: restate.ObjectOptions;
192
277
  }): VirtualObjectDefinition<P, Functions<H> & Functions<V>>;
193
278
  /**
194
- * Call `target`, and resolve to the id of the call's invocation (`inv_1f…`),
195
- * not waiting for its result: for a library that waits for it by
196
- * {@link attach}. It is a call, not a send: a handler with
197
- * `explicitCancellation` whose `cancelCalls` cancels the calls of its
198
- * attempt cancels this one too, as a send's would not be.
199
- *
200
- * Its result is left as it comes. A call of a workflow's `run` whose run of
201
- * that id started already fails ("the workflow method was already
202
- * invoked"), whatever its idempotency key, but its invocation id is that
203
- * run's: so a new attempt that calls again gets the id of the run an
204
- * earlier one started, and its `cancelCalls` cancels that run.
279
+ * The invocation's own state: every attempt of the invocation finds it, no
280
+ * other invocation does, and it ends with the invocation. Bytes only. For
281
+ * progress a handler must find again on its next attempt (what it already
282
+ * did), apart from the object's database.
205
283
  */
206
- export declare function start(ctx: SessionContext, target: Target & CallOptions): Promise<string>;
284
+ export interface InvocationState {
285
+ get(key: string): Promise<Uint8Array | null>;
286
+ set(key: string, value: Uint8Array): void;
287
+ clear(key: string): void;
288
+ clearAll(): void;
289
+ keys(): Promise<string[]>;
290
+ }
207
291
  /**
208
- * The result of invocation `invocationId` (such as {@link start}'s), once it
209
- * ends: its output, or its terminal error. Waiting for it cancels nothing
210
- * when the attempt ends: the invocation is its own.
292
+ * The invocation state of the invocation whose context `ctx` is: see
293
+ * {@link InvocationState}. A view's reads it; its writes throw a TerminalError.
211
294
  */
212
- export declare function attach<O = unknown>(ctx: SessionContext, invocationId: string, outputSerde?: Serde<O>): Promise<O>;
295
+ export declare function invocationState(ctx: SessionContext | ViewContext): InvocationState;
213
296
  /**
214
- * Resolves when Restate cancels the invocation of `ctx`, a handler's with
215
- * `explicitCancellation: true`, whose awaits are left as they are: for a
216
- * library that stops its own work then (a model's request, say).
217
- *
218
- * It watches for the cancellation, and holds nothing: awaited alone, it does
219
- * not suspend the invocation, and Restate is not told that the handler waits
220
- * (a heartbeat, in `ctx.working`, tells Restate the attempt makes progress
221
- * instead). The cancel signal comes while Restate keeps
222
- * the invocation's input open. Once Restate closed it (the handler sent and
223
- * got nothing for the inactivity timeout), a cancellation resolves this at
224
- * the handler's next await of Restate's, which suspends the invocation and
225
- * resumes it at once, or not at all if it awaits nothing more.
226
- *
227
- * So it is not a way to park a handler until it is cancelled. One that
228
- * awaits this and nothing else is not suspended: its attempt is shut down at
229
- * the inactivity timeout and started again at once, and so on until the
230
- * cancellation comes.
297
+ * The `index`-th signal named `name` (from 0) the invocation of `ctx`
298
+ * received: its payload, `null` if it carries nothing, or a TerminalError if
299
+ * it carries a failure. It waits for it: an attempt shut down meanwhile
300
+ * suspends, and the signal's arrival wakes the invocation. The caller keeps
301
+ * the index. A signal is sent through Restate's admin API
302
+ * (`POST /invocations/<id>/signals/<name>`) or {@link sendSignal}.
231
303
  */
232
- export declare const cancelled: (ctx: SessionContext) => Promise<void>;
304
+ export declare function readSignal(ctx: SessionContext | ViewContext, name: string, index?: number): Promise<Uint8Array | null>;
233
305
  /**
234
- * Cancel the calls the attempt of `ctx` made, as a cancelled invocation's
235
- * would be: a handler's with `explicitCancellation: true`.
306
+ * Send the signal `name` to invocation `invocationId`, with `value`, a
307
+ * failure, or nothing. An `invocationId` that is not an invocation id throws a
308
+ * `TerminalError` (400): nothing is sent, and the handler may catch it.
236
309
  */
237
- export declare const cancelCalls: (ctx: SessionContext) => Promise<void>;
310
+ export declare function sendSignal(ctx: SessionContext | ViewContext, invocationId: string, name: string, value?: Uint8Array | restate.TerminalError): void;
311
+ /** Resolves once every action the attempt of `ctx` made before it is applied by Restate. */
312
+ export declare function flush(ctx: SessionContext | ViewContext): Promise<void>;
238
313
  export {};
239
314
  //# sourceMappingURL=object.d.ts.map