@plitzi/sdk-server 0.38.20 → 0.38.22

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 (245) hide show
  1. package/CHANGELOG.md +141 -0
  2. package/README.md +2 -2
  3. package/dist/actions.d.ts +6 -0
  4. package/dist/actions.js +2 -1
  5. package/dist/core/auth/createAuth.d.ts +1 -1
  6. package/dist/core/auth/tokens.d.ts +1 -1
  7. package/dist/core/configSeam.js +12 -2
  8. package/dist/core/services/functionRoutes.js +7 -2
  9. package/dist/core/services/realtime.js +5 -2
  10. package/dist/functions-api.d.ts +176 -3
  11. package/dist/functions.d.ts +3 -1
  12. package/dist/functions.js +2 -1
  13. package/dist/helpers/serverLog.d.ts +1 -1
  14. package/dist/helpers/serverLog.js +1 -1
  15. package/dist/hosts/project/plugins.js +20 -3
  16. package/dist/hosts/project/serveProject.js +16 -1
  17. package/dist/modules/actions/index.js +17 -4
  18. package/dist/modules/actions/jobs/index.d.ts +4 -3
  19. package/dist/modules/actions/jobs/index.js +2 -1
  20. package/dist/modules/actions/jobs/later.d.ts +2 -2
  21. package/dist/modules/actions/jobs/later.js +5 -2
  22. package/dist/modules/actions/jobs/memoryQueue.d.ts +4 -4
  23. package/dist/modules/actions/jobs/memoryQueue.js +69 -25
  24. package/dist/modules/actions/jobs/scheduler.d.ts +2 -2
  25. package/dist/modules/actions/jobs/scheduler.js +5 -2
  26. package/dist/modules/actions/jobs/worker.d.ts +6 -3
  27. package/dist/modules/actions/jobs/worker.js +104 -10
  28. package/dist/modules/actions/runtime/errors.d.ts +9 -1
  29. package/dist/modules/actions/runtime/errors.js +12 -2
  30. package/dist/modules/actions/runtime/runAction.d.ts +5 -2
  31. package/dist/modules/actions/runtime/runAction.js +5 -3
  32. package/dist/modules/actions/runtime/taskContext.d.ts +12 -3
  33. package/dist/modules/actions/runtime/taskContext.js +9 -1
  34. package/dist/modules/actions/types.d.ts +22 -6
  35. package/dist/modules/functions/capabilities.js +124 -13
  36. package/dist/modules/functions/config.d.ts +20 -0
  37. package/dist/modules/functions/context.d.ts +2 -2
  38. package/dist/modules/functions/context.js +16 -3
  39. package/dist/modules/functions/contract.d.ts +97 -3
  40. package/dist/modules/functions/driver.js +136 -9
  41. package/dist/modules/functions/jobControl.d.ts +21 -0
  42. package/dist/modules/functions/jobControl.js +43 -0
  43. package/dist/modules/functions/jobs.d.ts +98 -0
  44. package/dist/modules/functions/jobs.js +438 -0
  45. package/dist/modules/functions/manifest.d.ts +2 -0
  46. package/dist/modules/functions/manifest.js +37 -4
  47. package/dist/modules/functions/native.js +2 -1
  48. package/dist/modules/functions/oauth.d.ts +3 -2
  49. package/dist/modules/functions/oauth.js +53 -19
  50. package/dist/modules/functions/protocol.d.ts +98 -7
  51. package/dist/modules/functions/protocol.js +15 -1
  52. package/dist/modules/functions/routes.d.ts +9 -1
  53. package/dist/modules/functions/routes.js +50 -25
  54. package/dist/modules/functions/runner/messages.d.ts +0 -1
  55. package/dist/modules/functions/runner/messages.js +46 -5
  56. package/dist/modules/functions/runner/remote.js +60 -8
  57. package/dist/modules/functions/runner/service.js +54 -8
  58. package/dist/modules/functions/sandbox/guest.js +5 -3
  59. package/dist/modules/functions/sandbox/isolate.js +7 -8
  60. package/dist/modules/functions/space.js +4 -4
  61. package/dist/modules/mongo/jobQueue.d.ts +3 -3
  62. package/dist/modules/mongo/jobQueue.js +137 -26
  63. package/dist/modules/mysql/jobs/jobQueue.d.ts +3 -3
  64. package/dist/modules/mysql/jobs/jobQueue.js +97 -33
  65. package/dist/modules/mysql/jobs/schema.js +38 -11
  66. package/dist/modules/realtime/handlers.d.ts +5 -2
  67. package/dist/modules/realtime/handlers.js +15 -4
  68. package/dist/modules/realtime/index.d.ts +11 -1
  69. package/dist/modules/realtime/index.js +8 -1
  70. package/dist/modules/realtime/jobs.d.ts +20 -0
  71. package/dist/modules/realtime/jobs.js +41 -0
  72. package/dist/modules/realtime/retained.d.ts +3 -2
  73. package/dist/modules/realtime/retained.js +2 -2
  74. package/dist/modules/realtime/socket.d.ts +4 -1
  75. package/dist/modules/realtime/socket.js +2 -2
  76. package/dist/modules/rsc/resolveRscData.js +2 -1
  77. package/dist/modules/runtime/host.js +1 -1
  78. package/dist/modules/runtime/runner.d.ts +1 -1
  79. package/dist/modules/runtime/runner.js +12 -2
  80. package/dist/modules/runtime/stages.js +1 -1
  81. package/dist/modules/ssr/applySSRResult.d.ts +5 -0
  82. package/dist/modules/ssr/applySSRResult.js +8 -1
  83. package/dist/modules/ssr/buildBody.js +2 -1
  84. package/dist/modules/ssr/prepareRender.d.ts +3 -0
  85. package/dist/modules/ssr/prepareRender.js +17 -5
  86. package/dist/modules/ssr/spaceDocument.d.ts +2 -1
  87. package/dist/modules/ssr/spaceDocument.js +14 -5
  88. package/dist/modules/ssr/streamBody.js +2 -1
  89. package/package.json +3 -3
  90. package/skills/plitzi-authoring/reference/auth.md +6 -0
  91. package/skills/plitzi-authoring/reference/authoring-errors.md +1 -0
  92. package/skills/plitzi-authoring/reference/plugin-reach.md +3 -0
  93. package/skills/plitzi-authoring/reference/realtime.md +4 -0
  94. package/dist/adapters/cloudAdapters.test.d.ts +0 -1
  95. package/dist/adapters/jsonAdapters.test.d.ts +0 -1
  96. package/dist/adapters/space/space.test.d.ts +0 -1
  97. package/dist/core/auth/api.test.d.ts +0 -1
  98. package/dist/core/auth/authorize.test.d.ts +0 -1
  99. package/dist/core/auth/createAuth.test.d.ts +0 -1
  100. package/dist/core/auth/csrf.test.d.ts +0 -1
  101. package/dist/core/auth/domains.test.d.ts +0 -1
  102. package/dist/core/auth/identity.test.d.ts +0 -1
  103. package/dist/core/auth/lifecycle.test.d.ts +0 -1
  104. package/dist/core/auth/oauth/oauth.test.d.ts +0 -1
  105. package/dist/core/auth/redirects.test.d.ts +0 -1
  106. package/dist/core/auth/routes.test.d.ts +0 -1
  107. package/dist/core/auth/session.test.d.ts +0 -1
  108. package/dist/core/auth/spaceTokens.test.d.ts +0 -1
  109. package/dist/core/auth/throttle.test.d.ts +0 -1
  110. package/dist/core/auth/tokens.test.d.ts +0 -1
  111. package/dist/core/auth/totp.test.d.ts +0 -1
  112. package/dist/core/configSeam.test.d.ts +0 -1
  113. package/dist/core/createServer.actions.test.d.ts +0 -1
  114. package/dist/core/createServer.functions.test.d.ts +0 -1
  115. package/dist/core/createServer.livePages.test.d.ts +0 -1
  116. package/dist/core/createServer.notFound.test.d.ts +0 -1
  117. package/dist/core/createServer.oauth.test.d.ts +0 -1
  118. package/dist/core/createServer.publicData.test.d.ts +0 -1
  119. package/dist/core/createServer.test.d.ts +0 -1
  120. package/dist/core/fontStore.test.d.ts +0 -1
  121. package/dist/core/freePort.test.d.ts +0 -1
  122. package/dist/core/handlers/csrfMiddleware.test.d.ts +0 -1
  123. package/dist/core/handlers/handlers.test.d.ts +0 -1
  124. package/dist/core/handlers/socialRouteHandlers.test.d.ts +0 -1
  125. package/dist/core/http/dispatcher.test.d.ts +0 -1
  126. package/dist/core/http/stages/crossSiteWrites.test.d.ts +0 -1
  127. package/dist/core/http/stages/exchangeRoute.test.d.ts +0 -1
  128. package/dist/core/http/stages/images.test.d.ts +0 -1
  129. package/dist/core/http/stages/middlewares.test.d.ts +0 -1
  130. package/dist/core/http/stages/sessionRenewal.test.d.ts +0 -1
  131. package/dist/core/http/stages/signInRoute.test.d.ts +0 -1
  132. package/dist/core/oauth/authorize.test.d.ts +0 -1
  133. package/dist/core/oauth/register.test.d.ts +0 -1
  134. package/dist/core/oauth/token.test.d.ts +0 -1
  135. package/dist/core/requestParser.test.d.ts +0 -1
  136. package/dist/core/server/baseServer.test.d.ts +0 -1
  137. package/dist/core/server/closeOnSignals.test.d.ts +0 -1
  138. package/dist/core/server/drain.test.d.ts +0 -1
  139. package/dist/core/server/fleet/channel.test.d.ts +0 -1
  140. package/dist/core/server/fleet/fixtures/fleetServer.d.ts +0 -1
  141. package/dist/core/server/fleet/fleet.integration.test.d.ts +0 -1
  142. package/dist/core/server/fleet/relay.test.d.ts +0 -1
  143. package/dist/core/server/fleet/role.test.d.ts +0 -1
  144. package/dist/core/server/fleet/supervisor.test.d.ts +0 -1
  145. package/dist/core/services/resolve.test.d.ts +0 -1
  146. package/dist/core/staticFiles.test.d.ts +0 -1
  147. package/dist/env.test.d.ts +0 -1
  148. package/dist/helpers/atomicFile.test.d.ts +0 -1
  149. package/dist/helpers/buildResponseHelpers.test.d.ts +0 -1
  150. package/dist/helpers/buildServerInfo.test.d.ts +0 -1
  151. package/dist/helpers/cache/CompressedFileCache.test.d.ts +0 -1
  152. package/dist/helpers/cache/cacheManager.test.d.ts +0 -1
  153. package/dist/helpers/cache/keys.test.d.ts +0 -1
  154. package/dist/helpers/compress.test.d.ts +0 -1
  155. package/dist/helpers/hydrationPayload.test.d.ts +0 -1
  156. package/dist/helpers/offlineDataLoader.test.d.ts +0 -1
  157. package/dist/helpers/onAbort.test.d.ts +0 -1
  158. package/dist/helpers/outboundGuard.test.d.ts +0 -1
  159. package/dist/helpers/reportReactBuild.test.d.ts +0 -1
  160. package/dist/helpers/resolveDebugMode.test.d.ts +0 -1
  161. package/dist/helpers/serverLog.test.d.ts +0 -1
  162. package/dist/hosts/authoringHost/index.test.d.ts +0 -1
  163. package/dist/hosts/project/serveProject.test.d.ts +0 -1
  164. package/dist/layers.test.d.ts +0 -1
  165. package/dist/middlewares/spaceDeployment.test.d.ts +0 -1
  166. package/dist/modules/actions/connectorWrite.test.d.ts +0 -1
  167. package/dist/modules/actions/jobs/failureStreak.test.d.ts +0 -1
  168. package/dist/modules/actions/jobs/later.test.d.ts +0 -1
  169. package/dist/modules/actions/jobs/memoryStores.test.d.ts +0 -1
  170. package/dist/modules/actions/jobs/scheduler.test.d.ts +0 -1
  171. package/dist/modules/actions/jobs/testing/jobQueueContract.d.ts +0 -25
  172. package/dist/modules/actions/jobs/worker.test.d.ts +0 -1
  173. package/dist/modules/actions/moduleFor.test.d.ts +0 -1
  174. package/dist/modules/actions/runtime/check.test.d.ts +0 -1
  175. package/dist/modules/actions/runtime/credentials.test.d.ts +0 -1
  176. package/dist/modules/actions/runtime/email.test.d.ts +0 -1
  177. package/dist/modules/actions/runtime/fileKv.test.d.ts +0 -1
  178. package/dist/modules/actions/runtime/flags.test.d.ts +0 -1
  179. package/dist/modules/actions/runtime/guards.test.d.ts +0 -1
  180. package/dist/modules/actions/runtime/kvStore.test.d.ts +0 -1
  181. package/dist/modules/actions/runtime/namespaceKv.test.d.ts +0 -1
  182. package/dist/modules/actions/runtime/redisKv.integration.test.d.ts +0 -1
  183. package/dist/modules/actions/runtime/renderResolver.test.d.ts +0 -1
  184. package/dist/modules/actions/runtime/renderShare.test.d.ts +0 -1
  185. package/dist/modules/actions/runtime/runAction.test.d.ts +0 -1
  186. package/dist/modules/actions/runtime/runLogger.test.d.ts +0 -1
  187. package/dist/modules/actions/runtime/signing.test.d.ts +0 -1
  188. package/dist/modules/actions/taskCatalog.test.d.ts +0 -1
  189. package/dist/modules/actions/tasks/db.test.d.ts +0 -1
  190. package/dist/modules/actions/tasks/email.test.d.ts +0 -1
  191. package/dist/modules/actions/tasks/http.test.d.ts +0 -1
  192. package/dist/modules/actions/tasks/kv.test.d.ts +0 -1
  193. package/dist/modules/actions/transport/callHandler.test.d.ts +0 -1
  194. package/dist/modules/actions/transport/webhookHandler.test.d.ts +0 -1
  195. package/dist/modules/connectors/engine.test.d.ts +0 -1
  196. package/dist/modules/connectors/projection.test.d.ts +0 -1
  197. package/dist/modules/connectors/resolver.test.d.ts +0 -1
  198. package/dist/modules/functions/build.test.d.ts +0 -1
  199. package/dist/modules/functions/load.test.d.ts +0 -1
  200. package/dist/modules/functions/local.test.d.ts +0 -1
  201. package/dist/modules/functions/manifest.test.d.ts +0 -1
  202. package/dist/modules/functions/native.test.d.ts +0 -1
  203. package/dist/modules/functions/oauth.test.d.ts +0 -1
  204. package/dist/modules/functions/plugins.test.d.ts +0 -1
  205. package/dist/modules/functions/routes.test.d.ts +0 -1
  206. package/dist/modules/functions/runner/remote.test.d.ts +0 -1
  207. package/dist/modules/functions/sandbox/isolate.test.d.ts +0 -1
  208. package/dist/modules/functions/testing/tasksOf.d.ts +0 -4
  209. package/dist/modules/images/imageProxy.test.d.ts +0 -1
  210. package/dist/modules/images/transform.test.d.ts +0 -1
  211. package/dist/modules/mongo/stores.integration.test.d.ts +0 -1
  212. package/dist/modules/mysql/accounts.test.d.ts +0 -1
  213. package/dist/modules/mysql/jobs/stores.integration.test.d.ts +0 -1
  214. package/dist/modules/mysql/schema.test.d.ts +0 -1
  215. package/dist/modules/mysql/store.integration.test.d.ts +0 -1
  216. package/dist/modules/realtime/realtime.test.d.ts +0 -1
  217. package/dist/modules/realtime/redisPubSub.test.d.ts +0 -1
  218. package/dist/modules/realtime/retained.test.d.ts +0 -1
  219. package/dist/modules/realtime/socket.test.d.ts +0 -1
  220. package/dist/modules/rsc/connectorRscData.test.d.ts +0 -1
  221. package/dist/modules/rsc/handler.test.d.ts +0 -1
  222. package/dist/modules/rsc/publicFileResolver.test.d.ts +0 -1
  223. package/dist/modules/rsc/resolveRscData.test.d.ts +0 -1
  224. package/dist/modules/runtime/elsewhere.test.d.ts +0 -1
  225. package/dist/modules/runtime/entry.test.d.ts +0 -1
  226. package/dist/modules/runtime/inside.test.d.ts +0 -1
  227. package/dist/modules/runtime/ownServer.test.d.ts +0 -1
  228. package/dist/modules/runtime/runtime.test.d.ts +0 -1
  229. package/dist/modules/sqlite/kv.test.d.ts +0 -1
  230. package/dist/modules/ssr/draftSession.test.d.ts +0 -1
  231. package/dist/modules/ssr/loadPluginComponents.test.d.ts +0 -1
  232. package/dist/modules/ssr/metering.test.d.ts +0 -1
  233. package/dist/modules/ssr/prepareRender.test.d.ts +0 -1
  234. package/dist/modules/ssr/redirect.test.d.ts +0 -1
  235. package/dist/modules/ssr/registerExternalPlugins.test.d.ts +0 -1
  236. package/dist/modules/ssr/reportMissingPlugins.test.d.ts +0 -1
  237. package/dist/modules/ssr/resolvePageSeo.test.d.ts +0 -1
  238. package/dist/modules/ssr/spaceDocument.test.d.ts +0 -1
  239. package/dist/modules/ssr/template.test.d.ts +0 -1
  240. package/dist/modules/ssr/testing/offlineData.d.ts +0 -5
  241. package/dist/modules/ssr/vendor.test.d.ts +0 -1
  242. package/dist/plugins/compile.test.d.ts +0 -1
  243. package/dist/plugins/copy.test.d.ts +0 -1
  244. package/dist/plugins/manager.test.d.ts +0 -1
  245. package/dist/plugins/validate.test.d.ts +0 -1
@@ -1,7 +1,7 @@
1
1
  import { LaterAnswer, LaterRequest } from '../actions/jobs/later';
2
2
  import { RateCount, RateLimit } from '../actions/runtime/rateLimit';
3
3
  import { ActionKvStore } from '../actions/types';
4
- import { Environment, FunctionOAuthConnection, FunctionTimeLimits, InteractionCallbackParam } from '@plitzi/sdk-shared';
4
+ import { ActionAccess, Environment, FunctionJobView, FunctionOAuthConnection, FunctionTimeLimits, InteractionCallbackParam } from '@plitzi/sdk-shared';
5
5
  /**
6
6
  * Who started the run, as a space's own code may know them: everything a function decides by — who, their roles and
7
7
  * permissions — and never their session. A token inside the sandbox is a token a function could send anywhere.
@@ -24,6 +24,8 @@ export type FunctionFetchInit = {
24
24
  headers?: Record<string, string>;
25
25
  body?: string;
26
26
  credential?: string;
27
+ /** Cuts the request short when it aborts (`AbortSignal.timeout(12_000)`); the run's own end cuts it regardless. */
28
+ signal?: AbortSignal;
27
29
  };
28
30
  /** What a function's `fetch` answers: a web `Response`, whichever runner it is in. */
29
31
  export type FunctionFetch = (url: string | URL, init?: FunctionFetchInit) => Promise<Response>;
@@ -34,12 +36,24 @@ export type FunctionFetch = (url: string | URL, init?: FunctionFetchInit) => Pro
34
36
  export type FunctionOAuthOwner = {
35
37
  owner?: string;
36
38
  };
39
+ /**
40
+ * The `code` of a refusal `ctx.oauth` throws (an `ActionRefusal`), to tell it apart by: `oauth-not-connected` — no
41
+ * account connected for that owner yet, so `connect` first; `oauth-no-owner` — nobody signed in and no `owner` named.
42
+ */
43
+ export type FunctionOAuthRefusal = 'oauth-not-connected' | 'oauth-no-owner';
37
44
  /** What `ctx.oauth.status` says of a connection — never its token. */
38
45
  export type FunctionOAuthStatus = {
39
46
  connected: boolean;
40
47
  scopes?: string[];
41
48
  expiresAt?: number;
42
49
  };
50
+ /** The access token `ctx.oauth.token` hands out — never the refresh token, which stays with the platform. */
51
+ export type FunctionOAuthToken = {
52
+ token: string;
53
+ type: string;
54
+ expiresAt?: number;
55
+ scopes?: string[];
56
+ };
43
57
  /**
44
58
  * OAuth 2.0 on behalf of whoever the space serves, through the connections it declared (`oauth` in its functions): the
45
59
  * consent, the code exchanged, the token kept sealed and renewed by the platform. The code never holds a token, as it
@@ -49,21 +63,97 @@ export type FunctionOAuth = {
49
63
  /**
50
64
  * Where to send the visitor to consent (authorization code, PKCE). They come back to `/fn/oauth/callback` — the
51
65
  * address to register with the provider, on the space's host — and from there to `returnTo`, a path of the space,
52
- * with `?oauth=<connection>&oauth_result=connected` or `&oauth_error=<what>`.
66
+ * with `?oauth=<connection>&oauth_result=connected` or `&oauth_error=<what>`. `authorizeParams` adds to the
67
+ * connection's for this consent alone — `{ prompt: 'select_account' }` to choose another account — never one the
68
+ * platform writes (`state`, `redirect_uri`, `scope`, PKCE's).
53
69
  */
54
70
  connect: (connection: string, options: {
55
71
  returnTo: string;
72
+ authorizeParams?: Record<string, string>;
56
73
  } & FunctionOAuthOwner) => Promise<{
57
74
  url: string;
58
75
  }>;
59
76
  status: (connection: string, options?: FunctionOAuthOwner) => Promise<FunctionOAuthStatus>;
60
77
  /**
61
78
  * A request to the provider's API with the token written in (`Authorization: Bearer`), renewed when it is about to
62
- * lapse and once more if the answer is 401. Only to the hosts the space declared (`allow.hosts`).
79
+ * lapse and once more if the answer is 401. Only to the hosts the space declared (`allow.hosts`). With nobody
80
+ * connected it refuses, `code: 'oauth-not-connected'` ({@link FunctionOAuthRefusal}).
63
81
  */
64
82
  fetch: (connection: string, url: string | URL, init?: Omit<FunctionFetchInit, 'credential'> & FunctionOAuthOwner) => Promise<Response>;
65
83
  /** Forgets the connection — revoked at the provider when it says where — and answers whether there was one. */
66
84
  disconnect: (connection: string, options?: FunctionOAuthOwner) => Promise<boolean>;
85
+ /**
86
+ * The access token itself, renewed first when it is about to lapse — only of a connection that declares
87
+ * `exposeToken: true`, for a provider's SDK in the page that asks for it (`getOAuthToken`). Whoever the code hands it
88
+ * to holds it until it lapses: answer it only to whom the connection is (its owner), from a route that checks so.
89
+ */
90
+ token: (connection: string, options?: FunctionOAuthOwner) => Promise<FunctionOAuthToken>;
91
+ };
92
+ /**
93
+ * The space's jobs, from its code: what starts one, reads it and stops it. Who may is the code's to decide — these are
94
+ * called from its routes and tasks, behind its own checks.
95
+ */
96
+ export type FunctionJobs = {
97
+ /**
98
+ * Starts one of the jobs this code declares (`jobs` in `defineFunctions`), with `input`: answered at once, the job
99
+ * `pending`. With `key`, at most one of that key runs at a time — starting it again while one is under way answers that
100
+ * one (a button pressed twice), and once it ended starts it over with the new input.
101
+ */
102
+ start: (name: string, input?: Record<string, unknown>, options?: {
103
+ key?: string;
104
+ }) => Promise<FunctionJobView>;
105
+ /** One of the space's jobs, as whoever may watch it sees it — or nothing, when there is none by that id. */
106
+ get: (id: string) => Promise<FunctionJobView | undefined>;
107
+ /** Sets it aside: it stops once its code saved, and waits as `paused`. Answers whether anything changed. */
108
+ pause: (id: string) => Promise<boolean>;
109
+ /** Puts a paused job back in the queue, to go on from what it saved. */
110
+ resume: (id: string) => Promise<boolean>;
111
+ /** Stops it for good: dropped if it waits, aborted if it runs. */
112
+ cancel: (id: string) => Promise<boolean>;
113
+ };
114
+ /**
115
+ * Why a slice of a job is asked to end (`job.stopping`): it was set aside (`pause`) or cancelled (`cancel`), its time in
116
+ * one go is up (`limit`) or the server is going away (`shutdown`). Whichever, what was saved is where it goes on from.
117
+ */
118
+ export type FunctionJobStop = 'pause' | 'cancel' | 'limit' | 'shutdown';
119
+ /**
120
+ * What a job's `run` is handed besides its input: the job, and how it keeps where it is. A job runs in slices — a pause,
121
+ * a lost server or its time in one go ending one — and every slice but the first starts from what the one before saved.
122
+ */
123
+ export type FunctionJobHandle<S = unknown> = {
124
+ id: string;
125
+ name: string;
126
+ /** What it last saved — `undefined` on its first slice, and whenever it never saved. */
127
+ state: S | undefined;
128
+ /** Which attempt this is, from 1: a slice after a failure is the next attempt, from the last save. */
129
+ attempt: number;
130
+ /**
131
+ * Keeps `state` durably: the next slice starts with it. JSON, within what the server keeps for one job. A method, not
132
+ * a property: so a job whose state has a type of its own is still one of `FunctionsDefinition['jobs']`.
133
+ */
134
+ save(state: S): Promise<void>;
135
+ /** How far it is, from 0 to 1, and what it is doing — for whoever watches it. Never fails the job. */
136
+ report: (fraction: number, step?: string) => void;
137
+ /** Why this slice is asked to end, once it is (`signal` aborted): save, and return. */
138
+ readonly stopping: FunctionJobStop | undefined;
139
+ /** Aborted when the slice is asked to end — the same as `ctx.signal`. Some seconds later it is cut. */
140
+ signal: AbortSignal;
141
+ };
142
+ /** A job of the space's: work longer than a request, run on the server slice by slice until it answers. */
143
+ export type FunctionJob<I extends Record<string, unknown> = Record<string, unknown>, S = unknown, R = unknown> = {
144
+ /**
145
+ * Who may watch it (`$job:<id>`, `useJob`) besides whoever started it — a channel's access, read against the visitor's
146
+ * permissions in the space. Absent, only whoever started it.
147
+ */
148
+ watch?: ActionAccess;
149
+ /** How long it may run, every slice together, in seconds — within what the server allows. */
150
+ maxSeconds?: number;
151
+ /**
152
+ * The work. What it answers is the job's result; an `ActionRefusal` fails it without a retry. A method, not a property:
153
+ * so a job typed with an input and a state of its own is still one of `FunctionsDefinition['jobs']`, and one written
154
+ * in place there gets an object for its input and `unknown` for its state.
155
+ */
156
+ run(input: I, job: FunctionJobHandle<S>, ctx: FunctionContext): R | Promise<R>;
67
157
  };
68
158
  /**
69
159
  * Everything a space's code can do besides computing — one object, the same wherever it runs. In a self-hosted server
@@ -124,6 +214,8 @@ export type FunctionContext = {
124
214
  log: (...values: unknown[]) => void;
125
215
  /** OAuth 2.0 through the space's declared connections — see {@link FunctionOAuth}. */
126
216
  oauth: FunctionOAuth;
217
+ /** The space's jobs — see {@link FunctionJobs}. */
218
+ jobs: FunctionJobs;
127
219
  /** Progress for a caller that asked for a stream — a no-op when nobody did. */
128
220
  emit: (chunk: unknown) => void;
129
221
  /** Aborted when the run is: cancelled, or out of time. Hand it to what can stop early. */
@@ -176,6 +268,8 @@ export type FunctionsDefinition = {
176
268
  * (OpenID) or its endpoints, the credential with the app's id and secret, the scopes.
177
269
  */
178
270
  oauth?: Record<string, FunctionOAuthConnection>;
271
+ /** Its jobs, by name (`ctx.jobs.start(name, input)`): work that outlives a request, run slice by slice. */
272
+ jobs?: Record<string, FunctionJob>;
179
273
  };
180
274
  /**
181
275
  * What a function throws to refuse, with a reason written for whoever asked — a wrong password, a board that is
@@ -19,7 +19,11 @@ var describeFunctions = (definition) => {
19
19
  } : {}),
20
20
  routes: isRecord(found.routes) ? Object.keys(found.routes) : [],
21
21
  limits: found.limits,
22
- oauth: found.oauth
22
+ oauth: found.oauth,
23
+ jobs: isRecord(found.jobs) ? Object.fromEntries(Object.entries(found.jobs).map(([name, job]) => [name, isRecord(job) ? {
24
+ watch: job.watch,
25
+ maxSeconds: job.maxSeconds
26
+ } : job])) : found.jobs
23
27
  };
24
28
  };
25
29
  /**
@@ -35,6 +39,42 @@ var createFunctionsDriver = (environment) => {
35
39
  const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
36
40
  const isCallable = (value) => typeof value === "function";
37
41
  const listOf = (value) => Array.isArray(value) ? value : [];
42
+ const isSignal = (value) => isRecord(value) && typeof value.aborted === "boolean" && typeof value.addEventListener === "function" && typeof value.removeEventListener === "function";
43
+ /** Why a request was cut: the signal's reason, as a web `fetch` rejects with it — an `AbortError` when it gave none. */
44
+ const abortedWith = (signal) => signal.reason instanceof Error ? signal.reason : Object.assign(/* @__PURE__ */ new Error("This operation was aborted"), { name: "AbortError" });
45
+ let requests = 0;
46
+ /**
47
+ * A request the code may cut short with its init's `signal`: the signal stays here — it does not cross — and the
48
+ * call is numbered, so that its firing tells the platform which request to cut (`abort`). The code stops waiting at
49
+ * once, with the signal's reason, as a web `fetch` does.
50
+ */
51
+ const cuttable = (message, init) => {
52
+ const { signal: given, ...rest } = init;
53
+ if (given === void 0 || given === null) return call({
54
+ ...message,
55
+ init: rest
56
+ });
57
+ if (!isSignal(given)) return Promise.reject(/* @__PURE__ */ new TypeError("The signal of a request is an AbortSignal"));
58
+ if (given.aborted) return Promise.reject(abortedWith(given));
59
+ const request = ++requests;
60
+ return new Promise((resolve, reject) => {
61
+ const cut = () => {
62
+ call({
63
+ op: "abort",
64
+ request
65
+ }).catch(() => void 0);
66
+ reject(abortedWith(given));
67
+ };
68
+ given.addEventListener("abort", cut, { once: true });
69
+ call({
70
+ ...message,
71
+ init: rest,
72
+ request
73
+ }).then(resolve, reject).finally(() => {
74
+ given.removeEventListener("abort", cut);
75
+ });
76
+ });
77
+ };
38
78
  /** A value as the wire can carry it; how a line reads is the platform's (`lineOf`), not the driver's. */
39
79
  const wireValue = (value) => {
40
80
  if (value instanceof Error) return `${value.name}: ${value.message}`;
@@ -73,11 +113,10 @@ var createFunctionsDriver = (environment) => {
73
113
  ...facts,
74
114
  kv,
75
115
  fetch: async (url, init = {}) => {
76
- const answer = await call({
116
+ const answer = await cuttable({
77
117
  op: "fetch",
78
- url: String(url),
79
- init
80
- });
118
+ url: String(url)
119
+ }, init);
81
120
  return responseOf(isRecord(answer) ? answer : {});
82
121
  },
83
122
  publish: async (topic, type, data) => {
@@ -130,12 +169,42 @@ var createFunctionsDriver = (environment) => {
130
169
  op: "data",
131
170
  file
132
171
  }),
172
+ jobs: {
173
+ start: (name, input = {}, options = {}) => call({
174
+ op: "jobs",
175
+ method: "start",
176
+ name,
177
+ input,
178
+ key: options.key
179
+ }),
180
+ get: (id) => call({
181
+ op: "jobs",
182
+ method: "get",
183
+ id
184
+ }).then((found) => found ?? void 0),
185
+ pause: (id) => call({
186
+ op: "jobs",
187
+ method: "pause",
188
+ id
189
+ }),
190
+ resume: (id) => call({
191
+ op: "jobs",
192
+ method: "resume",
193
+ id
194
+ }),
195
+ cancel: (id) => call({
196
+ op: "jobs",
197
+ method: "cancel",
198
+ id
199
+ })
200
+ },
133
201
  oauth: {
134
202
  connect: (connection, options = {}) => call({
135
203
  op: "oauth",
136
204
  method: "connect",
137
205
  connection,
138
206
  returnTo: options.returnTo,
207
+ authorizeParams: options.authorizeParams,
139
208
  owner: options.owner
140
209
  }),
141
210
  status: (connection, options = {}) => call({
@@ -150,16 +219,21 @@ var createFunctionsDriver = (environment) => {
150
219
  connection,
151
220
  owner: options.owner
152
221
  }),
222
+ token: (connection, options = {}) => call({
223
+ op: "oauth",
224
+ method: "token",
225
+ connection,
226
+ owner: options.owner
227
+ }),
153
228
  fetch: async (connection, url, init = {}) => {
154
229
  const { owner, ...rest } = init;
155
- const answer = await call({
230
+ const answer = await cuttable({
156
231
  op: "oauth",
157
232
  method: "fetch",
158
233
  connection,
159
234
  url: String(url),
160
- init: rest,
161
235
  owner
162
- });
236
+ }, rest);
163
237
  return responseOf(isRecord(answer) ? answer : {});
164
238
  }
165
239
  },
@@ -173,10 +247,63 @@ var createFunctionsDriver = (environment) => {
173
247
  signal
174
248
  };
175
249
  };
176
- /** One invocation: what a task returned (`null` for nothing), or the wire response a route answered. */
250
+ const STOPS = [
251
+ "pause",
252
+ "cancel",
253
+ "limit",
254
+ "shutdown"
255
+ ];
256
+ /**
257
+ * Why the slice is asked to end, once it is: the reason the signal was aborted with — said as itself in a runtime, and
258
+ * as the message of the `AbortError` the sandbox raises — and a cancel when it said none of them.
259
+ */
260
+ const stoppingOf = () => {
261
+ const current = signal;
262
+ if (typeof current !== "object" || current === null || !("aborted" in current) || current.aborted !== true) return;
263
+ const reason = "reason" in current ? current.reason : void 0;
264
+ const said = typeof reason === "string" ? reason : typeof reason === "object" && reason !== null && "message" in reason && typeof reason.message === "string" ? reason.message : void 0;
265
+ return said !== void 0 && STOPS.includes(said) ? said : "cancel";
266
+ };
267
+ /** A job's `run` and what it is handed: the slice, how it saves and reports, and why it is asked to end. */
268
+ const runJob = async (found, invocation, ctx) => {
269
+ const jobs = isRecord(found.jobs) ? found.jobs : {};
270
+ const name = String(invocation.name);
271
+ const job = Object.hasOwn(jobs, name) ? jobs[name] : void 0;
272
+ if (!isRecord(job) || !isCallable(job.run)) throw new Error(`This space's functions have no job "${name}"`);
273
+ const slice = isRecord(invocation.job) ? invocation.job : {};
274
+ const handle = {
275
+ id: slice.id,
276
+ name,
277
+ state: slice.state,
278
+ attempt: slice.attempt,
279
+ save: async (state) => {
280
+ await call({
281
+ op: "job",
282
+ method: "save",
283
+ state
284
+ });
285
+ },
286
+ report: (fraction, step) => {
287
+ call({
288
+ op: "job",
289
+ method: "report",
290
+ fraction,
291
+ step
292
+ }).catch(() => void 0);
293
+ },
294
+ get stopping() {
295
+ return stoppingOf();
296
+ },
297
+ signal
298
+ };
299
+ const value = await job.run(isRecord(invocation.input) ? invocation.input : {}, handle, ctx);
300
+ return value === void 0 ? null : value;
301
+ };
302
+ /** One invocation: what a task or a job's slice returned (`null` for nothing), or the wire response a route answered. */
177
303
  const invoke = async (definition, invocation) => {
178
304
  const found = isRecord(definition) ? definition : {};
179
305
  const ctx = contextOf(invocation);
306
+ if (invocation.kind === "job") return runJob(found, invocation, ctx);
180
307
  if (invocation.kind === "task") {
181
308
  const task = listOf(found.tasks).find((entry) => isRecord(entry) && `${String(entry.namespace)}.${String(entry.action)}` === invocation.name);
182
309
  if (!isRecord(task) || !isCallable(task.run)) throw new Error(`This space's functions have no task "${String(invocation.name)}"`);
@@ -0,0 +1,21 @@
1
+ import { ActionKvAdapter } from '../actions/types';
2
+ import { JobQueue, PubSubAdapter } from '@plitzi/sdk-shared';
3
+ export type JobControlOptions = {
4
+ queue: JobQueue;
5
+ /**
6
+ * The page server's realtime — the pub/sub its replicas listen on and the `kv` its retained messages are kept in — so
7
+ * whoever watches a job hears what an operator did to it. Absent, the queue changes and nobody is told until the job
8
+ * moves again.
9
+ */
10
+ realtime?: {
11
+ pubsub: PubSubAdapter;
12
+ kv: ActionKvAdapter;
13
+ };
14
+ };
15
+ export type JobControl = Pick<JobQueue, 'pause' | 'resume' | 'cancel' | 'requeue'>;
16
+ /**
17
+ * An operator's hold on the jobs, from a process that serves no pages — a deployment's API behind its Queue panel: the
18
+ * queue's own `pause`, `resume`, `cancel` and `requeue`, each said on `$job:<id>` when it changed a job of the spaces'
19
+ * functions, as the page server says it when its code does the same.
20
+ */
21
+ export declare const createJobControl: ({ queue, realtime }: JobControlOptions) => JobControl;
@@ -0,0 +1,43 @@
1
+ import { serverLog } from "../../helpers/serverLog.js";
2
+ import { jobViewOf } from "./jobs.js";
3
+ import { createRealtimeHub } from "../realtime/hub.js";
4
+ import { publishJobView } from "../realtime/jobs.js";
5
+ import { createRealtimeRetained } from "../realtime/retained.js";
6
+ //#region src/modules/functions/jobControl.ts
7
+ /**
8
+ * An operator's hold on the jobs, from a process that serves no pages — a deployment's API behind its Queue panel: the
9
+ * queue's own `pause`, `resume`, `cancel` and `requeue`, each said on `$job:<id>` when it changed a job of the spaces'
10
+ * functions, as the page server says it when its code does the same.
11
+ */
12
+ var createJobControl = ({ queue, realtime }) => {
13
+ const said = realtime ? {
14
+ retained: createRealtimeRetained(realtime.kv),
15
+ pubsub: realtime.pubsub
16
+ } : void 0;
17
+ const hub = said ? createRealtimeHub(said.pubsub, said.retained) : void 0;
18
+ const announce = async (spaceIds, jobId) => {
19
+ if (!hub || !said) return;
20
+ try {
21
+ const job = await queue.getJob(spaceIds, jobId);
22
+ if (job?.target.kind === "function") await publishJobView(hub, said.retained, {
23
+ spaceId: job.spaceId,
24
+ environment: job.environment
25
+ }, jobId, jobViewOf(job));
26
+ } catch (error) {
27
+ serverLog.warn("Actions", `job ${jobId}: its watchers were not told what an operator did`, error);
28
+ }
29
+ };
30
+ const told = (change) => async (spaceIds, jobId, ...rest) => {
31
+ const changed = await change(spaceIds, jobId, ...rest);
32
+ if (changed) await announce(spaceIds, jobId);
33
+ return changed;
34
+ };
35
+ return {
36
+ pause: told((spaceIds, jobId) => queue.pause(spaceIds, jobId)),
37
+ resume: told((spaceIds, jobId) => queue.resume(spaceIds, jobId)),
38
+ cancel: told((spaceIds, jobId) => queue.cancel(spaceIds, jobId)),
39
+ requeue: told((spaceIds, jobId, options) => queue.requeue(spaceIds, jobId, options))
40
+ };
41
+ };
42
+ //#endregion
43
+ export { createJobControl };
@@ -0,0 +1,98 @@
1
+ import { FunctionsConfig } from './config';
2
+ import { FunctionJobs, FunctionJobStop, FunctionsDefinition } from './contract';
3
+ import { SpaceFunctions } from './protocol';
4
+ import { TaskContextSource } from '../actions/runtime/runAction';
5
+ import { Job, JobQueue, Environment, FunctionJobManifest, FunctionJobView, RunUser, SpaceRevision } from '@plitzi/sdk-shared';
6
+ /**
7
+ * A space's jobs (`defineFunctions({ jobs })`): work longer than a request, kept in the actions' durable queue and run
8
+ * slice by slice — in the sandbox, in a space's runtime, or natively in a self-hosted server.
9
+ *
10
+ * A slice ends when the code returns (the job is done), throws (an attempt failed: the next starts from the last save),
11
+ * or is asked to stop: paused, cancelled, its time in one go up, the replica going away. `job.save` is the one
12
+ * checkpoint, and the rule that keeps a job from looping forever is that a slice cut by its time goes on only if it saved
13
+ * since it began.
14
+ */
15
+ /** What a server lets a space's jobs spend: a deployment sets it per space (its plan), each unset one the default's. */
16
+ export type FunctionJobLimits = {
17
+ /** Jobs running at once, across `pool`. */
18
+ running: number;
19
+ /** The spaces whose jobs `running` counts together — an account's. Default: the space alone. */
20
+ pool?: number[];
21
+ /** Jobs waiting (`pending` or `paused`) in one space. */
22
+ waiting: number;
23
+ /** How long one job may run, every slice together, in seconds. */
24
+ maxSeconds: number;
25
+ /** How long one slice runs in the sandbox before it is asked to save and go on in the next. */
26
+ sliceMs: number;
27
+ /** CPU one slice in the sandbox may use. */
28
+ sliceCpuMs: number;
29
+ /** Calls to `ctx` one slice in the sandbox may make. */
30
+ sliceCalls: number;
31
+ /** The most a job keeps of what it saves — and of its input — as JSON, in bytes. */
32
+ stateBytes: number;
33
+ };
34
+ export declare const DEFAULT_FUNCTION_JOB_LIMITS: Omit<FunctionJobLimits, 'pool'>;
35
+ /** How long a slice asked to end has to save and return before it is cut. */
36
+ export declare const JOB_GRACE_MS = 5000;
37
+ /** How a slice ended, for the worker to settle the job by. */
38
+ export type JobSliceOutcome = {
39
+ kind: 'done';
40
+ result: unknown;
41
+ spentMs: number;
42
+ } | {
43
+ kind: 'stopped';
44
+ stop: FunctionJobStop;
45
+ saved: boolean;
46
+ spentMs: number;
47
+ }
48
+ /** `final`: no attempt would change it — a refusal, a job no code declares, a job out of its time. */
49
+ | {
50
+ kind: 'failed';
51
+ error: string;
52
+ final: boolean;
53
+ refused: boolean;
54
+ spentMs: number;
55
+ }
56
+ /** Not started: the account runs as many jobs as it may, or may not run code right now. */
57
+ | {
58
+ kind: 'wait';
59
+ delayMs: number;
60
+ why: string;
61
+ };
62
+ /** Who and where a run of a space's code is, as `ctx.jobs` starts a job from it. */
63
+ export type JobRunScope = {
64
+ spaceId: number;
65
+ environment: Environment;
66
+ at?: SpaceRevision;
67
+ user?: RunUser;
68
+ };
69
+ export type FunctionJobsService = {
70
+ /** `ctx.jobs` for one run of a space's code, over the jobs that code declares. */
71
+ forRun: (run: JobRunScope, declared: Readonly<Record<string, FunctionJobManifest>>) => FunctionJobs;
72
+ /** Runs one slice of `job`, `signal` aborting with why (`pause`, `cancel`, `shutdown`) when its worker is told to. */
73
+ slice: (job: Job, signal: AbortSignal, workerId: string) => Promise<JobSliceOutcome>;
74
+ /** Says how the job is now to whoever watches it (`$job:<id>`). Never fails: a watcher missing a beat is not a fault. */
75
+ announce: (spaceId: number, jobId: string) => Promise<void>;
76
+ };
77
+ export type FunctionJobsDeps = {
78
+ /** Read when asked: the queue is made after the runner, and a server may run none. */
79
+ queue: () => JobQueue | undefined;
80
+ config: FunctionsConfig;
81
+ getFunctions?: (spaceId: number, at?: SpaceRevision) => Promise<SpaceFunctions | undefined>;
82
+ /** Read when a slice runs: the runner that makes it is made after this. */
83
+ taskContext: () => TaskContextSource;
84
+ /** Says the job as it is on `$job:<id>` — absent when the server has no realtime channels. */
85
+ publish?: (space: {
86
+ spaceId: number;
87
+ environment: string;
88
+ }, jobId: string, view: FunctionJobView) => Promise<void>;
89
+ maxAttempts: number;
90
+ };
91
+ /** What a job's declaration says besides its code, as a manifest holds it. */
92
+ export declare const jobsManifestOf: (definition: FunctionsDefinition) => Record<string, FunctionJobManifest>;
93
+ /**
94
+ * A job as whoever may watch it sees it: never its input or what it saved, and of a failure only the code's own refusal
95
+ * — anything else it threw can carry what a visitor must not read, and stays in the Queue for an operator.
96
+ */
97
+ export declare const jobViewOf: (job: Job) => FunctionJobView;
98
+ export declare const createFunctionJobs: ({ queue, config, getFunctions, taskContext, publish, maxAttempts }: FunctionJobsDeps) => FunctionJobsService;