@dxos/functions 0.5.4-main.f022b2e → 0.5.4-main.fb3ef83

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.
@@ -93,32 +93,21 @@ var FunctionRegistry = class extends Resource {
93
93
  };
94
94
 
95
95
  // packages/core/functions/src/handler.ts
96
- import { TextV0Type } from "@braneframe/types";
97
96
  import { PublicKey as PublicKey2 } from "@dxos/client";
98
97
  import { log as log2 } from "@dxos/log";
99
98
  import { nonNullable } from "@dxos/util";
100
99
  var __dxlog_file2 = "/home/runner/work/dxos/dxos/packages/core/functions/src/handler.ts";
101
- var subscriptionHandler = (handler, types) => {
102
- return async ({ event: { data }, context, response, ...rest }) => {
100
+ var subscriptionHandler = (handler) => {
101
+ return ({ event: { data }, context, ...rest }) => {
103
102
  const { client } = context;
104
103
  const space = data.spaceKey ? client.spaces.get(PublicKey2.from(data.spaceKey)) : void 0;
105
- if (!space) {
106
- log2.error("Invalid space", void 0, {
107
- F: __dxlog_file2,
108
- L: 90,
109
- S: void 0,
110
- C: (f, a) => f(...a)
111
- });
112
- return response.status(500);
113
- }
114
- registerTypes(space, types);
115
104
  const objects = space ? data.objects?.map((id) => space.db.getObjectById(id)).filter(nonNullable) : [];
116
105
  if (!!data.spaceKey && !space) {
117
106
  log2.warn("invalid space", {
118
107
  data
119
108
  }, {
120
109
  F: __dxlog_file2,
121
- L: 100,
110
+ L: 91,
122
111
  S: void 0,
123
112
  C: (f, a) => f(...a)
124
113
  });
@@ -128,7 +117,7 @@ var subscriptionHandler = (handler, types) => {
128
117
  objects: objects?.length
129
118
  }, {
130
119
  F: __dxlog_file2,
131
- L: 102,
120
+ L: 93,
132
121
  S: void 0,
133
122
  C: (f, a) => f(...a)
134
123
  });
@@ -142,22 +131,10 @@ var subscriptionHandler = (handler, types) => {
142
131
  }
143
132
  },
144
133
  context,
145
- response,
146
134
  ...rest
147
135
  });
148
136
  };
149
137
  };
150
- var registerTypes = (space, types = []) => {
151
- const registry = space.db.graph.runtimeSchemaRegistry;
152
- for (const type of [
153
- ...types,
154
- TextV0Type
155
- ]) {
156
- if (!registry.hasSchema(type)) {
157
- registry.registerSchema(type);
158
- }
159
- }
160
- };
161
138
 
162
139
  // packages/core/functions/src/runtime/dev-server.ts
163
140
  import express from "express";
@@ -657,7 +634,7 @@ import { log as log9 } from "@dxos/log";
657
634
  import { ComplexMap as ComplexMap2, diff as diff2 } from "@dxos/util";
658
635
 
659
636
  // packages/core/functions/src/trigger/type/subscription-trigger.ts
660
- import { TextV0Type as TextV0Type2 } from "@braneframe/types";
637
+ import { TextV0Type } from "@braneframe/types";
661
638
  import { debounce, UpdateScheduler } from "@dxos/async";
662
639
  import { Filter as Filter2 } from "@dxos/client/echo";
663
640
  import { createSubscription, getAutomergeObjectCore } from "@dxos/echo-db";
@@ -713,7 +690,7 @@ var createSubscriptionTrigger = async (ctx, space, spec, callback) => {
713
690
  if (deep) {
714
691
  for (const object of objects) {
715
692
  const content = object.content;
716
- if (content instanceof TextV0Type2) {
693
+ if (content instanceof TextV0Type) {
717
694
  subscriptions.push(getAutomergeObjectCore(content).updates.on(debounce(() => subscription.update([
718
695
  object
719
696
  ]), 1e3)));
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/function/function-registry.ts", "../../../src/handler.ts", "../../../src/runtime/dev-server.ts", "../../../src/runtime/scheduler.ts", "../../../src/trigger/trigger-registry.ts", "../../../src/trigger/type/subscription-trigger.ts", "../../../src/trigger/type/timer-trigger.ts", "../../../src/trigger/type/webhook-trigger.ts", "../../../src/trigger/type/websocket-trigger.ts"],
4
- "sourcesContent": ["//\n// Copyright 2024 DXOS.org\n//\n\nimport { Event } from '@dxos/async';\nimport { type Client } from '@dxos/client';\nimport { create, Filter, type Space } from '@dxos/client/echo';\nimport { type Context, Resource } from '@dxos/context';\nimport { PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { ComplexMap, diff } from '@dxos/util';\n\nimport { FunctionDef, type FunctionManifest } from '../types';\n\nexport type FunctionsRegisteredEvent = {\n space: Space;\n added: FunctionDef[];\n};\n\nexport class FunctionRegistry extends Resource {\n private readonly _functionBySpaceKey = new ComplexMap<PublicKey, FunctionDef[]>(PublicKey.hash);\n\n public readonly registered = new Event<FunctionsRegisteredEvent>();\n\n constructor(private readonly _client: Client) {\n super();\n }\n\n public getFunctions(space: Space): FunctionDef[] {\n return this._functionBySpaceKey.get(space.key) ?? [];\n }\n\n /**\n * Loads function definitions from the manifest into the space.\n * We first load all the definitions from the space to deduplicate by functionId.\n */\n public async register(space: Space, functions: FunctionManifest['functions']): Promise<void> {\n log('register', { space: space.key, functions: functions?.length ?? 0 });\n if (!functions?.length) {\n return;\n }\n if (!space.db.graph.runtimeSchemaRegistry.hasSchema(FunctionDef)) {\n space.db.graph.runtimeSchemaRegistry.registerSchema(FunctionDef);\n }\n\n // Sync definitions.\n const { objects: existing } = await space.db.query(Filter.schema(FunctionDef)).run();\n const { added } = diff(existing, functions, (a, b) => a.uri === b.uri);\n // TODO(burdon): Update existing templates.\n added.forEach((def) => space.db.add(create(FunctionDef, def)));\n }\n\n protected override async _open(): Promise<void> {\n log.info('opening...');\n const spacesSubscription = this._client.spaces.subscribe(async (spaces) => {\n for (const space of spaces) {\n if (this._functionBySpaceKey.has(space.key)) {\n continue;\n }\n\n const registered: FunctionDef[] = [];\n this._functionBySpaceKey.set(space.key, registered);\n await space.waitUntilReady();\n if (this._ctx.disposed) {\n break;\n }\n\n // Subscribe to updates.\n this._ctx.onDispose(\n space.db.query(Filter.schema(FunctionDef)).subscribe(({ objects }) => {\n const { added } = diff(registered, objects, (a, b) => a.uri === b.uri);\n // TODO(burdon): Update and remove.\n if (added.length > 0) {\n registered.push(...added);\n this.registered.emit({ space, added });\n }\n }),\n );\n }\n });\n\n // TODO(burdon): API: Normalize unsubscribe methods.\n this._ctx.onDispose(() => spacesSubscription.unsubscribe());\n }\n\n protected override async _close(_: Context): Promise<void> {\n log.info('closing...');\n this._functionBySpaceKey.clear();\n }\n}\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport { TextV0Type } from '@braneframe/types';\nimport { type Client, PublicKey } from '@dxos/client';\nimport { type Space } from '@dxos/client/echo';\nimport { type EchoReactiveObject, type S } from '@dxos/echo-schema';\nimport { log } from '@dxos/log';\nimport { nonNullable } from '@dxos/util';\n\n// TODO(burdon): Model after http request. Ref Lambda/OpenFaaS.\n// https://docs.aws.amazon.com/lambda/latest/dg/typescript-handler.html\n// https://www.serverless.com/framework/docs/providers/aws/guide/serverless.yml/#functions\n// https://www.npmjs.com/package/aws-lambda\n\n/**\n * Function handler.\n */\nexport type FunctionHandler<TData = {}, TMeta = {}> = (params: {\n context: FunctionContext;\n event: FunctionEvent<TData, TMeta>;\n response: FunctionResponse;\n}) => Promise<FunctionResponse | void>;\n\n/**\n * Function context.\n */\nexport interface FunctionContext {\n // TODO(burdon): Limit access to individual space.\n client: Client;\n // TODO(burdon): Replace with storage service abstraction.\n dataDir?: string;\n}\n\n/**\n * Event payload.\n */\nexport type FunctionEvent<TData = {}, TMeta = {}> = {\n data: FunctionEventMeta<TMeta> & TData;\n};\n\n/**\n * Metadata from trigger.\n */\nexport type FunctionEventMeta<TMeta = {}> = {\n meta: TMeta;\n};\n\n/**\n * Function response.\n */\nexport interface FunctionResponse {\n status(code: number): FunctionResponse;\n}\n\n//\n// Subscription utils.\n//\n\nexport type RawSubscriptionData = {\n spaceKey?: string;\n objects?: string[];\n};\n\nexport type SubscriptionData = {\n space?: Space;\n objects?: EchoReactiveObject<any>[];\n};\n\n/**\n * Handler wrapper for subscription events; extracts space and objects.\n *\n * To test:\n * ```\n * curl -s -X POST -H \"Content-Type: application/json\" --data '{\"space\": \"0446...1cbb\"}' http://localhost:7100/dev/email-extractor\n * ```\n *\n * NOTE: Get space key from devtools or `dx space list --json`\n */\n// TODO(burdon): Evolve into plugin definition like Composer.\nexport const subscriptionHandler = <TMeta>(\n handler: FunctionHandler<SubscriptionData, TMeta>,\n types?: S.Schema<any>[],\n): FunctionHandler<RawSubscriptionData, TMeta> => {\n return async ({ event: { data }, context, response, ...rest }) => {\n const { client } = context;\n const space = data.spaceKey ? client.spaces.get(PublicKey.from(data.spaceKey)) : undefined;\n if (!space) {\n log.error('Invalid space');\n return response.status(500);\n }\n\n registerTypes(space, types);\n const objects = space\n ? data.objects?.map<EchoReactiveObject<any> | undefined>((id) => space!.db.getObjectById(id)).filter(nonNullable)\n : [];\n\n if (!!data.spaceKey && !space) {\n log.warn('invalid space', { data });\n } else {\n log.info('handler', { space: space?.key.truncate(), objects: objects?.length });\n }\n\n return handler({ event: { data: { ...data, space, objects } }, context, response, ...rest });\n };\n};\n\n// TODO(burdon): Evolve types as part of function metadata.\nconst registerTypes = (space: Space, types: S.Schema<any>[] = []) => {\n const registry = space.db.graph.runtimeSchemaRegistry;\n for (const type of [...types, TextV0Type]) {\n if (!registry.hasSchema(type)) {\n registry.registerSchema(type);\n }\n }\n};\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport express from 'express';\nimport { getPort } from 'get-port-please';\nimport type http from 'http';\nimport { join } from 'node:path';\n\nimport { Event, Trigger } from '@dxos/async';\nimport { type Client } from '@dxos/client';\nimport { Context } from '@dxos/context';\nimport { invariant } from '@dxos/invariant';\nimport { log } from '@dxos/log';\n\nimport { type FunctionRegistry } from '../function';\nimport { type FunctionContext, type FunctionEvent, type FunctionHandler, type FunctionResponse } from '../handler';\nimport { type FunctionDef } from '../types';\n\nexport type DevServerOptions = {\n baseDir: string;\n port?: number;\n reload?: boolean;\n dataDir?: string;\n};\n\n/**\n * Functions dev server provides a local HTTP server for testing functions.\n */\nexport class DevServer {\n private _ctx = createContext();\n\n // Function handlers indexed by name (URL path).\n private readonly _handlers: Record<string, { def: FunctionDef; handler: FunctionHandler<any> }> = {};\n\n private _server?: http.Server;\n private _port?: number;\n private _functionServiceRegistration?: string;\n private _proxy?: string;\n private _seq = 0;\n\n public readonly update = new Event<number>();\n\n constructor(\n private readonly _client: Client,\n private readonly _functionsRegistry: FunctionRegistry,\n private readonly _options: DevServerOptions,\n ) {\n // TODO(burdon): Add/remove listener in start/stop.\n this._functionsRegistry.registered.on(async ({ added }) => {\n added.forEach((def) => this._load(def));\n await this._safeUpdateRegistration();\n log('new functions loaded', { added });\n });\n }\n\n get stats() {\n return {\n seq: this._seq,\n };\n }\n\n get endpoint() {\n invariant(this._port);\n return `http://localhost:${this._port}`;\n }\n\n get proxy() {\n return this._proxy;\n }\n\n get functions() {\n return Object.values(this._handlers);\n }\n\n async start() {\n invariant(!this._server);\n log.info('starting...');\n this._ctx = createContext();\n\n // TODO(burdon): Move to hono.\n const app = express();\n app.use(express.json());\n\n app.post('/:path', async (req, res) => {\n const { path } = req.params;\n try {\n log.info('calling', { path });\n if (this._options.reload) {\n const { def } = this._handlers['/' + path];\n await this._load(def, true);\n }\n\n // TODO(burdon): Get function context.\n res.statusCode = await this.invoke('/' + path, req.body);\n res.end();\n } catch (err: any) {\n log.catch(err);\n res.statusCode = 500;\n res.end();\n }\n });\n\n this._port = await getPort({ host: 'localhost', port: 7200, portRange: [7200, 7299] });\n this._server = app.listen(this._port);\n\n try {\n // Register functions.\n const { registrationId, endpoint } = await this._client.services.services.FunctionRegistryService!.register({\n endpoint: this.endpoint,\n });\n\n log.info('registered', { endpoint });\n this._proxy = endpoint;\n this._functionServiceRegistration = registrationId;\n\n // Open after registration, so that it can be updated with the list of function definitions.\n await this._functionsRegistry.open(this._ctx);\n } catch (err: any) {\n await this.stop();\n throw new Error('FunctionRegistryService not available (check plugin is configured).');\n }\n\n log.info('started', { port: this._port });\n }\n\n async stop() {\n invariant(this._server);\n log.info('stopping...');\n\n const trigger = new Trigger();\n this._server.close(async () => {\n log.info('server stopped');\n try {\n if (this._functionServiceRegistration) {\n invariant(this._client.services.services.FunctionRegistryService);\n await this._client.services.services.FunctionRegistryService.unregister({\n registrationId: this._functionServiceRegistration,\n });\n\n log.info('unregistered', { registrationId: this._functionServiceRegistration });\n this._functionServiceRegistration = undefined;\n this._proxy = undefined;\n }\n\n trigger.wake();\n } catch (err) {\n trigger.throw(err as Error);\n }\n });\n\n await trigger.wait();\n this._port = undefined;\n this._server = undefined;\n log.info('stopped');\n }\n\n /**\n * Load function.\n */\n private async _load(def: FunctionDef, force?: boolean | undefined) {\n const { uri, route, handler } = def;\n const filePath = join(this._options.baseDir, handler);\n log.info('loading', { uri, force });\n\n // Remove from cache.\n if (force) {\n Object.keys(require.cache)\n .filter((key) => key.startsWith(filePath))\n .forEach((key) => {\n delete require.cache[key];\n });\n }\n\n // TODO(burdon): Import types.\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const module = require(filePath);\n if (typeof module.default !== 'function') {\n throw new Error(`Handler must export default function: ${uri}`);\n }\n\n this._handlers[route] = { def, handler: module.default };\n }\n\n private async _safeUpdateRegistration(): Promise<void> {\n invariant(this._functionServiceRegistration);\n try {\n await this._client.services.services.FunctionRegistryService!.updateRegistration({\n registrationId: this._functionServiceRegistration,\n functions: this.functions.map(({ def: { id, route } }) => ({ id, route })),\n });\n } catch (err) {\n log.catch(err);\n }\n }\n\n /**\n * Invoke function.\n */\n public async invoke(path: string, data: any): Promise<number> {\n const seq = ++this._seq;\n const now = Date.now();\n\n log.info('req', { seq, path });\n const statusCode = await this._invoke(path, { data });\n\n log.info('res', { seq, path, statusCode, duration: Date.now() - now });\n this.update.emit(statusCode);\n return statusCode;\n }\n\n private async _invoke(path: string, event: FunctionEvent) {\n const { handler } = this._handlers[path] ?? {};\n invariant(handler, `invalid path: ${path}`);\n const context: FunctionContext = {\n client: this._client,\n dataDir: this._options.dataDir,\n };\n\n let statusCode = 200;\n const response: FunctionResponse = {\n status: (code: number) => {\n statusCode = code;\n return response;\n },\n };\n\n await handler({ context, event, response });\n return statusCode;\n }\n}\n\nconst createContext = () => new Context({ name: 'DevServer' });\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport path from 'node:path';\n\nimport { Mutex } from '@dxos/async';\nimport { type Space } from '@dxos/client/echo';\nimport { Context } from '@dxos/context';\nimport { log } from '@dxos/log';\n\nimport { type FunctionRegistry } from '../function';\nimport { type FunctionEventMeta } from '../handler';\nimport { type TriggerRegistry } from '../trigger';\nimport { type FunctionDef, type FunctionManifest, type FunctionTrigger } from '../types';\n\nexport type Callback = (data: any) => Promise<void | number>;\n\nexport type SchedulerOptions = {\n endpoint?: string;\n callback?: Callback;\n};\n\n/**\n * The scheduler triggers function execution based on various triggers.\n */\nexport class Scheduler {\n private _ctx = createContext();\n\n private readonly _functionUriToCallMutex = new Map<string, Mutex>();\n\n constructor(\n public readonly functions: FunctionRegistry,\n public readonly triggers: TriggerRegistry,\n private readonly _options: SchedulerOptions = {},\n ) {\n this.functions.registered.on(async ({ space, added }) => {\n await this._safeActivateTriggers(space, this.triggers.getInactiveTriggers(space), added);\n });\n this.triggers.registered.on(async ({ space, triggers }) => {\n await this._safeActivateTriggers(space, triggers, this.functions.getFunctions(space));\n });\n }\n\n async start() {\n await this._ctx.dispose();\n this._ctx = createContext();\n await this.functions.open(this._ctx);\n await this.triggers.open(this._ctx);\n }\n\n async stop() {\n await this._ctx.dispose();\n await this.functions.close();\n await this.triggers.close();\n }\n\n // TODO(burdon): Remove and update registries directly.\n public async register(space: Space, manifest: FunctionManifest) {\n await this.functions.register(space, manifest.functions);\n await this.triggers.register(space, manifest);\n }\n\n private async _safeActivateTriggers(\n space: Space,\n triggers: FunctionTrigger[],\n functions: FunctionDef[],\n ): Promise<void> {\n const mountTasks = triggers.map((trigger) => {\n return this.activate(space, functions, trigger);\n });\n await Promise.all(mountTasks).catch(log.catch);\n }\n\n private async activate(space: Space, functions: FunctionDef[], trigger: FunctionTrigger) {\n const definition = functions.find((def) => def.uri === trigger.function);\n if (!definition) {\n log.info('function is not found for trigger', { trigger });\n return;\n }\n\n await this.triggers.activate(space, trigger, async (args) => {\n const mutex = this._functionUriToCallMutex.get(definition.uri) ?? new Mutex();\n this._functionUriToCallMutex.set(definition.uri, mutex);\n\n log.info('function triggered, waiting for mutex', { uri: definition.uri });\n return mutex.executeSynchronized(() => {\n log.info('mutex acquired', { uri: definition.uri });\n return this._execFunction(definition, trigger, {\n meta: trigger.meta ?? {},\n data: { ...args, spaceKey: space.key },\n });\n });\n });\n\n log('activated trigger', { space: space.key, trigger });\n }\n\n private async _execFunction<TData, TMeta>(\n def: FunctionDef,\n trigger: FunctionTrigger,\n { data, meta }: { data: TData; meta?: TMeta },\n ): Promise<number> {\n let status = 0;\n try {\n // TODO(burdon): Pass in Space key (common context)?\n const payload = Object.assign({}, meta && ({ meta } satisfies FunctionEventMeta<TMeta>), data);\n\n const { endpoint, callback } = this._options;\n if (endpoint) {\n // TODO(burdon): Move out of scheduler (generalize as callback).\n const url = path.join(endpoint, def.route);\n log.info('exec', { function: def.uri, url, triggerType: trigger.spec.type });\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(payload),\n });\n\n status = response.status;\n } else if (callback) {\n log.info('exec', { function: def.uri });\n status = (await callback(payload)) ?? 200;\n }\n\n // Check errors.\n if (status && status >= 400) {\n throw new Error(`Response: ${status}`);\n }\n\n // const result = await response.json();\n log.info('done', { function: def.uri, status });\n } catch (err: any) {\n log.error('error', { function: def.uri, error: err.message });\n status = 500;\n }\n\n return status;\n }\n}\n\nconst createContext = () => new Context({ name: 'FunctionScheduler' });\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { Event } from '@dxos/async';\nimport { type Client } from '@dxos/client';\nimport { create, Filter, getMeta, type Space } from '@dxos/client/echo';\nimport { Context, Resource } from '@dxos/context';\nimport { compareForeignKeys, ECHO_ATTR_META, foreignKey } from '@dxos/echo-schema';\nimport { invariant } from '@dxos/invariant';\nimport { PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { ComplexMap, diff } from '@dxos/util';\n\nimport { createSubscriptionTrigger, createTimerTrigger, createWebhookTrigger, createWebsocketTrigger } from './type';\nimport { type FunctionManifest, FunctionTrigger, type FunctionTriggerType, type TriggerSpec } from '../types';\n\ntype ResponseCode = number;\n\nexport type TriggerCallback = (args: object) => Promise<ResponseCode>;\n\n// TODO(burdon): Make object?\nexport type TriggerFactory<Spec extends TriggerSpec, Options = any> = (\n ctx: Context,\n space: Space,\n spec: Spec,\n callback: TriggerCallback,\n options?: Options,\n) => Promise<void>;\n\nexport type TriggerHandlerMap = { [type in FunctionTriggerType]: TriggerFactory<any> };\n\nconst triggerHandlers: TriggerHandlerMap = {\n subscription: createSubscriptionTrigger,\n timer: createTimerTrigger,\n webhook: createWebhookTrigger,\n websocket: createWebsocketTrigger,\n};\n\nexport type TriggerEvent = {\n space: Space;\n triggers: FunctionTrigger[];\n};\n\ntype RegisteredTrigger = {\n activationCtx?: Context;\n trigger: FunctionTrigger;\n};\n\nexport class TriggerRegistry extends Resource {\n private readonly _triggersBySpaceKey = new ComplexMap<PublicKey, RegisteredTrigger[]>(PublicKey.hash);\n\n public readonly registered = new Event<TriggerEvent>();\n public readonly removed = new Event<TriggerEvent>();\n\n constructor(\n private readonly _client: Client,\n private readonly _options?: TriggerHandlerMap,\n ) {\n super();\n }\n\n public getActiveTriggers(space: Space): FunctionTrigger[] {\n return this._getTriggers(space, (t) => t.activationCtx != null);\n }\n\n public getInactiveTriggers(space: Space): FunctionTrigger[] {\n return this._getTriggers(space, (t) => t.activationCtx == null);\n }\n\n async activate(space: Space, trigger: FunctionTrigger, callback: TriggerCallback): Promise<void> {\n log('activate', { space: space.key, trigger });\n\n const activationCtx = new Context({ name: `FunctionTrigger-${trigger.function}` });\n this._ctx.onDispose(() => activationCtx.dispose());\n const registeredTrigger = this._triggersBySpaceKey.get(space.key)?.find((reg) => reg.trigger.id === trigger.id);\n invariant(registeredTrigger, `Trigger is not registered: ${trigger.function}`);\n registeredTrigger.activationCtx = activationCtx;\n\n try {\n const options = this._options?.[trigger.spec.type];\n await triggerHandlers[trigger.spec.type](activationCtx, space, trigger.spec, callback, options);\n } catch (err) {\n delete registeredTrigger.activationCtx;\n throw err;\n }\n }\n\n /**\n * Loads triggers from the manifest into the space.\n */\n public async register(space: Space, manifest: FunctionManifest): Promise<void> {\n log('register', { space: space.key });\n if (!manifest.triggers?.length) {\n return;\n }\n\n if (!space.db.graph.runtimeSchemaRegistry.hasSchema(FunctionTrigger)) {\n space.db.graph.runtimeSchemaRegistry.registerSchema(FunctionTrigger);\n }\n\n // Create FK to enable syncing if none are set (NOTE: Possible collision).\n const manifestTriggers = manifest.triggers.map((trigger) => {\n let keys = trigger[ECHO_ATTR_META]?.keys;\n delete trigger[ECHO_ATTR_META];\n if (!keys?.length) {\n keys = [foreignKey('manifest', [trigger.function, trigger.spec.type].join(':'))];\n }\n\n return create(FunctionTrigger, trigger, { keys });\n });\n\n // Sync triggers.\n const { objects: existing } = await space.db.query(Filter.schema(FunctionTrigger)).run();\n const { added } = diff(existing, manifestTriggers, compareForeignKeys);\n\n // TODO(burdon): Update existing.\n added.forEach((trigger) => {\n space.db.add(trigger);\n log.info('added', { meta: getMeta(trigger) });\n });\n\n if (added.length > 0) {\n await space.db.flush();\n }\n }\n\n protected override async _open(): Promise<void> {\n log.info('open...');\n const spaceListSubscription = this._client.spaces.subscribe(async (spaces) => {\n for (const space of spaces) {\n if (this._triggersBySpaceKey.has(space.key)) {\n continue;\n }\n\n const registered: RegisteredTrigger[] = [];\n this._triggersBySpaceKey.set(space.key, registered);\n await space.waitUntilReady();\n if (this._ctx.disposed) {\n break;\n }\n\n // Subscribe to updates.\n this._ctx.onDispose(\n space.db.query(Filter.schema(FunctionTrigger)).subscribe(async ({ objects: current }) => {\n log.info('update', { space: space.key, registered: registered.length, current: current.length });\n await this._handleRemovedTriggers(space, current, registered);\n this._handleNewTriggers(space, current, registered);\n }),\n );\n }\n });\n\n this._ctx.onDispose(() => spaceListSubscription.unsubscribe());\n log.info('opened');\n }\n\n protected override async _close(_: Context): Promise<void> {\n log.info('close...');\n this._triggersBySpaceKey.clear();\n log.info('closed');\n }\n\n private _handleNewTriggers(space: Space, current: FunctionTrigger[], registered: RegisteredTrigger[]) {\n const added = current.filter((candidate) => {\n return candidate.enabled && registered.find((reg) => reg.trigger.id === candidate.id) == null;\n });\n\n if (added.length > 0) {\n const newRegisteredTriggers: RegisteredTrigger[] = added.map((trigger) => ({ trigger }));\n registered.push(...newRegisteredTriggers);\n log.info('added', () => ({\n spaceKey: space.key,\n triggers: added.map((trigger) => trigger.function),\n }));\n\n this.registered.emit({ space, triggers: added });\n }\n }\n\n private async _handleRemovedTriggers(\n space: Space,\n current: FunctionTrigger[],\n registered: RegisteredTrigger[],\n ): Promise<void> {\n const removed: FunctionTrigger[] = [];\n for (let i = registered.length - 1; i >= 0; i--) {\n const wasRemoved =\n current.filter((trigger) => trigger.enabled).find((trigger) => trigger.id === registered[i].trigger.id) == null;\n if (wasRemoved) {\n const unregistered = registered.splice(i, 1)[0];\n await unregistered.activationCtx?.dispose();\n removed.push(unregistered.trigger);\n }\n }\n\n if (removed.length > 0) {\n log.info('removed', () => ({\n spaceKey: space.key,\n triggers: removed.map((trigger) => trigger.function),\n }));\n\n this.removed.emit({ space, triggers: removed });\n }\n }\n\n private _getTriggers(space: Space, predicate: (trigger: RegisteredTrigger) => boolean): FunctionTrigger[] {\n const allSpaceTriggers = this._triggersBySpaceKey.get(space.key) ?? [];\n return allSpaceTriggers.filter(predicate).map((trigger) => trigger.trigger);\n }\n}\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { TextV0Type } from '@braneframe/types';\nimport { debounce, UpdateScheduler } from '@dxos/async';\nimport { Filter, type Space } from '@dxos/client/echo';\nimport { type Context } from '@dxos/context';\nimport { createSubscription, getAutomergeObjectCore, type Query } from '@dxos/echo-db';\nimport { log } from '@dxos/log';\n\nimport type { SubscriptionTrigger } from '../../types';\nimport { type TriggerCallback, type TriggerFactory } from '../trigger-registry';\n\nexport const createSubscriptionTrigger: TriggerFactory<SubscriptionTrigger> = async (\n ctx: Context,\n space: Space,\n spec: SubscriptionTrigger,\n callback: TriggerCallback,\n) => {\n const objectIds = new Set<string>();\n const task = new UpdateScheduler(\n ctx,\n async () => {\n if (objectIds.size > 0) {\n const objects = Array.from(objectIds);\n objectIds.clear();\n await callback({ objects });\n }\n },\n { maxFrequency: 4 },\n );\n\n // TODO(burdon): Factor out diff.\n // TODO(burdon): Don't fire initially?\n // TODO(burdon): Create queue. Only allow one invocation per trigger at a time?\n const subscriptions: (() => void)[] = [];\n const subscription = createSubscription(({ added, updated }) => {\n const sizeBefore = objectIds.size;\n for (const object of added) {\n objectIds.add(object.id);\n }\n for (const object of updated) {\n objectIds.add(object.id);\n }\n if (objectIds.size > sizeBefore) {\n log.info('updated', { added: added.length, updated: updated.length });\n task.trigger();\n }\n });\n\n subscriptions.push(() => subscription.unsubscribe());\n\n // TODO(burdon): Disable trigger if keeps failing.\n const { filter, options: { deep, delay } = {} } = spec;\n const update = ({ objects }: Query) => {\n log.info('update', { objects: objects.length });\n subscription.update(objects);\n\n // TODO(burdon): Hack to monitor changes to Document's text object.\n if (deep) {\n for (const object of objects) {\n const content = object.content;\n if (content instanceof TextV0Type) {\n subscriptions.push(\n getAutomergeObjectCore(content).updates.on(debounce(() => subscription.update([object]), 1_000)),\n );\n }\n }\n }\n };\n\n // TODO(burdon): OR not working.\n // TODO(burdon): [Bug]: all callbacks are fired on the first mutation.\n // TODO(burdon): [Bug]: not updated when document is deleted (either top or hierarchically).\n log.info('subscription', { filter });\n // const query = triggerCtx.space.db.query(Filter.or(filter.map(({ type, props }) => Filter.typename(type, props))));\n if (filter) {\n const query = space.db.query(Filter.typename(filter[0].type, filter[0].props));\n subscriptions.push(query.subscribe(delay ? debounce(update, delay) : update));\n }\n\n ctx.onDispose(() => {\n subscriptions.forEach((unsubscribe) => unsubscribe());\n });\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { CronJob } from 'cron';\n\nimport { DeferredTask } from '@dxos/async';\nimport { type Space } from '@dxos/client/echo';\nimport { type Context } from '@dxos/context';\nimport { log } from '@dxos/log';\n\nimport type { TimerTrigger } from '../../types';\nimport { type TriggerCallback, type TriggerFactory } from '../trigger-registry';\n\nexport const createTimerTrigger: TriggerFactory<TimerTrigger> = async (\n ctx: Context,\n space: Space,\n spec: TimerTrigger,\n callback: TriggerCallback,\n) => {\n const task = new DeferredTask(ctx, async () => {\n await callback({});\n });\n\n let last = 0;\n let run = 0;\n // https://www.npmjs.com/package/cron#constructor\n const job = CronJob.from({\n cronTime: spec.cron,\n runOnInit: false,\n onTick: () => {\n // TODO(burdon): Check greater than 30s (use cron-parser).\n const now = Date.now();\n const delta = last ? now - last : 0;\n last = now;\n\n run++;\n log.info('tick', { space: space.key.truncate(), count: run, delta });\n task.schedule();\n },\n });\n\n job.start();\n ctx.onDispose(() => job.stop());\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { getPort } from 'get-port-please';\nimport http from 'node:http';\n\nimport { type Space } from '@dxos/client/echo';\nimport { type Context } from '@dxos/context';\nimport { log } from '@dxos/log';\n\nimport type { WebhookTrigger } from '../../types';\nimport { type TriggerCallback, type TriggerFactory } from '../trigger-registry';\n\nexport const createWebhookTrigger: TriggerFactory<WebhookTrigger> = async (\n ctx: Context,\n space: Space,\n spec: WebhookTrigger,\n callback: TriggerCallback,\n) => {\n // TODO(burdon): Enable POST hook with payload.\n const server = http.createServer(async (req, res) => {\n if (req.method !== spec.method) {\n res.statusCode = 405;\n return res.end();\n }\n res.statusCode = await callback({});\n res.end();\n });\n\n // TODO(burdon): Not used.\n // const DEF_PORT_RANGE = { min: 7500, max: 7599 };\n // const portRange = Object.assign({}, trigger.port, DEF_PORT_RANGE) as WebhookTrigger['port'];\n const port = await getPort({\n random: true,\n // portRange: [portRange!.min, portRange!.max],\n });\n\n // TODO(burdon): Update trigger object with actual port.\n server.listen(port, () => {\n log.info('started webhook', { port });\n spec.port = port;\n });\n\n ctx.onDispose(() => {\n server.close();\n });\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport WebSocket from 'ws';\n\nimport { sleep, Trigger } from '@dxos/async';\nimport { type Space } from '@dxos/client/echo';\nimport { type Context } from '@dxos/context';\nimport { log } from '@dxos/log';\n\nimport { type WebsocketTrigger } from '../../types';\nimport { type TriggerCallback, type TriggerFactory } from '../trigger-registry';\n\ninterface WebsocketTriggerOptions {\n retryDelay: number;\n maxAttempts: number;\n}\n\n/**\n * Websocket.\n * NOTE: The port must be unique, so the same hook cannot be used for multiple spaces.\n */\nexport const createWebsocketTrigger: TriggerFactory<WebsocketTrigger, WebsocketTriggerOptions> = async (\n ctx: Context,\n space: Space,\n spec: WebsocketTrigger,\n callback: TriggerCallback,\n options: WebsocketTriggerOptions = { retryDelay: 2, maxAttempts: 5 },\n) => {\n const { url, init } = spec;\n\n let ws: WebSocket;\n for (let attempt = 1; attempt <= options.maxAttempts; attempt++) {\n const open = new Trigger<boolean>();\n\n ws = new WebSocket(url);\n Object.assign(ws, {\n onopen: () => {\n log.info('opened', { url });\n if (spec.init) {\n ws.send(new TextEncoder().encode(JSON.stringify(init)));\n }\n\n open.wake(true);\n },\n\n onclose: (event) => {\n log.info('closed', { url, code: event.code });\n // Reconnect if server closes (e.g., CF restart).\n // https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent/code\n if (event.code === 1006) {\n setTimeout(async () => {\n log.info(`reconnecting in ${options.retryDelay}s...`, { url });\n await createWebsocketTrigger(ctx, space, spec, callback, options);\n }, options.retryDelay * 1_000);\n }\n\n open.wake(false);\n },\n\n onerror: (event) => {\n log.catch(event.error, { url });\n },\n\n onmessage: async (event) => {\n try {\n log.info('message');\n const data = JSON.parse(new TextDecoder().decode(event.data as Uint8Array));\n await callback({ data });\n } catch (err) {\n log.catch(err, { url });\n }\n },\n } satisfies Partial<WebSocket>);\n\n const isOpen = await open.wait();\n if (isOpen) {\n break;\n } else {\n const wait = Math.pow(attempt, 2) * options.retryDelay;\n if (attempt < options.maxAttempts) {\n log.warn(`failed to connect; trying again in ${wait}s`, { attempt });\n await sleep(wait * 1_000);\n }\n }\n }\n\n ct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;MACnC;IACF;AAEA,QAAIR,QAAQ+B,SAAS,GAAG;AACtBrB,MAAAA,KAAI8C,KAAK,WAAW,OAAO;QACzBwB,UAAU9E,MAAMS;QAChBmB,UAAU9B,QAAQuC,IAAI,CAAC/B,YAAYA,QAAQM,QAAQ;MACrD,IAAA;;;;;;AAEA,WAAKd,QAAQiF,KAAK;QAAE/E;QAAO4B,UAAU9B;MAAQ,CAAA;IAC/C;EACF;EAEQG,aAAaD,OAAcoF,WAAuE;AACxG,UAAMC,mBAAmB,KAAK7F,oBAAoByB,IAAIjB,MAAMS,GAAG,KAAK,CAAA;AACpE,WAAO4E,iBAAiBZ,OAAOW,SAAAA,EAAW/C,IAAI,CAAC/B,YAAYA,QAAQA,OAAO;EAC5E;AACF;",
6
- "names": ["Event", "create", "Filter", "Resource", "PublicKey", "log", "ComplexMap", "diff", "FunctionRegistry", "Resource", "constructor", "_client", "_functionBySpaceKey", "ComplexMap", "PublicKey", "hash", "registered", "Event", "getFunctions", "space", "get", "key", "register", "functions", "log", "length", "db", "graph", "runtimeSchemaRegistry", "hasSchema", "FunctionDef", "registerSchema", "objects", "existing", "query", "Filter", "schema", "run", "added", "diff", "a", "b", "uri", "forEach", "def", "add", "create", "_open", "info", "spacesSubscription", "spaces", "subscribe", "has", "set", "waitUntilReady", "_ctx", "disposed", "onDispose", "push", "emit", "unsubscribe", "_close", "_", "clear", "TextV0Type", "PublicKey", "log", "nonNullable", "subscriptionHandler", "handler", "types", "event", "data", "context", "response", "rest", "client", "space", "spaceKey", "spaces", "get", "from", "undefined", "error", "status", "registerTypes", "objects", "map", "id", "db", "getObjectById", "filter", "warn", "info", "key", "truncate", "length", "registry", "graph", "runtimeSchemaRegistry", "type", "hasSchema", "registerSchema", "express", "getPort", "join", "Event", "Trigger", "Context", "invariant", "log", "DevServer", "constructor", "_client", "_functionsRegistry", "_options", "_ctx", "createContext", "_handlers", "_seq", "update", "Event", "registered", "on", "added", "forEach", "def", "_load", "_safeUpdateRegistration", "log", "stats", "seq", "endpoint", "invariant", "_port", "proxy", "_proxy", "functions", "Object", "values", "start", "_server", "info", "app", "express", "use", "json", "post", "req", "res", "path", "params", "reload", "statusCode", "invoke", "body", "end", "err", "catch", "getPort", "host", "port", "portRange", "listen", "registrationId", "services", "FunctionRegistryService", "register", "_functionServiceRegistration", "open", "stop", "Error", "trigger", "Trigger", "close", "unregister", "undefined", "wake", "throw", "wait", "force", "uri", "route", "handler", "filePath", "join", "baseDir", "keys", "require", "cache", "filter", "key", "startsWith", "module", "default", "updateRegistration", "map", "id", "data", "now", "Date", "_invoke", "duration", "emit", "event", "context", "client", "dataDir", "response", "status", "code", "Context", "name", "path", "Mutex", "Context", "log", "Scheduler", "constructor", "functions", "triggers", "_options", "_ctx", "createContext", "_functionUriToCallMutex", "Map", "registered", "on", "space", "added", "_safeActivateTriggers", "getInactiveTriggers", "getFunctions", "start", "dispose", "open", "stop", "close", "register", "manifest", "mountTasks", "map", "trigger", "activate", "Promise", "all", "catch", "definition", "find", "def", "uri", "function", "info", "args", "mutex", "get", "set", "executeSynchronized", "_execFunction", "meta", "data", "spaceKey", "key", "status", "payload", "Object", "assign", "endpoint", "callback", "url", "join", "route", "triggerType", "spec", "type", "response", "fetch", "method", "headers", "body", "JSON", "stringify", "Error", "err", "error", "message", "name", "Event", "create", "Filter", "getMeta", "Context", "Resource", "compareForeignKeys", "ECHO_ATTR_META", "foreignKey", "invariant", "PublicKey", "log", "ComplexMap", "diff", "TextV0Type", "debounce", "UpdateScheduler", "Filter", "createSubscription", "getAutomergeObjectCore", "log", "createSubscriptionTrigger", "ctx", "space", "spec", "callback", "objectIds", "Set", "task", "size", "objects", "Array", "from", "clear", "maxFrequency", "subscriptions", "subscription", "added", "updated", "sizeBefore", "object", "add", "id", "info", "length", "trigger", "push", "unsubscribe", "filter", "options", "deep", "delay", "update", "content", "updates", "on", "query", "db", "typename", "type", "props", "subscribe", "onDispose", "forEach", "CronJob", "DeferredTask", "log", "createTimerTrigger", "ctx", "space", "spec", "callback", "task", "last", "run", "job", "from", "cronTime", "cron", "runOnInit", "onTick", "now", "Date", "delta", "info", "key", "truncate", "count", "schedule", "start", "onDispose", "stop", "getPort", "http", "log", "createWebhookTrigger", "ctx", "space", "spec", "callback", "server", "createServer", "req", "res", "method", "statusCode", "end", "port", "random", "listen", "info", "onDispose", "close", "WebSocket", "sleep", "Trigger", "log", "createWebsocketTrigger", "ctx", "space", "spec", "callback", "options", "retryDelay", "maxAttempts", "url", "init", "ws", "attempt", "open", "Object", "assign", "onopen", "info", "send", "TextEncoder", "encode", "JSON", "stringify", "wake", "onclose", "event", "code", "setTimeout", "onerror", "catch", "error", "onmessage", "data", "parse", "TextDecoder", "decode", "err", "isOpen", "wait", "Math", "pow", "warn", "onDispose", "close", "triggerHandlers", "subscription", "createSubscriptionTrigger", "timer", "createTimerTrigger", "webhook", "createWebhookTrigger", "websocket", "createWebsocketTrigger", "TriggerRegistry", "Resource", "constructor", "_client", "_options", "_triggersBySpaceKey", "ComplexMap", "PublicKey", "hash", "registered", "Event", "removed", "getActiveTriggers", "space", "_getTriggers", "t", "activationCtx", "getInactiveTriggers", "activate", "trigger", "callback", "log", "key", "Context", "name", "function", "_ctx", "onDispose", "dispose", "registeredTrigger", "get", "find", "reg", "id", "invariant", "options", "spec", "type", "err", "register", "manifest", "triggers", "length", "db", "graph", "runtimeSchemaRegistry", "hasSchema", "FunctionTrigger", "registerSchema", "manifestTriggers", "map", "keys", "ECHO_ATTR_META", "foreignKey", "join", "create", "objects", "existing", "query", "Filter", "schema", "run", "added", "diff", "compareForeignKeys", "forEach", "add", "info", "meta", "getMeta", "flush", "_open", "spaceListSubscription", "spaces", "subscribe", "has", "set", "waitUntilReady", "disposed", "current", "_handleRemovedTriggers", "_handleNewTriggers", "unsubscribe", "_close", "_", "clear", "filter", "candidate", "enabled", "newRegisteredTriggers", "push", "spaceKey", "emit", "i", "wasRemoved", "unregistered", "splice", "predicate", "allSpaceTriggers"]
4
+ "sourcesContent": ["//\n// Copyright 2024 DXOS.org\n//\n\nimport { Event } from '@dxos/async';\nimport { type Client } from '@dxos/client';\nimport { create, Filter, type Space } from '@dxos/client/echo';\nimport { type Context, Resource } from '@dxos/context';\nimport { PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { ComplexMap, diff } from '@dxos/util';\n\nimport { FunctionDef, type FunctionManifest } from '../types';\n\nexport type FunctionsRegisteredEvent = {\n space: Space;\n added: FunctionDef[];\n};\n\nexport class FunctionRegistry extends Resource {\n private readonly _functionBySpaceKey = new ComplexMap<PublicKey, FunctionDef[]>(PublicKey.hash);\n\n public readonly registered = new Event<FunctionsRegisteredEvent>();\n\n constructor(private readonly _client: Client) {\n super();\n }\n\n public getFunctions(space: Space): FunctionDef[] {\n return this._functionBySpaceKey.get(space.key) ?? [];\n }\n\n /**\n * Loads function definitions from the manifest into the space.\n * We first load all the definitions from the space to deduplicate by functionId.\n */\n public async register(space: Space, functions: FunctionManifest['functions']): Promise<void> {\n log('register', { space: space.key, functions: functions?.length ?? 0 });\n if (!functions?.length) {\n return;\n }\n if (!space.db.graph.runtimeSchemaRegistry.hasSchema(FunctionDef)) {\n space.db.graph.runtimeSchemaRegistry.registerSchema(FunctionDef);\n }\n\n // Sync definitions.\n const { objects: existing } = await space.db.query(Filter.schema(FunctionDef)).run();\n const { added } = diff(existing, functions, (a, b) => a.uri === b.uri);\n // TODO(burdon): Update existing templates.\n added.forEach((def) => space.db.add(create(FunctionDef, def)));\n }\n\n protected override async _open(): Promise<void> {\n log.info('opening...');\n const spacesSubscription = this._client.spaces.subscribe(async (spaces) => {\n for (const space of spaces) {\n if (this._functionBySpaceKey.has(space.key)) {\n continue;\n }\n\n const registered: FunctionDef[] = [];\n this._functionBySpaceKey.set(space.key, registered);\n await space.waitUntilReady();\n if (this._ctx.disposed) {\n break;\n }\n\n // Subscribe to updates.\n this._ctx.onDispose(\n space.db.query(Filter.schema(FunctionDef)).subscribe(({ objects }) => {\n const { added } = diff(registered, objects, (a, b) => a.uri === b.uri);\n // TODO(burdon): Update and remove.\n if (added.length > 0) {\n registered.push(...added);\n this.registered.emit({ space, added });\n }\n }),\n );\n }\n });\n\n // TODO(burdon): API: Normalize unsubscribe methods.\n this._ctx.onDispose(() => spacesSubscription.unsubscribe());\n }\n\n protected override async _close(_: Context): Promise<void> {\n log.info('closing...');\n this._functionBySpaceKey.clear();\n }\n}\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport { type Client, PublicKey } from '@dxos/client';\nimport { type Space } from '@dxos/client/echo';\nimport { type EchoReactiveObject } from '@dxos/echo-schema';\nimport { log } from '@dxos/log';\nimport { nonNullable } from '@dxos/util';\n\n// TODO(burdon): Model after http request. Ref Lambda/OpenFaaS.\n// https://docs.aws.amazon.com/lambda/latest/dg/typescript-handler.html\n// https://www.serverless.com/framework/docs/providers/aws/guide/serverless.yml/#functions\n// https://www.npmjs.com/package/aws-lambda\n\n/**\n * Function handler.\n */\nexport type FunctionHandler<TData = {}, TMeta = {}> = (params: {\n context: FunctionContext;\n event: FunctionEvent<TData, TMeta>;\n response: FunctionResponse;\n}) => Promise<FunctionResponse | void>;\n\n/**\n * Function context.\n */\nexport interface FunctionContext {\n // TODO(burdon): Limit access to individual space.\n client: Client;\n // TODO(burdon): Replace with storage service abstraction.\n dataDir?: string;\n}\n\n/**\n * Event payload.\n */\nexport type FunctionEvent<TData = {}, TMeta = {}> = {\n data: FunctionEventMeta<TMeta> & TData;\n};\n\n/**\n * Metadata from trigger.\n */\nexport type FunctionEventMeta<TMeta = {}> = {\n meta: TMeta;\n};\n\n/**\n * Function response.\n */\nexport interface FunctionResponse {\n status(code: number): FunctionResponse;\n}\n\n//\n// Subscription utils.\n//\n\nexport type RawSubscriptionData = {\n spaceKey?: string;\n objects?: string[];\n};\n\nexport type SubscriptionData = {\n space?: Space;\n objects?: EchoReactiveObject<any>[];\n};\n\n/**\n * Handler wrapper for subscription events; extracts space and objects.\n *\n * To test:\n * ```\n * curl -s -X POST -H \"Content-Type: application/json\" --data '{\"space\": \"0446...1cbb\"}' http://localhost:7100/dev/email-extractor\n * ```\n *\n * NOTE: Get space key from devtools or `dx space list --json`\n */\nexport const subscriptionHandler = <TMeta>(\n handler: FunctionHandler<SubscriptionData, TMeta>,\n): FunctionHandler<RawSubscriptionData, TMeta> => {\n return ({ event: { data }, context, ...rest }) => {\n const { client } = context;\n const space = data.spaceKey ? client.spaces.get(PublicKey.from(data.spaceKey)) : undefined;\n const objects = space\n ? data.objects?.map<EchoReactiveObject<any> | undefined>((id) => space!.db.getObjectById(id)).filter(nonNullable)\n : [];\n\n if (!!data.spaceKey && !space) {\n log.warn('invalid space', { data });\n } else {\n log.info('handler', { space: space?.key.truncate(), objects: objects?.length });\n }\n\n return handler({ event: { data: { ...data, space, objects } }, context, ...rest });\n };\n};\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport express from 'express';\nimport { getPort } from 'get-port-please';\nimport type http from 'http';\nimport { join } from 'node:path';\n\nimport { Event, Trigger } from '@dxos/async';\nimport { type Client } from '@dxos/client';\nimport { Context } from '@dxos/context';\nimport { invariant } from '@dxos/invariant';\nimport { log } from '@dxos/log';\n\nimport { type FunctionRegistry } from '../function';\nimport { type FunctionContext, type FunctionEvent, type FunctionHandler, type FunctionResponse } from '../handler';\nimport { type FunctionDef } from '../types';\n\nexport type DevServerOptions = {\n baseDir: string;\n port?: number;\n reload?: boolean;\n dataDir?: string;\n};\n\n/**\n * Functions dev server provides a local HTTP server for testing functions.\n */\nexport class DevServer {\n private _ctx = createContext();\n\n // Function handlers indexed by name (URL path).\n private readonly _handlers: Record<string, { def: FunctionDef; handler: FunctionHandler<any> }> = {};\n\n private _server?: http.Server;\n private _port?: number;\n private _functionServiceRegistration?: string;\n private _proxy?: string;\n private _seq = 0;\n\n public readonly update = new Event<number>();\n\n constructor(\n private readonly _client: Client,\n private readonly _functionsRegistry: FunctionRegistry,\n private readonly _options: DevServerOptions,\n ) {\n // TODO(burdon): Add/remove listener in start/stop.\n this._functionsRegistry.registered.on(async ({ added }) => {\n added.forEach((def) => this._load(def));\n await this._safeUpdateRegistration();\n log('new functions loaded', { added });\n });\n }\n\n get stats() {\n return {\n seq: this._seq,\n };\n }\n\n get endpoint() {\n invariant(this._port);\n return `http://localhost:${this._port}`;\n }\n\n get proxy() {\n return this._proxy;\n }\n\n get functions() {\n return Object.values(this._handlers);\n }\n\n async start() {\n invariant(!this._server);\n log.info('starting...');\n this._ctx = createContext();\n\n // TODO(burdon): Move to hono.\n const app = express();\n app.use(express.json());\n\n app.post('/:path', async (req, res) => {\n const { path } = req.params;\n try {\n log.info('calling', { path });\n if (this._options.reload) {\n const { def } = this._handlers['/' + path];\n await this._load(def, true);\n }\n\n // TODO(burdon): Get function context.\n res.statusCode = await this.invoke('/' + path, req.body);\n res.end();\n } catch (err: any) {\n log.catch(err);\n res.statusCode = 500;\n res.end();\n }\n });\n\n this._port = await getPort({ host: 'localhost', port: 7200, portRange: [7200, 7299] });\n this._server = app.listen(this._port);\n\n try {\n // Register functions.\n const { registrationId, endpoint } = await this._client.services.services.FunctionRegistryService!.register({\n endpoint: this.endpoint,\n });\n\n log.info('registered', { endpoint });\n this._proxy = endpoint;\n this._functionServiceRegistration = registrationId;\n\n // Open after registration, so that it can be updated with the list of function definitions.\n await this._functionsRegistry.open(this._ctx);\n } catch (err: any) {\n await this.stop();\n throw new Error('FunctionRegistryService not available (check plugin is configured).');\n }\n\n log.info('started', { port: this._port });\n }\n\n async stop() {\n invariant(this._server);\n log.info('stopping...');\n\n const trigger = new Trigger();\n this._server.close(async () => {\n log.info('server stopped');\n try {\n if (this._functionServiceRegistration) {\n invariant(this._client.services.services.FunctionRegistryService);\n await this._client.services.services.FunctionRegistryService.unregister({\n registrationId: this._functionServiceRegistration,\n });\n\n log.info('unregistered', { registrationId: this._functionServiceRegistration });\n this._functionServiceRegistration = undefined;\n this._proxy = undefined;\n }\n\n trigger.wake();\n } catch (err) {\n trigger.throw(err as Error);\n }\n });\n\n await trigger.wait();\n this._port = undefined;\n this._server = undefined;\n log.info('stopped');\n }\n\n /**\n * Load function.\n */\n private async _load(def: FunctionDef, force?: boolean | undefined) {\n const { uri, route, handler } = def;\n const filePath = join(this._options.baseDir, handler);\n log.info('loading', { uri, force });\n\n // Remove from cache.\n if (force) {\n Object.keys(require.cache)\n .filter((key) => key.startsWith(filePath))\n .forEach((key) => {\n delete require.cache[key];\n });\n }\n\n // TODO(burdon): Import types.\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const module = require(filePath);\n if (typeof module.default !== 'function') {\n throw new Error(`Handler must export default function: ${uri}`);\n }\n\n this._handlers[route] = { def, handler: module.default };\n }\n\n private async _safeUpdateRegistration(): Promise<void> {\n invariant(this._functionServiceRegistration);\n try {\n await this._client.services.services.FunctionRegistryService!.updateRegistration({\n registrationId: this._functionServiceRegistration,\n functions: this.functions.map(({ def: { id, route } }) => ({ id, route })),\n });\n } catch (err) {\n log.catch(err);\n }\n }\n\n /**\n * Invoke function.\n */\n public async invoke(path: string, data: any): Promise<number> {\n const seq = ++this._seq;\n const now = Date.now();\n\n log.info('req', { seq, path });\n const statusCode = await this._invoke(path, { data });\n\n log.info('res', { seq, path, statusCode, duration: Date.now() - now });\n this.update.emit(statusCode);\n return statusCode;\n }\n\n private async _invoke(path: string, event: FunctionEvent) {\n const { handler } = this._handlers[path] ?? {};\n invariant(handler, `invalid path: ${path}`);\n const context: FunctionContext = {\n client: this._client,\n dataDir: this._options.dataDir,\n };\n\n let statusCode = 200;\n const response: FunctionResponse = {\n status: (code: number) => {\n statusCode = code;\n return response;\n },\n };\n\n await handler({ context, event, response });\n return statusCode;\n }\n}\n\nconst createContext = () => new Context({ name: 'DevServer' });\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport path from 'node:path';\n\nimport { Mutex } from '@dxos/async';\nimport { type Space } from '@dxos/client/echo';\nimport { Context } from '@dxos/context';\nimport { log } from '@dxos/log';\n\nimport { type FunctionRegistry } from '../function';\nimport { type FunctionEventMeta } from '../handler';\nimport { type TriggerRegistry } from '../trigger';\nimport { type FunctionDef, type FunctionManifest, type FunctionTrigger } from '../types';\n\nexport type Callback = (data: any) => Promise<void | number>;\n\nexport type SchedulerOptions = {\n endpoint?: string;\n callback?: Callback;\n};\n\n/**\n * The scheduler triggers function execution based on various triggers.\n */\nexport class Scheduler {\n private _ctx = createContext();\n\n private readonly _functionUriToCallMutex = new Map<string, Mutex>();\n\n constructor(\n public readonly functions: FunctionRegistry,\n public readonly triggers: TriggerRegistry,\n private readonly _options: SchedulerOptions = {},\n ) {\n this.functions.registered.on(async ({ space, added }) => {\n await this._safeActivateTriggers(space, this.triggers.getInactiveTriggers(space), added);\n });\n this.triggers.registered.on(async ({ space, triggers }) => {\n await this._safeActivateTriggers(space, triggers, this.functions.getFunctions(space));\n });\n }\n\n async start() {\n await this._ctx.dispose();\n this._ctx = createContext();\n await this.functions.open(this._ctx);\n await this.triggers.open(this._ctx);\n }\n\n async stop() {\n await this._ctx.dispose();\n await this.functions.close();\n await this.triggers.close();\n }\n\n // TODO(burdon): Remove and update registries directly.\n public async register(space: Space, manifest: FunctionManifest) {\n await this.functions.register(space, manifest.functions);\n await this.triggers.register(space, manifest);\n }\n\n private async _safeActivateTriggers(\n space: Space,\n triggers: FunctionTrigger[],\n functions: FunctionDef[],\n ): Promise<void> {\n const mountTasks = triggers.map((trigger) => {\n return this.activate(space, functions, trigger);\n });\n await Promise.all(mountTasks).catch(log.catch);\n }\n\n private async activate(space: Space, functions: FunctionDef[], trigger: FunctionTrigger) {\n const definition = functions.find((def) => def.uri === trigger.function);\n if (!definition) {\n log.info('function is not found for trigger', { trigger });\n return;\n }\n\n await this.triggers.activate(space, trigger, async (args) => {\n const mutex = this._functionUriToCallMutex.get(definition.uri) ?? new Mutex();\n this._functionUriToCallMutex.set(definition.uri, mutex);\n\n log.info('function triggered, waiting for mutex', { uri: definition.uri });\n return mutex.executeSynchronized(() => {\n log.info('mutex acquired', { uri: definition.uri });\n return this._execFunction(definition, trigger, {\n meta: trigger.meta ?? {},\n data: { ...args, spaceKey: space.key },\n });\n });\n });\n\n log('activated trigger', { space: space.key, trigger });\n }\n\n private async _execFunction<TData, TMeta>(\n def: FunctionDef,\n trigger: FunctionTrigger,\n { data, meta }: { data: TData; meta?: TMeta },\n ): Promise<number> {\n let status = 0;\n try {\n // TODO(burdon): Pass in Space key (common context)?\n const payload = Object.assign({}, meta && ({ meta } satisfies FunctionEventMeta<TMeta>), data);\n\n const { endpoint, callback } = this._options;\n if (endpoint) {\n // TODO(burdon): Move out of scheduler (generalize as callback).\n const url = path.join(endpoint, def.route);\n log.info('exec', { function: def.uri, url, triggerType: trigger.spec.type });\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(payload),\n });\n\n status = response.status;\n } else if (callback) {\n log.info('exec', { function: def.uri });\n status = (await callback(payload)) ?? 200;\n }\n\n // Check errors.\n if (status && status >= 400) {\n throw new Error(`Response: ${status}`);\n }\n\n // const result = await response.json();\n log.info('done', { function: def.uri, status });\n } catch (err: any) {\n log.error('error', { function: def.uri, error: err.message });\n status = 500;\n }\n\n return status;\n }\n}\n\nconst createContext = () => new Context({ name: 'FunctionScheduler' });\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { Event } from '@dxos/async';\nimport { type Client } from '@dxos/client';\nimport { create, Filter, getMeta, type Space } from '@dxos/client/echo';\nimport { Context, Resource } from '@dxos/context';\nimport { compareForeignKeys, ECHO_ATTR_META, foreignKey } from '@dxos/echo-schema';\nimport { invariant } from '@dxos/invariant';\nimport { PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { ComplexMap, diff } from '@dxos/util';\n\nimport { createSubscriptionTrigger, createTimerTrigger, createWebhookTrigger, createWebsocketTrigger } from './type';\nimport { type FunctionManifest, FunctionTrigger, type FunctionTriggerType, type TriggerSpec } from '../types';\n\ntype ResponseCode = number;\n\nexport type TriggerCallback = (args: object) => Promise<ResponseCode>;\n\n// TODO(burdon): Make object?\nexport type TriggerFactory<Spec extends TriggerSpec, Options = any> = (\n ctx: Context,\n space: Space,\n spec: Spec,\n callback: TriggerCallback,\n options?: Options,\n) => Promise<void>;\n\nexport type TriggerHandlerMap = { [type in FunctionTriggerType]: TriggerFactory<any> };\n\nconst triggerHandlers: TriggerHandlerMap = {\n subscription: createSubscriptionTrigger,\n timer: createTimerTrigger,\n webhook: createWebhookTrigger,\n websocket: createWebsocketTrigger,\n};\n\nexport type TriggerEvent = {\n space: Space;\n triggers: FunctionTrigger[];\n};\n\ntype RegisteredTrigger = {\n activationCtx?: Context;\n trigger: FunctionTrigger;\n};\n\nexport class TriggerRegistry extends Resource {\n private readonly _triggersBySpaceKey = new ComplexMap<PublicKey, RegisteredTrigger[]>(PublicKey.hash);\n\n public readonly registered = new Event<TriggerEvent>();\n public readonly removed = new Event<TriggerEvent>();\n\n constructor(\n private readonly _client: Client,\n private readonly _options?: TriggerHandlerMap,\n ) {\n super();\n }\n\n public getActiveTriggers(space: Space): FunctionTrigger[] {\n return this._getTriggers(space, (t) => t.activationCtx != null);\n }\n\n public getInactiveTriggers(space: Space): FunctionTrigger[] {\n return this._getTriggers(space, (t) => t.activationCtx == null);\n }\n\n async activate(space: Space, trigger: FunctionTrigger, callback: TriggerCallback): Promise<void> {\n log('activate', { space: space.key, trigger });\n\n const activationCtx = new Context({ name: `FunctionTrigger-${trigger.function}` });\n this._ctx.onDispose(() => activationCtx.dispose());\n const registeredTrigger = this._triggersBySpaceKey.get(space.key)?.find((reg) => reg.trigger.id === trigger.id);\n invariant(registeredTrigger, `Trigger is not registered: ${trigger.function}`);\n registeredTrigger.activationCtx = activationCtx;\n\n try {\n const options = this._options?.[trigger.spec.type];\n await triggerHandlers[trigger.spec.type](activationCtx, space, trigger.spec, callback, options);\n } catch (err) {\n delete registeredTrigger.activationCtx;\n throw err;\n }\n }\n\n /**\n * Loads triggers from the manifest into the space.\n */\n public async register(space: Space, manifest: FunctionManifest): Promise<void> {\n log('register', { space: space.key });\n if (!manifest.triggers?.length) {\n return;\n }\n\n if (!space.db.graph.runtimeSchemaRegistry.hasSchema(FunctionTrigger)) {\n space.db.graph.runtimeSchemaRegistry.registerSchema(FunctionTrigger);\n }\n\n // Create FK to enable syncing if none are set (NOTE: Possible collision).\n const manifestTriggers = manifest.triggers.map((trigger) => {\n let keys = trigger[ECHO_ATTR_META]?.keys;\n delete trigger[ECHO_ATTR_META];\n if (!keys?.length) {\n keys = [foreignKey('manifest', [trigger.function, trigger.spec.type].join(':'))];\n }\n\n return create(FunctionTrigger, trigger, { keys });\n });\n\n // Sync triggers.\n const { objects: existing } = await space.db.query(Filter.schema(FunctionTrigger)).run();\n const { added } = diff(existing, manifestTriggers, compareForeignKeys);\n\n // TODO(burdon): Update existing.\n added.forEach((trigger) => {\n space.db.add(trigger);\n log.info('added', { meta: getMeta(trigger) });\n });\n\n if (added.length > 0) {\n await space.db.flush();\n }\n }\n\n protected override async _open(): Promise<void> {\n log.info('open...');\n const spaceListSubscription = this._client.spaces.subscribe(async (spaces) => {\n for (const space of spaces) {\n if (this._triggersBySpaceKey.has(space.key)) {\n continue;\n }\n\n const registered: RegisteredTrigger[] = [];\n this._triggersBySpaceKey.set(space.key, registered);\n await space.waitUntilReady();\n if (this._ctx.disposed) {\n break;\n }\n\n // Subscribe to updates.\n this._ctx.onDispose(\n space.db.query(Filter.schema(FunctionTrigger)).subscribe(async ({ objects: current }) => {\n log.info('update', { space: space.key, registered: registered.length, current: current.length });\n await this._handleRemovedTriggers(space, current, registered);\n this._handleNewTriggers(space, current, registered);\n }),\n );\n }\n });\n\n this._ctx.onDispose(() => spaceListSubscription.unsubscribe());\n log.info('opened');\n }\n\n protected override async _close(_: Context): Promise<void> {\n log.info('close...');\n this._triggersBySpaceKey.clear();\n log.info('closed');\n }\n\n private _handleNewTriggers(space: Space, current: FunctionTrigger[], registered: RegisteredTrigger[]) {\n const added = current.filter((candidate) => {\n return candidate.enabled && registered.find((reg) => reg.trigger.id === candidate.id) == null;\n });\n\n if (added.length > 0) {\n const newRegisteredTriggers: RegisteredTrigger[] = added.map((trigger) => ({ trigger }));\n registered.push(...newRegisteredTriggers);\n log.info('added', () => ({\n spaceKey: space.key,\n triggers: added.map((trigger) => trigger.function),\n }));\n\n this.registered.emit({ space, triggers: added });\n }\n }\n\n private async _handleRemovedTriggers(\n space: Space,\n current: FunctionTrigger[],\n registered: RegisteredTrigger[],\n ): Promise<void> {\n const removed: FunctionTrigger[] = [];\n for (let i = registered.length - 1; i >= 0; i--) {\n const wasRemoved =\n current.filter((trigger) => trigger.enabled).find((trigger) => trigger.id === registered[i].trigger.id) == null;\n if (wasRemoved) {\n const unregistered = registered.splice(i, 1)[0];\n await unregistered.activationCtx?.dispose();\n removed.push(unregistered.trigger);\n }\n }\n\n if (removed.length > 0) {\n log.info('removed', () => ({\n spaceKey: space.key,\n triggers: removed.map((trigger) => trigger.function),\n }));\n\n this.removed.emit({ space, triggers: removed });\n }\n }\n\n private _getTriggers(space: Space, predicate: (trigger: RegisteredTrigger) => boolean): FunctionTrigger[] {\n const allSpaceTriggers = this._triggersBySpaceKey.get(space.key) ?? [];\n return allSpaceTriggers.filter(predicate).map((trigger) => trigger.trigger);\n }\n}\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { TextV0Type } from '@braneframe/types';\nimport { debounce, UpdateScheduler } from '@dxos/async';\nimport { Filter, type Space } from '@dxos/client/echo';\nimport { type Context } from '@dxos/context';\nimport { createSubscription, getAutomergeObjectCore, type Query } from '@dxos/echo-db';\nimport { log } from '@dxos/log';\n\nimport type { SubscriptionTrigger } from '../../types';\nimport { type TriggerCallback, type TriggerFactory } from '../trigger-registry';\n\nexport const createSubscriptionTrigger: TriggerFactory<SubscriptionTrigger> = async (\n ctx: Context,\n space: Space,\n spec: SubscriptionTrigger,\n callback: TriggerCallback,\n) => {\n const objectIds = new Set<string>();\n const task = new UpdateScheduler(\n ctx,\n async () => {\n if (objectIds.size > 0) {\n const objects = Array.from(objectIds);\n objectIds.clear();\n await callback({ objects });\n }\n },\n { maxFrequency: 4 },\n );\n\n // TODO(burdon): Factor out diff.\n // TODO(burdon): Don't fire initially?\n // TODO(burdon): Create queue. Only allow one invocation per trigger at a time?\n const subscriptions: (() => void)[] = [];\n const subscription = createSubscription(({ added, updated }) => {\n const sizeBefore = objectIds.size;\n for (const object of added) {\n objectIds.add(object.id);\n }\n for (const object of updated) {\n objectIds.add(object.id);\n }\n if (objectIds.size > sizeBefore) {\n log.info('updated', { added: added.length, updated: updated.length });\n task.trigger();\n }\n });\n\n subscriptions.push(() => subscription.unsubscribe());\n\n // TODO(burdon): Disable trigger if keeps failing.\n const { filter, options: { deep, delay } = {} } = spec;\n const update = ({ objects }: Query) => {\n log.info('update', { objects: objects.length });\n subscription.update(objects);\n\n // TODO(burdon): Hack to monitor changes to Document's text object.\n if (deep) {\n for (const object of objects) {\n const content = object.content;\n if (content instanceof TextV0Type) {\n subscriptions.push(\n getAutomergeObjectCore(content).updates.on(debounce(() => subscription.update([object]), 1_000)),\n );\n }\n }\n }\n };\n\n // TODO(burdon): OR not working.\n // TODO(burdon): [Bug]: all callbacks are fired on the first mutation.\n // TODO(burdon): [Bug]: not updated when document is deleted (either top or hierarchically).\n log.info('subscription', { filter });\n // const query = triggerCtx.space.db.query(Filter.or(filter.map(({ type, props }) => Filter.typename(type, props))));\n if (filter) {\n const query = space.db.query(Filter.typename(filter[0].type, filter[0].props));\n subscriptions.push(query.subscribe(delay ? debounce(update, delay) : update));\n }\n\n ctx.onDispose(() => {\n subscriptions.forEach((unsubscribe) => unsubscribe());\n });\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { CronJob } from 'cron';\n\nimport { DeferredTask } from '@dxos/async';\nimport { type Space } from '@dxos/client/echo';\nimport { type Context } from '@dxos/context';\nimport { log } from '@dxos/log';\n\nimport type { TimerTrigger } from '../../types';\nimport { type TriggerCallback, type TriggerFactory } from '../trigger-registry';\n\nexport const createTimerTrigger: TriggerFactory<TimerTrigger> = async (\n ctx: Context,\n space: Space,\n spec: TimerTrigger,\n callback: TriggerCallback,\n) => {\n const task = new DeferredTask(ctx, async () => {\n await callback({});\n });\n\n let last = 0;\n let run = 0;\n // https://www.npmjs.com/package/cron#constructor\n const job = CronJob.from({\n cronTime: spec.cron,\n runOnInit: false,\n onTick: () => {\n // TODO(burdon): Check greater than 30s (use cron-parser).\n const now = Date.now();\n const delta = last ? now - last : 0;\n last = now;\n\n run++;\n log.info('tick', { space: space.key.truncate(), count: run, delta });\n task.schedule();\n },\n });\n\n job.start();\n ctx.onDispose(() => job.stop());\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { getPort } from 'get-port-please';\nimport http from 'node:http';\n\nimport { type Space } from '@dxos/client/echo';\nimport { type Context } from '@dxos/context';\nimport { log } from '@dxos/log';\n\nimport type { WebhookTrigger } from '../../types';\nimport { type TriggerCallback, type TriggerFactory } from '../trigger-registry';\n\nexport const createWebhookTrigger: TriggerFactory<WebhookTrigger> = async (\n ctx: Context,\n space: Space,\n spec: WebhookTrigger,\n callback: TriggerCallback,\n) => {\n // TODO(burdon): Enable POST hook with payload.\n const server = http.createServer(async (req, res) => {\n if (req.method !== spec.method) {\n res.statusCode = 405;\n return res.end();\n }\n res.statusCode = await callback({});\n res.end();\n });\n\n // TODO(burdon): Not used.\n // const DEF_PORT_RANGE = { min: 7500, max: 7599 };\n // const portRange = Object.assign({}, trigger.port, DEF_PORT_RANGE) as WebhookTrigger['port'];\n const port = await getPort({\n random: true,\n // portRange: [portRange!.min, portRange!.max],\n });\n\n // TODO(burdon): Update trigger object with actual port.\n server.listen(port, () => {\n log.info('started webhook', { port });\n spec.port = port;\n });\n\n ctx.onDispose(() => {\n server.close();\n });\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport WebSocket from 'ws';\n\nimport { sleep, Trigger } from '@dxos/async';\nimport { type Space } from '@dxos/client/echo';\nimport { type Context } from '@dxos/context';\nimport { log } from '@dxos/log';\n\nimport { type WebsocketTrigger } from '../../types';\nimport { type TriggerCallback, type TriggerFactory } from '../trigger-registry';\n\ninterface WebsocketTriggerOptions {\n retryDelay: number;\n maxAttempts: number;\n}\n\n/**\n * Websocket.\n * NOTE: The port must be unique, so the same hook cannot be used for multiple spaces.\n */\nexport const createWebsocketTrigger: TriggerFactory<WebsocketTrigger, WebsocketTriggerOptions> = async (\n ctx: Context,\n space: Space,\n spec: WebsocketTrigger,\n callback: TriggerCallback,\n options: WebsocketTriggerOptions = { retryDelay: 2, maxAttempts: 5 },\n) => {\n const { url, init } = spec;\n\n let ws: WebSocket;\n for (let attempt = 1; attempt <= options.maxAttempts; attempt++) {\n const open = new Trigger<boolean>();\n\n ws = new WebSocket(url);\n Object.assign(ws, {\n onopen: () => {\n log.info('opened', { url });\n if (spec.init) {\n ws.send(new TextEncoder().encode(JSON.stringify(init)));\n }\n\n open.wake(true);\n },\n\n onclose: (event) => {\n log.info('closed', { url, code: event.code });\n // Reconnect if server closes (e.g., CF restart).\n // https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent/code\n if (event.code === 1006) {\n setTimeout(async () => {\n log.info(`reconnecting in ${options.retryDelay}s...`, { url });\n await createWebsocketTrigger(ctx, space, spec, callback, options);\n }, options.retryDelay * 1_000);\n }\n\n open.wake(false);\n },\n\n onerror: (event) => {\n log.catch(event.error, { url });\n },\n\n onmessage: async (event) => {\n try {\n log.info('message');\n const data = JSON.parse(new TextDecoder().decode(event.data as Uint8Array));\n await callback({ data });\n } catch (err) {\n log.catch(err, { url });\n }\n },\n } satisfies Partial<WebSocket>);\n\n const isOpen = await open.wait();\n if (isOpen) {\n break;\n } else {\n const wait = Math.pow(attempt, 2) * options.retryDelay;\n if (attempt < options.maxAttempts) {\n log.warn(`failed to connect; trying again in ${wait}s`, { attempt });\n await sleep(wait * 1_000);\n }\n }\n }\n\n ctx.onDispose(() => {\n ws?.close();\n });\n};\n"],
5
+ "mappings": ";;;;;;;;;;AAIA,SAASA,aAAa;AAEtB,SAASC,QAAQC,cAA0B;AAC3C,SAAuBC,g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ry", "Resource", "constructor", "_client", "_functionBySpaceKey", "ComplexMap", "PublicKey", "hash", "registered", "Event", "getFunctions", "space", "get", "key", "register", "functions", "log", "length", "db", "graph", "runtimeSchemaRegistry", "hasSchema", "FunctionDef", "registerSchema", "objects", "existing", "query", "Filter", "schema", "run", "added", "diff", "a", "b", "uri", "forEach", "def", "add", "create", "_open", "info", "spacesSubscription", "spaces", "subscribe", "has", "set", "waitUntilReady", "_ctx", "disposed", "onDispose", "push", "emit", "unsubscribe", "_close", "_", "clear", "PublicKey", "log", "nonNullable", "subscriptionHandler", "handler", "event", "data", "context", "rest", "client", "space", "spaceKey", "spaces", "get", "from", "undefined", "objects", "map", "id", "db", "getObjectById", "filter", "warn", "info", "key", "truncate", "length", "express", "getPort", "join", "Event", "Trigger", "Context", "invariant", "log", "DevServer", "constructor", "_client", "_functionsRegistry", "_options", "_ctx", "createContext", "_handlers", "_seq", "update", "Event", "registered", "on", "added", "forEach", "def", "_load", "_safeUpdateRegistration", "log", "stats", "seq", "endpoint", "invariant", "_port", "proxy", "_proxy", "functions", "Object", "values", "start", "_server", "info", "app", "express", "use", "json", "post", "req", "res", "path", "params", "reload", "statusCode", "invoke", "body", "end", "err", "catch", "getPort", "host", "port", "portRange", "listen", "registrationId", "services", "FunctionRegistryService", "register", "_functionServiceRegistration", "open", "stop", "Error", "trigger", "Trigger", "close", "unregister", "undefined", "wake", "throw", "wait", "force", "uri", "route", "handler", "filePath", "join", "baseDir", "keys", "require", "cache", "filter", "key", "startsWith", "module", "default", "updateRegistration", "map", "id", "data", "now", "Date", "_invoke", "duration", "emit", "event", "context", "client", "dataDir", "response", "status", "code", "Context", "name", "path", "Mutex", "Context", "log", "Scheduler", "constructor", "functions", "triggers", "_options", "_ctx", "createContext", "_functionUriToCallMutex", "Map", "registered", "on", "space", "added", "_safeActivateTriggers", "getInactiveTriggers", "getFunctions", "start", "dispose", "open", "stop", "close", "register", "manifest", "mountTasks", "map", "trigger", "activate", "Promise", "all", "catch", "definition", "find", "def", "uri", "function", "info", "args", "mutex", "get", "set", "executeSynchronized", "_execFunction", "meta", "data", "spaceKey", "key", "status", "payload", "Object", "assign", "endpoint", "callback", "url", "join", "route", "triggerType", "spec", "type", "response", "fetch", "method", "headers", "body", "JSON", "stringify", "Error", "err", "error", "message", "name", "Event", "create", "Filter", "getMeta", "Context", "Resource", "compareForeignKeys", "ECHO_ATTR_META", "foreignKey", "invariant", "PublicKey", "log", "ComplexMap", "diff", "TextV0Type", "debounce", "UpdateScheduler", "Filter", "createSubscription", "getAutomergeObjectCore", "log", "createSubscriptionTrigger", "ctx", "space", "spec", "callback", "objectIds", "Set", "task", "size", "objects", "Array", "from", "clear", "maxFrequency", "subscriptions", "subscription", "added", "updated", "sizeBefore", "object", "add", "id", "info", "length", "trigger", "push", "unsubscribe", "filter", "options", "deep", "delay", "update", "content", "updates", "on", "query", "db", "typename", "type", "props", "subscribe", "onDispose", "forEach", "CronJob", "DeferredTask", "log", "createTimerTrigger", "ctx", "space", "spec", "callback", "task", "last", "run", "job", "from", "cronTime", "cron", "runOnInit", "onTick", "now", "Date", "delta", "info", "key", "truncate", "count", "schedule", "start", "onDispose", "stop", "getPort", "http", "log", "createWebhookTrigger", "ctx", "space", "spec", "callback", "server", "createServer", "req", "res", "method", "statusCode", "end", "port", "random", "listen", "info", "onDispose", "close", "WebSocket", "sleep", "Trigger", "log", "createWebsocketTrigger", "ctx", "space", "spec", "callback", "options", "retryDelay", "maxAttempts", "url", "init", "ws", "attempt", "open", "Object", "assign", "onopen", "info", "send", "TextEncoder", "encode", "JSON", "stringify", "wake", "onclose", "event", "code", "setTimeout", "onerror", "catch", "error", "onmessage", "data", "parse", "TextDecoder", "decode", "err", "isOpen", "wait", "Math", "pow", "warn", "onDispose", "close", "triggerHandlers", "subscription", "createSubscriptionTrigger", "timer", "createTimerTrigger", "webhook", "createWebhookTrigger", "websocket", "createWebsocketTrigger", "TriggerRegistry", "Resource", "constructor", "_client", "_options", "_triggersBySpaceKey", "ComplexMap", "PublicKey", "hash", "registered", "Event", "removed", "getActiveTriggers", "space", "_getTriggers", "t", "activationCtx", "getInactiveTriggers", "activate", "trigger", "callback", "log", "key", "Context", "name", "function", "_ctx", "onDispose", "dispose", "registeredTrigger", "get", "find", "reg", "id", "invariant", "options", "spec", "type", "err", "register", "manifest", "triggers", "length", "db", "graph", "runtimeSchemaRegistry", "hasSchema", "FunctionTrigger", "registerSchema", "manifestTriggers", "map", "keys", "ECHO_ATTR_META", "foreignKey", "join", "create", "objects", "existing", "query", "Filter", "schema", "run", "added", "diff", "compareForeignKeys", "forEach", "add", "info", "meta", "getMeta", "flush", "_open", "spaceListSubscription", "spaces", "subscribe", "has", "set", "waitUntilReady", "disposed", "current", "_handleRemovedTriggers", "_handleNewTriggers", "unsubscribe", "_close", "_", "clear", "filter", "candidate", "enabled", "newRegisteredTriggers", "push", "spaceKey", "emit", "i", "wasRemoved", "unregistered", "splice", "predicate", "allSpaceTriggers"]
7
7
  }
@@ -1 +1 @@
1
- {"inputs":{"inject-globals:@inject-globals":{"bytes":384,"imports":[{"path":"@dxos/node-std/inject-globals","kind":"import-statement","external":true}],"format":"esm"},"packages/core/functions/src/types.ts":{"bytes":9711,"imports":[{"path":"@dxos/echo-schema","kind":"import-statement","external":true},{"path":"@inject-globals","kind":"import-statement","external":true}],"format":"esm"},"packages/core/functions/src/function/function-registry.ts":{"bytes":11375,"imports":[{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/client/echo","kind":"import-statement","external":true},{"path":"@dxos/context","kind":"import-statement","external":true},{"path":"@dxos/keys","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"packages/core/functions/src/types.ts","kind":"import-statement","original":"../types"},{"path":"@inject-globals","kind":"import-statement","external":true}],"format":"esm"},"packages/core/functions/src/function/index.ts":{"bytes":529,"imports":[{"path":"packages/core/functions/src/function/function-registry.ts","kind":"import-statement","original":"./function-registry"},{"path":"@inject-globals","kind":"import-statement","external":true}],"format":"esm"},"packages/core/functions/src/handler.ts":{"bytes":9375,"imports":[{"path":"@braneframe/types","kind":"import-statement","external":true},{"path":"@dxos/client","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"@inject-globals","kind":"import-statement","external":true}],"format":"esm"},"packages/core/functions/src/runtime/dev-server.ts":{"bytes":27983,"imports":[{"path":"express","kind":"import-statement","external":true},{"path":"get-port-please","kind":"import-statement","external":true},{"path":"@dxos/node-std/path","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/context","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@inject-globals","kind":"import-statement","external":true},{"path":"<runtime>","kind":"import-statement","external":true}],"format":"esm"},"packages/core/functions/src/runtime/scheduler.ts":{"bytes":18003,"imports":[{"path":"@dxos/node-std/path","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/context","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@inject-globals","kind":"import-statement","external":true}],"format":"esm"},"packages/core/functions/src/runtime/index.ts":{"bytes":598,"imports":[{"path":"packages/core/functions/src/runtime/dev-server.ts","kind":"import-statement","original":"./dev-server"},{"path":"packages/core/functions/src/runtime/scheduler.ts","kind":"import-statement","original":"./scheduler"},{"path":"@inject-globals","kind":"import-statement","external":true}],"format":"esm"},"packages/core/functions/src/trigger/type/subscription-trigger.ts":{"bytes":10741,"imports":[{"path":"@braneframe/types","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/client/echo","kind":"import-statement","external":true},{"path":"@dxos/echo-db","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@inject-globals","kind":"import-statement","external":true}],"format":"esm"},"packages/core/functions/src/trigger/type/timer-trigger.ts":{"bytes":4173,"imports":[{"path":"cron","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@inject-globals","kind":"import-statement","external":true}],"format":"esm"},"packages/core/functions/src/trigger/type/webhook-trigger.ts":{"bytes":4388,"imports":[{"path":"get-port-please","kind":"import-statement","external":true},{"path":"@dxos/node-std/http","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@inject-globals","kind":"import-statement","external":true}],"format":"esm"},"packages/core/functions/src/trigger/type/websocket-trigger.ts":{"bytes":10551,"imports":[{"path":"ws","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@inject-globals","kind":"import-statement","external":true}],"format":"esm"},"packages/core/functions/src/trigger/type/index.ts":{"bytes":865,"imports":[{"path":"packages/core/functions/src/trigger/type/subscription-trigger.ts","kind":"import-statement","original":"./subscription-trigger"},{"path":"packages/core/functions/src/trigger/type/timer-trigger.ts","kind":"import-statement","original":"./timer-trigger"},{"path":"packages/core/functions/src/trigger/type/webhook-trigger.ts","kind":"import-statement","original":"./webhook-trigger"},{"path":"packages/core/functions/src/trigger/type/websocket-trigger.ts","kind":"import-statement","original":"./websocket-trigger"},{"path":"@inject-globals","kind":"import-statement","external":true}],"format":"esm"},"packages/core/functions/src/trigger/trigger-registry.ts":{"bytes":27381,"imports":[{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/client/echo","kind":"import-statement","external":true},{"path":"@dxos/context","kind":"import-statement","external":true},{"path":"@dxos/echo-schema","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/keys","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"packages/core/functions/src/trigger/type/index.ts","kind":"import-statement","original":"./type"},{"path":"packages/core/functions/src/types.ts","kind":"import-statement","original":"../types"},{"path":"@inject-globals","kind":"import-statement","external":true}],"format":"esm"},"packages/core/functions/src/trigger/index.ts":{"bytes":523,"imports":[{"path":"packages/core/functions/src/trigger/trigger-registry.ts","kind":"import-statement","original":"./trigger-registry"},{"path":"@inject-globals","kind":"import-statement","external":true}],"format":"esm"},"packages/core/functions/src/index.ts":{"bytes":837,"imports":[{"path":"packages/core/functions/src/function/index.ts","kind":"import-statement","original":"./function"},{"path":"packages/core/functions/src/handler.ts","kind":"import-statement","original":"./handler"},{"path":"packages/core/functions/src/runtime/index.ts","kind":"import-statement","original":"./runtime"},{"path":"packages/core/functions/src/trigger/index.ts","kind":"import-statement","original":"./trigger"},{"path":"packages/core/functions/src/types.ts","kind":"import-statement","original":"./types"},{"path":"@inject-globals","kind":"import-statement","external":true}],"format":"esm"}},"outputs":{"packages/core/functions/dist/lib/browser/index.mjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":58380},"packages/core/functions/dist/lib/browser/index.mjs":{"imports":[{"path":"packages/core/functions/dist/lib/browser/chunk-4D4I3YMJ.mjs","kind":"import-statement"},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/client/echo","kind":"import-statement","external":true},{"path":"@dxos/context","kind":"import-statement","external":true},{"path":"@dxos/keys","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"@braneframe/types","kind":"import-statement","external":true},{"path":"@dxos/client","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"express","kind":"import-statement","external":true},{"path":"get-port-please","kind":"import-statement","external":true},{"path":"@dxos/node-std/path","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/context","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/node-std/path","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/context","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/client/echo","kind":"import-statement","external":true},{"path":"@dxos/context","kind":"import-statement","external":true},{"path":"@dxos/echo-schema","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/keys","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"@braneframe/types","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/client/echo","kind":"import-statement","external":true},{"path":"@dxos/echo-db","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"cron","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"get-port-please","kind":"import-statement","external":true},{"path":"@dxos/node-std/http","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"ws","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true}],"exports":["DevServer","FUNCTION_SCHEMA","FunctionDef","FunctionManifestSchema","FunctionRegistry","FunctionTrigger","Scheduler","TriggerRegistry","subscriptionHandler"],"entryPoint":"packages/core/functions/src/index.ts","inputs":{"packages/core/functions/src/function/function-registry.ts":{"bytesInOutput":2655},"packages/core/functions/src/function/index.ts":{"bytesInOutput":0},"packages/core/functions/src/index.ts":{"bytesInOutput":0},"packages/core/functions/src/handler.ts":{"bytesInOutput":1724},"packages/core/functions/src/runtime/dev-server.ts":{"bytesInOutput":7772},"packages/core/functions/src/runtime/index.ts":{"bytesInOutput":0},"packages/core/functions/src/runtime/scheduler.ts":{"bytesInOutput":4612},"packages/core/functions/src/trigger/trigger-registry.ts":{"bytesInOutput":6996},"packages/core/functions/src/trigger/type/subscription-trigger.ts":{"bytesInOutput":2387},"packages/core/functions/src/trigger/type/index.ts":{"bytesInOutput":0},"packages/core/functions/src/trigger/type/timer-trigger.ts":{"bytesInOutput":898},"packages/core/functions/src/trigger/type/webhook-trigger.ts":{"bytesInOutput":839},"packages/core/functions/src/trigger/type/websocket-trigger.ts":{"bytesInOutput":2837},"packages/core/functions/src/trigger/index.ts":{"bytesInOutput":0}},"bytes":31690},"packages/core/functions/dist/lib/browser/types.mjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":93},"packages/core/functions/dist/lib/browser/types.mjs":{"imports":[{"path":"packages/core/functions/dist/lib/browser/chunk-4D4I3YMJ.mjs","kind":"import-statement"}],"exports":["FUNCTION_SCHEMA","FunctionDef","FunctionManifestSchema","FunctionTrigger"],"entryPoint":"packages/core/functions/src/types.ts","inputs":{},"bytes":276},"packages/core/functions/dist/lib/browser/chunk-4D4I3YMJ.mjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":5396},"packages/core/functions/dist/lib/browser/chunk-4D4I3YMJ.mjs":{"imports":[{"path":"@dxos/node-std/inject-globals","kind":"import-statement","external":true},{"path":"@dxos/echo-schema","kind":"import-statement","external":true}],"exports":["FUNCTION_SCHEMA","FunctionDef","FunctionManifestSchema","FunctionTrigger","__require"],"inputs":{"inject-globals:@inject-globals":{"bytesInOutput":90},"packages/core/functions/src/types.ts":{"bytesInOutput":1848}},"bytes":2564}}}
1
+ {"inputs":{"inject-globals:@inject-globals":{"bytes":384,"imports":[{"path":"@dxos/node-std/inject-globals","kind":"import-statement","external":true}],"format":"esm"},"packages/core/functions/src/types.ts":{"bytes":9711,"imports":[{"path":"@dxos/echo-schema","kind":"import-statement","external":true},{"path":"@inject-globals","kind":"import-statement","external":true}],"format":"esm"},"packages/core/functions/src/function/function-registry.ts":{"bytes":11375,"imports":[{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/client/echo","kind":"import-statement","external":true},{"path":"@dxos/context","kind":"import-statement","external":true},{"path":"@dxos/keys","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"packages/core/functions/src/types.ts","kind":"import-statement","original":"../types"},{"path":"@inject-globals","kind":"import-statement","external":true}],"format":"esm"},"packages/core/functions/src/function/index.ts":{"bytes":529,"imports":[{"path":"packages/core/functions/src/function/function-registry.ts","kind":"import-statement","original":"./function-registry"},{"path":"@inject-globals","kind":"import-statement","external":true}],"format":"esm"},"packages/core/functions/src/handler.ts":{"bytes":6970,"imports":[{"path":"@dxos/client","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"@inject-globals","kind":"import-statement","external":true}],"format":"esm"},"packages/core/functions/src/runtime/dev-server.ts":{"bytes":27983,"imports":[{"path":"express","kind":"import-statement","external":true},{"path":"get-port-please","kind":"import-statement","external":true},{"path":"@dxos/node-std/path","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/context","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@inject-globals","kind":"import-statement","external":true},{"path":"<runtime>","kind":"import-statement","external":true}],"format":"esm"},"packages/core/functions/src/runtime/scheduler.ts":{"bytes":18003,"imports":[{"path":"@dxos/node-std/path","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/context","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@inject-globals","kind":"import-statement","external":true}],"format":"esm"},"packages/core/functions/src/runtime/index.ts":{"bytes":598,"imports":[{"path":"packages/core/functions/src/runtime/dev-server.ts","kind":"import-statement","original":"./dev-server"},{"path":"packages/core/functions/src/runtime/scheduler.ts","kind":"import-statement","original":"./scheduler"},{"path":"@inject-globals","kind":"import-statement","external":true}],"format":"esm"},"packages/core/functions/src/trigger/type/subscription-trigger.ts":{"bytes":10741,"imports":[{"path":"@braneframe/types","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/client/echo","kind":"import-statement","external":true},{"path":"@dxos/echo-db","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@inject-globals","kind":"import-statement","external":true}],"format":"esm"},"packages/core/functions/src/trigger/type/timer-trigger.ts":{"bytes":4173,"imports":[{"path":"cron","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@inject-globals","kind":"import-statement","external":true}],"format":"esm"},"packages/core/functions/src/trigger/type/webhook-trigger.ts":{"bytes":4388,"imports":[{"path":"get-port-please","kind":"import-statement","external":true},{"path":"@dxos/node-std/http","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@inject-globals","kind":"import-statement","external":true}],"format":"esm"},"packages/core/functions/src/trigger/type/websocket-trigger.ts":{"bytes":10551,"imports":[{"path":"ws","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@inject-globals","kind":"import-statement","external":true}],"format":"esm"},"packages/core/functions/src/trigger/type/index.ts":{"bytes":865,"imports":[{"path":"packages/core/functions/src/trigger/type/subscription-trigger.ts","kind":"import-statement","original":"./subscription-trigger"},{"path":"packages/core/functions/src/trigger/type/timer-trigger.ts","kind":"import-statement","original":"./timer-trigger"},{"path":"packages/core/functions/src/trigger/type/webhook-trigger.ts","kind":"import-statement","original":"./webhook-trigger"},{"path":"packages/core/functions/src/trigger/type/websocket-trigger.ts","kind":"import-statement","original":"./websocket-trigger"},{"path":"@inject-globals","kind":"import-statement","external":true}],"format":"esm"},"packages/core/functions/src/trigger/trigger-registry.ts":{"bytes":27381,"imports":[{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/client/echo","kind":"import-statement","external":true},{"path":"@dxos/context","kind":"import-statement","external":true},{"path":"@dxos/echo-schema","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/keys","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"packages/core/functions/src/trigger/type/index.ts","kind":"import-statement","original":"./type"},{"path":"packages/core/functions/src/types.ts","kind":"import-statement","original":"../types"},{"path":"@inject-globals","kind":"import-statement","external":true}],"format":"esm"},"packages/core/functions/src/trigger/index.ts":{"bytes":523,"imports":[{"path":"packages/core/functions/src/trigger/trigger-registry.ts","kind":"import-statement","original":"./trigger-registry"},{"path":"@inject-globals","kind":"import-statement","external":true}],"format":"esm"},"packages/core/functions/src/index.ts":{"bytes":837,"imports":[{"path":"packages/core/functions/src/function/index.ts","kind":"import-statement","original":"./function"},{"path":"packages/core/functions/src/handler.ts","kind":"import-statement","original":"./handler"},{"path":"packages/core/functions/src/runtime/index.ts","kind":"import-statement","original":"./runtime"},{"path":"packages/core/functions/src/trigger/index.ts","kind":"import-statement","original":"./trigger"},{"path":"packages/core/functions/src/types.ts","kind":"import-statement","original":"./types"},{"path":"@inject-globals","kind":"import-statement","external":true}],"format":"esm"}},"outputs":{"packages/core/functions/dist/lib/browser/index.mjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":57217},"packages/core/functions/dist/lib/browser/index.mjs":{"imports":[{"path":"packages/core/functions/dist/lib/browser/chunk-4D4I3YMJ.mjs","kind":"import-statement"},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/client/echo","kind":"import-statement","external":true},{"path":"@dxos/context","kind":"import-statement","external":true},{"path":"@dxos/keys","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"@dxos/client","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"express","kind":"import-statement","external":true},{"path":"get-port-please","kind":"import-statement","external":true},{"path":"@dxos/node-std/path","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/context","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/node-std/path","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/context","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/client/echo","kind":"import-statement","external":true},{"path":"@dxos/context","kind":"import-statement","external":true},{"path":"@dxos/echo-schema","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/keys","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"@braneframe/types","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/client/echo","kind":"import-statement","external":true},{"path":"@dxos/echo-db","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"cron","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"get-port-please","kind":"import-statement","external":true},{"path":"@dxos/node-std/http","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"ws","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true}],"exports":["DevServer","FUNCTION_SCHEMA","FunctionDef","FunctionManifestSchema","FunctionRegistry","FunctionTrigger","Scheduler","TriggerRegistry","subscriptionHandler"],"entryPoint":"packages/core/functions/src/index.ts","inputs":{"packages/core/functions/src/function/function-registry.ts":{"bytesInOutput":2655},"packages/core/functions/src/function/index.ts":{"bytesInOutput":0},"packages/core/functions/src/index.ts":{"bytesInOutput":0},"packages/core/functions/src/handler.ts":{"bytesInOutput":1152},"packages/core/functions/src/runtime/dev-server.ts":{"bytesInOutput":7772},"packages/core/functions/src/runtime/index.ts":{"bytesInOutput":0},"packages/core/functions/src/runtime/scheduler.ts":{"bytesInOutput":4612},"packages/core/functions/src/trigger/trigger-registry.ts":{"bytesInOutput":6996},"packages/core/functions/src/trigger/type/subscription-trigger.ts":{"bytesInOutput":2371},"packages/core/functions/src/trigger/type/index.ts":{"bytesInOutput":0},"packages/core/functions/src/trigger/type/timer-trigger.ts":{"bytesInOutput":898},"packages/core/functions/src/trigger/type/webhook-trigger.ts":{"bytesInOutput":839},"packages/core/functions/src/trigger/type/websocket-trigger.ts":{"bytesInOutput":2837},"packages/core/functions/src/trigger/index.ts":{"bytesInOutput":0}},"bytes":31102},"packages/core/functions/dist/lib/browser/types.mjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":93},"packages/core/functions/dist/lib/browser/types.mjs":{"imports":[{"path":"packages/core/functions/dist/lib/browser/chunk-4D4I3YMJ.mjs","kind":"import-statement"}],"exports":["FUNCTION_SCHEMA","FunctionDef","FunctionManifestSchema","FunctionTrigger"],"entryPoint":"packages/core/functions/src/types.ts","inputs":{},"bytes":276},"packages/core/functions/dist/lib/browser/chunk-4D4I3YMJ.mjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":5396},"packages/core/functions/dist/lib/browser/chunk-4D4I3YMJ.mjs":{"imports":[{"path":"@dxos/node-std/inject-globals","kind":"import-statement","external":true},{"path":"@dxos/echo-schema","kind":"import-statement","external":true}],"exports":["FUNCTION_SCHEMA","FunctionDef","FunctionManifestSchema","FunctionTrigger","__require"],"inputs":{"inject-globals:@inject-globals":{"bytesInOutput":90},"packages/core/functions/src/types.ts":{"bytesInOutput":1848}},"bytes":2564}}}
@@ -46,7 +46,6 @@ var import_context = require("@dxos/context");
46
46
  var import_keys = require("@dxos/keys");
47
47
  var import_log = require("@dxos/log");
48
48
  var import_util = require("@dxos/util");
49
- var import_types = require("@braneframe/types");
50
49
  var import_client = require("@dxos/client");
51
50
  var import_log2 = require("@dxos/log");
52
51
  var import_util2 = require("@dxos/util");
@@ -69,7 +68,7 @@ var import_invariant2 = require("@dxos/invariant");
69
68
  var import_keys2 = require("@dxos/keys");
70
69
  var import_log5 = require("@dxos/log");
71
70
  var import_util3 = require("@dxos/util");
72
- var import_types2 = require("@braneframe/types");
71
+ var import_types = require("@braneframe/types");
73
72
  var import_async5 = require("@dxos/async");
74
73
  var import_echo3 = require("@dxos/client/echo");
75
74
  var import_echo_db = require("@dxos/echo-db");
@@ -161,27 +160,17 @@ var FunctionRegistry = class extends import_context.Resource {
161
160
  }
162
161
  };
163
162
  var __dxlog_file2 = "/home/runner/work/dxos/dxos/packages/core/functions/src/handler.ts";
164
- var subscriptionHandler = (handler, types) => {
165
- return async ({ event: { data }, context, response, ...rest }) => {
163
+ var subscriptionHandler = (handler) => {
164
+ return ({ event: { data }, context, ...rest }) => {
166
165
  const { client } = context;
167
166
  const space = data.spaceKey ? client.spaces.get(import_client.PublicKey.from(data.spaceKey)) : void 0;
168
- if (!space) {
169
- import_log2.log.error("Invalid space", void 0, {
170
- F: __dxlog_file2,
171
- L: 90,
172
- S: void 0,
173
- C: (f, a) => f(...a)
174
- });
175
- return response.status(500);
176
- }
177
- registerTypes(space, types);
178
167
  const objects = space ? data.objects?.map((id) => space.db.getObjectById(id)).filter(import_util2.nonNullable) : [];
179
168
  if (!!data.spaceKey && !space) {
180
169
  import_log2.log.warn("invalid space", {
181
170
  data
182
171
  }, {
183
172
  F: __dxlog_file2,
184
- L: 100,
173
+ L: 91,
185
174
  S: void 0,
186
175
  C: (f, a) => f(...a)
187
176
  });
@@ -191,7 +180,7 @@ var subscriptionHandler = (handler, types) => {
191
180
  objects: objects?.length
192
181
  }, {
193
182
  F: __dxlog_file2,
194
- L: 102,
183
+ L: 93,
195
184
  S: void 0,
196
185
  C: (f, a) => f(...a)
197
186
  });
@@ -205,22 +194,10 @@ var subscriptionHandler = (handler, types) => {
205
194
  }
206
195
  },
207
196
  context,
208
- response,
209
197
  ...rest
210
198
  });
211
199
  };
212
200
  };
213
- var registerTypes = (space, types = []) => {
214
- const registry = space.db.graph.runtimeSchemaRegistry;
215
- for (const type of [
216
- ...types,
217
- import_types.TextV0Type
218
- ]) {
219
- if (!registry.hasSchema(type)) {
220
- registry.registerSchema(type);
221
- }
222
- }
223
- };
224
201
  var __dxlog_file3 = "/home/runner/work/dxos/dxos/packages/core/functions/src/runtime/dev-server.ts";
225
202
  var DevServer = class {
226
203
  constructor(_client, _functionsRegistry, _options) {
@@ -744,7 +721,7 @@ var createSubscriptionTrigger = async (ctx, space, spec, callback) => {
744
721
  if (deep) {
745
722
  for (const object of objects) {
746
723
  const content = object.content;
747
- if (content instanceof import_types2.TextV0Type) {
724
+ if (content instanceof import_types.TextV0Type) {
748
725
  subscriptions.push((0, import_echo_db.getAutomergeObjectCore)(content).updates.on((0, import_async5.debounce)(() => subscription.update([
749
726
  object
750
727
  ]), 1e3)));
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/function/function-registry.ts", "../../../src/handler.ts", "../../../src/runtime/dev-server.ts", "../../../src/runtime/scheduler.ts", "../../../src/trigger/trigger-registry.ts", "../../../src/trigger/type/subscription-trigger.ts", "../../../src/trigger/type/timer-trigger.ts", "../../../src/trigger/type/webhook-trigger.ts", "../../../src/trigger/type/websocket-trigger.ts"],
4
- "sourcesContent": ["//\n// Copyright 2024 DXOS.org\n//\n\nimport { Event } from '@dxos/async';\nimport { type Client } from '@dxos/client';\nimport { create, Filter, type Space } from '@dxos/client/echo';\nimport { type Context, Resource } from '@dxos/context';\nimport { PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { ComplexMap, diff } from '@dxos/util';\n\nimport { FunctionDef, type FunctionManifest } from '../types';\n\nexport type FunctionsRegisteredEvent = {\n space: Space;\n added: FunctionDef[];\n};\n\nexport class FunctionRegistry extends Resource {\n private readonly _functionBySpaceKey = new ComplexMap<PublicKey, FunctionDef[]>(PublicKey.hash);\n\n public readonly registered = new Event<FunctionsRegisteredEvent>();\n\n constructor(private readonly _client: Client) {\n super();\n }\n\n public getFunctions(space: Space): FunctionDef[] {\n return this._functionBySpaceKey.get(space.key) ?? [];\n }\n\n /**\n * Loads function definitions from the manifest into the space.\n * We first load all the definitions from the space to deduplicate by functionId.\n */\n public async register(space: Space, functions: FunctionManifest['functions']): Promise<void> {\n log('register', { space: space.key, functions: functions?.length ?? 0 });\n if (!functions?.length) {\n return;\n }\n if (!space.db.graph.runtimeSchemaRegistry.hasSchema(FunctionDef)) {\n space.db.graph.runtimeSchemaRegistry.registerSchema(FunctionDef);\n }\n\n // Sync definitions.\n const { objects: existing } = await space.db.query(Filter.schema(FunctionDef)).run();\n const { added } = diff(existing, functions, (a, b) => a.uri === b.uri);\n // TODO(burdon): Update existing templates.\n added.forEach((def) => space.db.add(create(FunctionDef, def)));\n }\n\n protected override async _open(): Promise<void> {\n log.info('opening...');\n const spacesSubscription = this._client.spaces.subscribe(async (spaces) => {\n for (const space of spaces) {\n if (this._functionBySpaceKey.has(space.key)) {\n continue;\n }\n\n const registered: FunctionDef[] = [];\n this._functionBySpaceKey.set(space.key, registered);\n await space.waitUntilReady();\n if (this._ctx.disposed) {\n break;\n }\n\n // Subscribe to updates.\n this._ctx.onDispose(\n space.db.query(Filter.schema(FunctionDef)).subscribe(({ objects }) => {\n const { added } = diff(registered, objects, (a, b) => a.uri === b.uri);\n // TODO(burdon): Update and remove.\n if (added.length > 0) {\n registered.push(...added);\n this.registered.emit({ space, added });\n }\n }),\n );\n }\n });\n\n // TODO(burdon): API: Normalize unsubscribe methods.\n this._ctx.onDispose(() => spacesSubscription.unsubscribe());\n }\n\n protected override async _close(_: Context): Promise<void> {\n log.info('closing...');\n this._functionBySpaceKey.clear();\n }\n}\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport { TextV0Type } from '@braneframe/types';\nimport { type Client, PublicKey } from '@dxos/client';\nimport { type Space } from '@dxos/client/echo';\nimport { type EchoReactiveObject, type S } from '@dxos/echo-schema';\nimport { log } from '@dxos/log';\nimport { nonNullable } from '@dxos/util';\n\n// TODO(burdon): Model after http request. Ref Lambda/OpenFaaS.\n// https://docs.aws.amazon.com/lambda/latest/dg/typescript-handler.html\n// https://www.serverless.com/framework/docs/providers/aws/guide/serverless.yml/#functions\n// https://www.npmjs.com/package/aws-lambda\n\n/**\n * Function handler.\n */\nexport type FunctionHandler<TData = {}, TMeta = {}> = (params: {\n context: FunctionContext;\n event: FunctionEvent<TData, TMeta>;\n response: FunctionResponse;\n}) => Promise<FunctionResponse | void>;\n\n/**\n * Function context.\n */\nexport interface FunctionContext {\n // TODO(burdon): Limit access to individual space.\n client: Client;\n // TODO(burdon): Replace with storage service abstraction.\n dataDir?: string;\n}\n\n/**\n * Event payload.\n */\nexport type FunctionEvent<TData = {}, TMeta = {}> = {\n data: FunctionEventMeta<TMeta> & TData;\n};\n\n/**\n * Metadata from trigger.\n */\nexport type FunctionEventMeta<TMeta = {}> = {\n meta: TMeta;\n};\n\n/**\n * Function response.\n */\nexport interface FunctionResponse {\n status(code: number): FunctionResponse;\n}\n\n//\n// Subscription utils.\n//\n\nexport type RawSubscriptionData = {\n spaceKey?: string;\n objects?: string[];\n};\n\nexport type SubscriptionData = {\n space?: Space;\n objects?: EchoReactiveObject<any>[];\n};\n\n/**\n * Handler wrapper for subscription events; extracts space and objects.\n *\n * To test:\n * ```\n * curl -s -X POST -H \"Content-Type: application/json\" --data '{\"space\": \"0446...1cbb\"}' http://localhost:7100/dev/email-extractor\n * ```\n *\n * NOTE: Get space key from devtools or `dx space list --json`\n */\n// TODO(burdon): Evolve into plugin definition like Composer.\nexport const subscriptionHandler = <TMeta>(\n handler: FunctionHandler<SubscriptionData, TMeta>,\n types?: S.Schema<any>[],\n): FunctionHandler<RawSubscriptionData, TMeta> => {\n return async ({ event: { data }, context, response, ...rest }) => {\n const { client } = context;\n const space = data.spaceKey ? client.spaces.get(PublicKey.from(data.spaceKey)) : undefined;\n if (!space) {\n log.error('Invalid space');\n return response.status(500);\n }\n\n registerTypes(space, types);\n const objects = space\n ? data.objects?.map<EchoReactiveObject<any> | undefined>((id) => space!.db.getObjectById(id)).filter(nonNullable)\n : [];\n\n if (!!data.spaceKey && !space) {\n log.warn('invalid space', { data });\n } else {\n log.info('handler', { space: space?.key.truncate(), objects: objects?.length });\n }\n\n return handler({ event: { data: { ...data, space, objects } }, context, response, ...rest });\n };\n};\n\n// TODO(burdon): Evolve types as part of function metadata.\nconst registerTypes = (space: Space, types: S.Schema<any>[] = []) => {\n const registry = space.db.graph.runtimeSchemaRegistry;\n for (const type of [...types, TextV0Type]) {\n if (!registry.hasSchema(type)) {\n registry.registerSchema(type);\n }\n }\n};\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport express from 'express';\nimport { getPort } from 'get-port-please';\nimport type http from 'http';\nimport { join } from 'node:path';\n\nimport { Event, Trigger } from '@dxos/async';\nimport { type Client } from '@dxos/client';\nimport { Context } from '@dxos/context';\nimport { invariant } from '@dxos/invariant';\nimport { log } from '@dxos/log';\n\nimport { type FunctionRegistry } from '../function';\nimport { type FunctionContext, type FunctionEvent, type FunctionHandler, type FunctionResponse } from '../handler';\nimport { type FunctionDef } from '../types';\n\nexport type DevServerOptions = {\n baseDir: string;\n port?: number;\n reload?: boolean;\n dataDir?: string;\n};\n\n/**\n * Functions dev server provides a local HTTP server for testing functions.\n */\nexport class DevServer {\n private _ctx = createContext();\n\n // Function handlers indexed by name (URL path).\n private readonly _handlers: Record<string, { def: FunctionDef; handler: FunctionHandler<any> }> = {};\n\n private _server?: http.Server;\n private _port?: number;\n private _functionServiceRegistration?: string;\n private _proxy?: string;\n private _seq = 0;\n\n public readonly update = new Event<number>();\n\n constructor(\n private readonly _client: Client,\n private readonly _functionsRegistry: FunctionRegistry,\n private readonly _options: DevServerOptions,\n ) {\n // TODO(burdon): Add/remove listener in start/stop.\n this._functionsRegistry.registered.on(async ({ added }) => {\n added.forEach((def) => this._load(def));\n await this._safeUpdateRegistration();\n log('new functions loaded', { added });\n });\n }\n\n get stats() {\n return {\n seq: this._seq,\n };\n }\n\n get endpoint() {\n invariant(this._port);\n return `http://localhost:${this._port}`;\n }\n\n get proxy() {\n return this._proxy;\n }\n\n get functions() {\n return Object.values(this._handlers);\n }\n\n async start() {\n invariant(!this._server);\n log.info('starting...');\n this._ctx = createContext();\n\n // TODO(burdon): Move to hono.\n const app = express();\n app.use(express.json());\n\n app.post('/:path', async (req, res) => {\n const { path } = req.params;\n try {\n log.info('calling', { path });\n if (this._options.reload) {\n const { def } = this._handlers['/' + path];\n await this._load(def, true);\n }\n\n // TODO(burdon): Get function context.\n res.statusCode = await this.invoke('/' + path, req.body);\n res.end();\n } catch (err: any) {\n log.catch(err);\n res.statusCode = 500;\n res.end();\n }\n });\n\n this._port = await getPort({ host: 'localhost', port: 7200, portRange: [7200, 7299] });\n this._server = app.listen(this._port);\n\n try {\n // Register functions.\n const { registrationId, endpoint } = await this._client.services.services.FunctionRegistryService!.register({\n endpoint: this.endpoint,\n });\n\n log.info('registered', { endpoint });\n this._proxy = endpoint;\n this._functionServiceRegistration = registrationId;\n\n // Open after registration, so that it can be updated with the list of function definitions.\n await this._functionsRegistry.open(this._ctx);\n } catch (err: any) {\n await this.stop();\n throw new Error('FunctionRegistryService not available (check plugin is configured).');\n }\n\n log.info('started', { port: this._port });\n }\n\n async stop() {\n invariant(this._server);\n log.info('stopping...');\n\n const trigger = new Trigger();\n this._server.close(async () => {\n log.info('server stopped');\n try {\n if (this._functionServiceRegistration) {\n invariant(this._client.services.services.FunctionRegistryService);\n await this._client.services.services.FunctionRegistryService.unregister({\n registrationId: this._functionServiceRegistration,\n });\n\n log.info('unregistered', { registrationId: this._functionServiceRegistration });\n this._functionServiceRegistration = undefined;\n this._proxy = undefined;\n }\n\n trigger.wake();\n } catch (err) {\n trigger.throw(err as Error);\n }\n });\n\n await trigger.wait();\n this._port = undefined;\n this._server = undefined;\n log.info('stopped');\n }\n\n /**\n * Load function.\n */\n private async _load(def: FunctionDef, force?: boolean | undefined) {\n const { uri, route, handler } = def;\n const filePath = join(this._options.baseDir, handler);\n log.info('loading', { uri, force });\n\n // Remove from cache.\n if (force) {\n Object.keys(require.cache)\n .filter((key) => key.startsWith(filePath))\n .forEach((key) => {\n delete require.cache[key];\n });\n }\n\n // TODO(burdon): Import types.\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const module = require(filePath);\n if (typeof module.default !== 'function') {\n throw new Error(`Handler must export default function: ${uri}`);\n }\n\n this._handlers[route] = { def, handler: module.default };\n }\n\n private async _safeUpdateRegistration(): Promise<void> {\n invariant(this._functionServiceRegistration);\n try {\n await this._client.services.services.FunctionRegistryService!.updateRegistration({\n registrationId: this._functionServiceRegistration,\n functions: this.functions.map(({ def: { id, route } }) => ({ id, route })),\n });\n } catch (err) {\n log.catch(err);\n }\n }\n\n /**\n * Invoke function.\n */\n public async invoke(path: string, data: any): Promise<number> {\n const seq = ++this._seq;\n const now = Date.now();\n\n log.info('req', { seq, path });\n const statusCode = await this._invoke(path, { data });\n\n log.info('res', { seq, path, statusCode, duration: Date.now() - now });\n this.update.emit(statusCode);\n return statusCode;\n }\n\n private async _invoke(path: string, event: FunctionEvent) {\n const { handler } = this._handlers[path] ?? {};\n invariant(handler, `invalid path: ${path}`);\n const context: FunctionContext = {\n client: this._client,\n dataDir: this._options.dataDir,\n };\n\n let statusCode = 200;\n const response: FunctionResponse = {\n status: (code: number) => {\n statusCode = code;\n return response;\n },\n };\n\n await handler({ context, event, response });\n return statusCode;\n }\n}\n\nconst createContext = () => new Context({ name: 'DevServer' });\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport path from 'node:path';\n\nimport { Mutex } from '@dxos/async';\nimport { type Space } from '@dxos/client/echo';\nimport { Context } from '@dxos/context';\nimport { log } from '@dxos/log';\n\nimport { type FunctionRegistry } from '../function';\nimport { type FunctionEventMeta } from '../handler';\nimport { type TriggerRegistry } from '../trigger';\nimport { type FunctionDef, type FunctionManifest, type FunctionTrigger } from '../types';\n\nexport type Callback = (data: any) => Promise<void | number>;\n\nexport type SchedulerOptions = {\n endpoint?: string;\n callback?: Callback;\n};\n\n/**\n * The scheduler triggers function execution based on various triggers.\n */\nexport class Scheduler {\n private _ctx = createContext();\n\n private readonly _functionUriToCallMutex = new Map<string, Mutex>();\n\n constructor(\n public readonly functions: FunctionRegistry,\n public readonly triggers: TriggerRegistry,\n private readonly _options: SchedulerOptions = {},\n ) {\n this.functions.registered.on(async ({ space, added }) => {\n await this._safeActivateTriggers(space, this.triggers.getInactiveTriggers(space), added);\n });\n this.triggers.registered.on(async ({ space, triggers }) => {\n await this._safeActivateTriggers(space, triggers, this.functions.getFunctions(space));\n });\n }\n\n async start() {\n await this._ctx.dispose();\n this._ctx = createContext();\n await this.functions.open(this._ctx);\n await this.triggers.open(this._ctx);\n }\n\n async stop() {\n await this._ctx.dispose();\n await this.functions.close();\n await this.triggers.close();\n }\n\n // TODO(burdon): Remove and update registries directly.\n public async register(space: Space, manifest: FunctionManifest) {\n await this.functions.register(space, manifest.functions);\n await this.triggers.register(space, manifest);\n }\n\n private async _safeActivateTriggers(\n space: Space,\n triggers: FunctionTrigger[],\n functions: FunctionDef[],\n ): Promise<void> {\n const mountTasks = triggers.map((trigger) => {\n return this.activate(space, functions, trigger);\n });\n await Promise.all(mountTasks).catch(log.catch);\n }\n\n private async activate(space: Space, functions: FunctionDef[], trigger: FunctionTrigger) {\n const definition = functions.find((def) => def.uri === trigger.function);\n if (!definition) {\n log.info('function is not found for trigger', { trigger });\n return;\n }\n\n await this.triggers.activate(space, trigger, async (args) => {\n const mutex = this._functionUriToCallMutex.get(definition.uri) ?? new Mutex();\n this._functionUriToCallMutex.set(definition.uri, mutex);\n\n log.info('function triggered, waiting for mutex', { uri: definition.uri });\n return mutex.executeSynchronized(() => {\n log.info('mutex acquired', { uri: definition.uri });\n return this._execFunction(definition, trigger, {\n meta: trigger.meta ?? {},\n data: { ...args, spaceKey: space.key },\n });\n });\n });\n\n log('activated trigger', { space: space.key, trigger });\n }\n\n private async _execFunction<TData, TMeta>(\n def: FunctionDef,\n trigger: FunctionTrigger,\n { data, meta }: { data: TData; meta?: TMeta },\n ): Promise<number> {\n let status = 0;\n try {\n // TODO(burdon): Pass in Space key (common context)?\n const payload = Object.assign({}, meta && ({ meta } satisfies FunctionEventMeta<TMeta>), data);\n\n const { endpoint, callback } = this._options;\n if (endpoint) {\n // TODO(burdon): Move out of scheduler (generalize as callback).\n const url = path.join(endpoint, def.route);\n log.info('exec', { function: def.uri, url, triggerType: trigger.spec.type });\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(payload),\n });\n\n status = response.status;\n } else if (callback) {\n log.info('exec', { function: def.uri });\n status = (await callback(payload)) ?? 200;\n }\n\n // Check errors.\n if (status && status >= 400) {\n throw new Error(`Response: ${status}`);\n }\n\n // const result = await response.json();\n log.info('done', { function: def.uri, status });\n } catch (err: any) {\n log.error('error', { function: def.uri, error: err.message });\n status = 500;\n }\n\n return status;\n }\n}\n\nconst createContext = () => new Context({ name: 'FunctionScheduler' });\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { Event } from '@dxos/async';\nimport { type Client } from '@dxos/client';\nimport { create, Filter, getMeta, type Space } from '@dxos/client/echo';\nimport { Context, Resource } from '@dxos/context';\nimport { compareForeignKeys, ECHO_ATTR_META, foreignKey } from '@dxos/echo-schema';\nimport { invariant } from '@dxos/invariant';\nimport { PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { ComplexMap, diff } from '@dxos/util';\n\nimport { createSubscriptionTrigger, createTimerTrigger, createWebhookTrigger, createWebsocketTrigger } from './type';\nimport { type FunctionManifest, FunctionTrigger, type FunctionTriggerType, type TriggerSpec } from '../types';\n\ntype ResponseCode = number;\n\nexport type TriggerCallback = (args: object) => Promise<ResponseCode>;\n\n// TODO(burdon): Make object?\nexport type TriggerFactory<Spec extends TriggerSpec, Options = any> = (\n ctx: Context,\n space: Space,\n spec: Spec,\n callback: TriggerCallback,\n options?: Options,\n) => Promise<void>;\n\nexport type TriggerHandlerMap = { [type in FunctionTriggerType]: TriggerFactory<any> };\n\nconst triggerHandlers: TriggerHandlerMap = {\n subscription: createSubscriptionTrigger,\n timer: createTimerTrigger,\n webhook: createWebhookTrigger,\n websocket: createWebsocketTrigger,\n};\n\nexport type TriggerEvent = {\n space: Space;\n triggers: FunctionTrigger[];\n};\n\ntype RegisteredTrigger = {\n activationCtx?: Context;\n trigger: FunctionTrigger;\n};\n\nexport class TriggerRegistry extends Resource {\n private readonly _triggersBySpaceKey = new ComplexMap<PublicKey, RegisteredTrigger[]>(PublicKey.hash);\n\n public readonly registered = new Event<TriggerEvent>();\n public readonly removed = new Event<TriggerEvent>();\n\n constructor(\n private readonly _client: Client,\n private readonly _options?: TriggerHandlerMap,\n ) {\n super();\n }\n\n public getActiveTriggers(space: Space): FunctionTrigger[] {\n return this._getTriggers(space, (t) => t.activationCtx != null);\n }\n\n public getInactiveTriggers(space: Space): FunctionTrigger[] {\n return this._getTriggers(space, (t) => t.activationCtx == null);\n }\n\n async activate(space: Space, trigger: FunctionTrigger, callback: TriggerCallback): Promise<void> {\n log('activate', { space: space.key, trigger });\n\n const activationCtx = new Context({ name: `FunctionTrigger-${trigger.function}` });\n this._ctx.onDispose(() => activationCtx.dispose());\n const registeredTrigger = this._triggersBySpaceKey.get(space.key)?.find((reg) => reg.trigger.id === trigger.id);\n invariant(registeredTrigger, `Trigger is not registered: ${trigger.function}`);\n registeredTrigger.activationCtx = activationCtx;\n\n try {\n const options = this._options?.[trigger.spec.type];\n await triggerHandlers[trigger.spec.type](activationCtx, space, trigger.spec, callback, options);\n } catch (err) {\n delete registeredTrigger.activationCtx;\n throw err;\n }\n }\n\n /**\n * Loads triggers from the manifest into the space.\n */\n public async register(space: Space, manifest: FunctionManifest): Promise<void> {\n log('register', { space: space.key });\n if (!manifest.triggers?.length) {\n return;\n }\n\n if (!space.db.graph.runtimeSchemaRegistry.hasSchema(FunctionTrigger)) {\n space.db.graph.runtimeSchemaRegistry.registerSchema(FunctionTrigger);\n }\n\n // Create FK to enable syncing if none are set (NOTE: Possible collision).\n const manifestTriggers = manifest.triggers.map((trigger) => {\n let keys = trigger[ECHO_ATTR_META]?.keys;\n delete trigger[ECHO_ATTR_META];\n if (!keys?.length) {\n keys = [foreignKey('manifest', [trigger.function, trigger.spec.type].join(':'))];\n }\n\n return create(FunctionTrigger, trigger, { keys });\n });\n\n // Sync triggers.\n const { objects: existing } = await space.db.query(Filter.schema(FunctionTrigger)).run();\n const { added } = diff(existing, manifestTriggers, compareForeignKeys);\n\n // TODO(burdon): Update existing.\n added.forEach((trigger) => {\n space.db.add(trigger);\n log.info('added', { meta: getMeta(trigger) });\n });\n\n if (added.length > 0) {\n await space.db.flush();\n }\n }\n\n protected override async _open(): Promise<void> {\n log.info('open...');\n const spaceListSubscription = this._client.spaces.subscribe(async (spaces) => {\n for (const space of spaces) {\n if (this._triggersBySpaceKey.has(space.key)) {\n continue;\n }\n\n const registered: RegisteredTrigger[] = [];\n this._triggersBySpaceKey.set(space.key, registered);\n await space.waitUntilReady();\n if (this._ctx.disposed) {\n break;\n }\n\n // Subscribe to updates.\n this._ctx.onDispose(\n space.db.query(Filter.schema(FunctionTrigger)).subscribe(async ({ objects: current }) => {\n log.info('update', { space: space.key, registered: registered.length, current: current.length });\n await this._handleRemovedTriggers(space, current, registered);\n this._handleNewTriggers(space, current, registered);\n }),\n );\n }\n });\n\n this._ctx.onDispose(() => spaceListSubscription.unsubscribe());\n log.info('opened');\n }\n\n protected override async _close(_: Context): Promise<void> {\n log.info('close...');\n this._triggersBySpaceKey.clear();\n log.info('closed');\n }\n\n private _handleNewTriggers(space: Space, current: FunctionTrigger[], registered: RegisteredTrigger[]) {\n const added = current.filter((candidate) => {\n return candidate.enabled && registered.find((reg) => reg.trigger.id === candidate.id) == null;\n });\n\n if (added.length > 0) {\n const newRegisteredTriggers: RegisteredTrigger[] = added.map((trigger) => ({ trigger }));\n registered.push(...newRegisteredTriggers);\n log.info('added', () => ({\n spaceKey: space.key,\n triggers: added.map((trigger) => trigger.function),\n }));\n\n this.registered.emit({ space, triggers: added });\n }\n }\n\n private async _handleRemovedTriggers(\n space: Space,\n current: FunctionTrigger[],\n registered: RegisteredTrigger[],\n ): Promise<void> {\n const removed: FunctionTrigger[] = [];\n for (let i = registered.length - 1; i >= 0; i--) {\n const wasRemoved =\n current.filter((trigger) => trigger.enabled).find((trigger) => trigger.id === registered[i].trigger.id) == null;\n if (wasRemoved) {\n const unregistered = registered.splice(i, 1)[0];\n await unregistered.activationCtx?.dispose();\n removed.push(unregistered.trigger);\n }\n }\n\n if (removed.length > 0) {\n log.info('removed', () => ({\n spaceKey: space.key,\n triggers: removed.map((trigger) => trigger.function),\n }));\n\n this.removed.emit({ space, triggers: removed });\n }\n }\n\n private _getTriggers(space: Space, predicate: (trigger: RegisteredTrigger) => boolean): FunctionTrigger[] {\n const allSpaceTriggers = this._triggersBySpaceKey.get(space.key) ?? [];\n return allSpaceTriggers.filter(predicate).map((trigger) => trigger.trigger);\n }\n}\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { TextV0Type } from '@braneframe/types';\nimport { debounce, UpdateScheduler } from '@dxos/async';\nimport { Filter, type Space } from '@dxos/client/echo';\nimport { type Context } from '@dxos/context';\nimport { createSubscription, getAutomergeObjectCore, type Query } from '@dxos/echo-db';\nimport { log } from '@dxos/log';\n\nimport type { SubscriptionTrigger } from '../../types';\nimport { type TriggerCallback, type TriggerFactory } from '../trigger-registry';\n\nexport const createSubscriptionTrigger: TriggerFactory<SubscriptionTrigger> = async (\n ctx: Context,\n space: Space,\n spec: SubscriptionTrigger,\n callback: TriggerCallback,\n) => {\n const objectIds = new Set<string>();\n const task = new UpdateScheduler(\n ctx,\n async () => {\n if (objectIds.size > 0) {\n const objects = Array.from(objectIds);\n objectIds.clear();\n await callback({ objects });\n }\n },\n { maxFrequency: 4 },\n );\n\n // TODO(burdon): Factor out diff.\n // TODO(burdon): Don't fire initially?\n // TODO(burdon): Create queue. Only allow one invocation per trigger at a time?\n const subscriptions: (() => void)[] = [];\n const subscription = createSubscription(({ added, updated }) => {\n const sizeBefore = objectIds.size;\n for (const object of added) {\n objectIds.add(object.id);\n }\n for (const object of updated) {\n objectIds.add(object.id);\n }\n if (objectIds.size > sizeBefore) {\n log.info('updated', { added: added.length, updated: updated.length });\n task.trigger();\n }\n });\n\n subscriptions.push(() => subscription.unsubscribe());\n\n // TODO(burdon): Disable trigger if keeps failing.\n const { filter, options: { deep, delay } = {} } = spec;\n const update = ({ objects }: Query) => {\n log.info('update', { objects: objects.length });\n subscription.update(objects);\n\n // TODO(burdon): Hack to monitor changes to Document's text object.\n if (deep) {\n for (const object of objects) {\n const content = object.content;\n if (content instanceof TextV0Type) {\n subscriptions.push(\n getAutomergeObjectCore(content).updates.on(debounce(() => subscription.update([object]), 1_000)),\n );\n }\n }\n }\n };\n\n // TODO(burdon): OR not working.\n // TODO(burdon): [Bug]: all callbacks are fired on the first mutation.\n // TODO(burdon): [Bug]: not updated when document is deleted (either top or hierarchically).\n log.info('subscription', { filter });\n // const query = triggerCtx.space.db.query(Filter.or(filter.map(({ type, props }) => Filter.typename(type, props))));\n if (filter) {\n const query = space.db.query(Filter.typename(filter[0].type, filter[0].props));\n subscriptions.push(query.subscribe(delay ? debounce(update, delay) : update));\n }\n\n ctx.onDispose(() => {\n subscriptions.forEach((unsubscribe) => unsubscribe());\n });\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { CronJob } from 'cron';\n\nimport { DeferredTask } from '@dxos/async';\nimport { type Space } from '@dxos/client/echo';\nimport { type Context } from '@dxos/context';\nimport { log } from '@dxos/log';\n\nimport type { TimerTrigger } from '../../types';\nimport { type TriggerCallback, type TriggerFactory } from '../trigger-registry';\n\nexport const createTimerTrigger: TriggerFactory<TimerTrigger> = async (\n ctx: Context,\n space: Space,\n spec: TimerTrigger,\n callback: TriggerCallback,\n) => {\n const task = new DeferredTask(ctx, async () => {\n await callback({});\n });\n\n let last = 0;\n let run = 0;\n // https://www.npmjs.com/package/cron#constructor\n const job = CronJob.from({\n cronTime: spec.cron,\n runOnInit: false,\n onTick: () => {\n // TODO(burdon): Check greater than 30s (use cron-parser).\n const now = Date.now();\n const delta = last ? now - last : 0;\n last = now;\n\n run++;\n log.info('tick', { space: space.key.truncate(), count: run, delta });\n task.schedule();\n },\n });\n\n job.start();\n ctx.onDispose(() => job.stop());\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { getPort } from 'get-port-please';\nimport http from 'node:http';\n\nimport { type Space } from '@dxos/client/echo';\nimport { type Context } from '@dxos/context';\nimport { log } from '@dxos/log';\n\nimport type { WebhookTrigger } from '../../types';\nimport { type TriggerCallback, type TriggerFactory } from '../trigger-registry';\n\nexport const createWebhookTrigger: TriggerFactory<WebhookTrigger> = async (\n ctx: Context,\n space: Space,\n spec: WebhookTrigger,\n callback: TriggerCallback,\n) => {\n // TODO(burdon): Enable POST hook with payload.\n const server = http.createServer(async (req, res) => {\n if (req.method !== spec.method) {\n res.statusCode = 405;\n return res.end();\n }\n res.statusCode = await callback({});\n res.end();\n });\n\n // TODO(burdon): Not used.\n // const DEF_PORT_RANGE = { min: 7500, max: 7599 };\n // const portRange = Object.assign({}, trigger.port, DEF_PORT_RANGE) as WebhookTrigger['port'];\n const port = await getPort({\n random: true,\n // portRange: [portRange!.min, portRange!.max],\n });\n\n // TODO(burdon): Update trigger object with actual port.\n server.listen(port, () => {\n log.info('started webhook', { port });\n spec.port = port;\n });\n\n ctx.onDispose(() => {\n server.close();\n });\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport WebSocket from 'ws';\n\nimport { sleep, Trigger } from '@dxos/async';\nimport { type Space } from '@dxos/client/echo';\nimport { type Context } from '@dxos/context';\nimport { log } from '@dxos/log';\n\nimport { type WebsocketTrigger } from '../../types';\nimport { type TriggerCallback, type TriggerFactory } from '../trigger-registry';\n\ninterface WebsocketTriggerOptions {\n retryDelay: number;\n maxAttempts: number;\n}\n\n/**\n * Websocket.\n * NOTE: The port must be unique, so the same hook cannot be used for multiple spaces.\n */\nexport const createWebsocketTrigger: TriggerFactory<WebsocketTrigger, WebsocketTriggerOptions> = async (\n ctx: Context,\n space: Space,\n spec: WebsocketTrigger,\n callback: TriggerCallback,\n options: WebsocketTriggerOptions = { retryDelay: 2, maxAttempts: 5 },\n) => {\n const { url, init } = spec;\n\n let ws: WebSocket;\n for (let attempt = 1; attempt <= options.maxAttempts; attempt++) {\n const open = new Trigger<boolean>();\n\n ws = new WebSocket(url);\n Object.assign(ws, {\n onopen: () => {\n log.info('opened', { url });\n if (spec.init) {\n ws.send(new TextEncoder().encode(JSON.stringify(init)));\n }\n\n open.wake(true);\n },\n\n onclose: (event) => {\n log.info('closed', { url, code: event.code });\n // Reconnect if server closes (e.g., CF restart).\n // https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent/code\n if (event.code === 1006) {\n setTimeout(async () => {\n log.info(`reconnecting in ${options.retryDelay}s...`, { url });\n await createWebsocketTrigger(ctx, space, spec, callback, options);\n }, options.retryDelay * 1_000);\n }\n\n open.wake(false);\n },\n\n onerror: (event) => {\n log.catch(event.error, { url });\n },\n\n onmessage: async (event) => {\n try {\n log.info('message');\n const data = JSON.parse(new TextDecoder().decode(event.data as Uint8Array));\n await callback({ data });\n } catch (err) {\n log.catch(err, { url });\n }\n },\n } satisfies Partial<WebSocket>);\n\n const isOpen = await open.wait();\n if (isOpen) {\n break;\n } else {\n const wait = Math.pow(attempt, 2) * options.retryDelay;\n if (attempt < options.maxAttempts) {\n log.warn(`failed to connect; trying again in ${wait}s`, { attempt });\n await sleep(wait * 1_000);\n }\n }\n }\n\n ctx.onDispose(() => {\n ws?.close();\n });\n};\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,mBAAsB;AAEtB,kBAA2C;AAC3C,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F;EAEA,MAAcqP,uBACZxQ,OACAuQ,SACA1Q,YACe;AACf,UAAM2P,UAA6B,CAAA;AACnC,aAASqB,IAAIhR,WAAWS,SAAS,GAAGuQ,KAAK,GAAGA,KAAK;AAC/C,YAAMC,aACJP,QAAQxM,OAAO,CAACwD,YAAYA,QAAQoJ,OAAO,EAAE5G,KAAK,CAACxC,YAAYA,QAAQ1D,OAAOhE,WAAWgR,CAAAA,EAAGtJ,QAAQ1D,EAAE,KAAK;AAC7G,UAAIiN,YAAY;AACd,cAAMC,eAAelR,WAAWmR,OAAOH,GAAG,CAAA,EAAG,CAAA;AAC7C,cAAME,aAAanB,eAAepG,QAAAA;AAClCgG,gBAAQjN,KAAKwO,aAAaxJ,OAAO;MACnC;IACF;AAEA,QAAIiI,QAAQlP,SAAS,GAAG;AACtBD,kBAAAA,IAAIwB,KAAK,WAAW,OAAO;QACzByB,UAAUtD,MAAME;QAChBiJ,UAAUqG,QAAQ5L,IAAI,CAAC2D,YAAYA,QAAQyC,QAAQ;MACrD,IAAA;;;;;;AAEA,WAAKwF,QAAQhN,KAAK;QAAExC;QAAOmJ,UAAUqG;MAAQ,CAAA;IAC/C;EACF;EAEQE,aAAa1P,OAAciR,WAAuE;AACxG,UAAMC,mBAAmB,KAAK3B,oBAAoBtP,IAAID,MAAME,GAAG,KAAK,CAAA;AACpE,WAAOgR,iBAAiBnN,OAAOkN,SAAAA,EAAWrN,IAAI,CAAC2D,YAAYA,QAAQA,OAAO;EAC5E;AACF;",
6
- "names": ["import_log", "import_util", "import_async", "import_context", "import_node_path", "import_echo", "import_invariant", "import_keys", "import_types", "import_get_port_please", "FunctionRegistry", "Resource", "constructor", "_client", "_functionBySpaceKey", "ComplexMap", "PublicKey", "hash", "registered", "Event", "getFunctions", "space", "get", "key", "register", "functions", "log", "length", "db", "graph", "runtimeSchemaRegistry", "hasSchema", "FunctionDef", "registerSchema", "objects", "existing", "query", "Filter", "schema", "run", "added", "diff", "a", "b", "uri", "forEach", "def", "add", "create", "_open", "info", "spacesSubscription", "spaces", "subscribe", "has", "set", "waitUntilReady", "_ctx", "disposed", "onDispose", "push", "emit", "unsubscribe", "_close", "_", "clear", "subscriptionHandler", "handler", "types", "event", "data", "context", "response", "rest", "client", "spaceKey", "from", "undefined", "error", "status", "registerTypes", "map", "id", "getObjectById", "filter", "nonNullable", "warn", "truncate", "registry", "type", "TextV0Type", "DevServer", "_functionsRegistry", "_options", "createContext", "_handlers", "_seq", "update", "on", "_load", "_safeUpdateRegistration", "stats", "seq", "endpoint", "invariant", "_port", "proxy", "_proxy", "Object", "values", "start", "_server", "app", "express", "use", "json", "post", "req", "res", "path", "params", "reload", "statusCode", "invoke", "body", "end", "err", "catch", "getPort", "host", "port", "portRange", "listen", "registrationId", "services", "FunctionRegistryService", "_functionServiceRegistration", "open", "stop", "Error", "trigger", "Trigger", "close", "unregister", "wake", "throw", "wait", "force", "route", "filePath", "join", "baseDir", "keys", "require", "cache", "startsWith", "module", "default", "updateRegistration", "now", "Date", "_invoke", "duration", "dataDir", "code", "Context", "name", "Scheduler", "triggers", "_functionUriToCallMutex", "Map", "_safeActivateTriggers", "getInactiveTriggers", "dispose", "manifest", "mountTasks", "activate", "Promise", "all", "definition", "find", "function", "args", "mutex", "Mutex", "executeSynchronized", "_execFunction", "meta", "payload", "assign", "callback", "url", "triggerType", "spec", "fetch", "method", "headers", "JSON", "stringify", "message", "createSubscriptionTrigger", "ctx", "objectIds", "Set", "task", "UpdateScheduler", "size", "Array", "maxFrequency", "subscriptions", "subscription", "createSubscription", "updated", "sizeBefore", "object", "options", "deep", "delay", "content", "getAutomergeObjectCore", "updates", "debounce", "typename", "props", "createTimerTrigger", "DeferredTask", "last", "job", "CronJob", "cronTime", "cron", "runOnInit", "onTick", "delta", "count", "schedule", "createWebhookTrigger", "server", "http", "createServer", "random", "createWebsocketTrigger", "retryDelay", "maxAttempts", "init", "ws", "attempt", "WebSocket", "onopen", "send", "TextEncoder", "encode", "onclose", "setTimeout", "onerror", "onmessage", "parse", "TextDecoder", "decode", "isOpen", "Math", "pow", "sleep", "triggerHandlers", "timer", "webhook", "websocket", "TriggerRegistry", "_triggersBySpaceKey", "removed", "getActiveTriggers", "_getTriggers", "t", "activationCtx", "registeredTrigger", "reg", "FunctionTrigger", "manifestTriggers", "ECHO_ATTR_META", "foreignKey", "compareForeignKeys", "getMeta", "flush", "spaceListSubscription", "current", "_handleRemovedTriggers", "_handleNewTriggers", "candidate", "enabled", "newRegisteredTriggers", "i", "wasRemoved", "unregistered", "splice", "predicate", "allSpaceTriggers"]
4
+ "sourcesContent": ["//\n// Copyright 2024 DXOS.org\n//\n\nimport { Event } from '@dxos/async';\nimport { type Client } from '@dxos/client';\nimport { create, Filter, type Space } from '@dxos/client/echo';\nimport { type Context, Resource } from '@dxos/context';\nimport { PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { ComplexMap, diff } from '@dxos/util';\n\nimport { FunctionDef, type FunctionManifest } from '../types';\n\nexport type FunctionsRegisteredEvent = {\n space: Space;\n added: FunctionDef[];\n};\n\nexport class FunctionRegistry extends Resource {\n private readonly _functionBySpaceKey = new ComplexMap<PublicKey, FunctionDef[]>(PublicKey.hash);\n\n public readonly registered = new Event<FunctionsRegisteredEvent>();\n\n constructor(private readonly _client: Client) {\n super();\n }\n\n public getFunctions(space: Space): FunctionDef[] {\n return this._functionBySpaceKey.get(space.key) ?? [];\n }\n\n /**\n * Loads function definitions from the manifest into the space.\n * We first load all the definitions from the space to deduplicate by functionId.\n */\n public async register(space: Space, functions: FunctionManifest['functions']): Promise<void> {\n log('register', { space: space.key, functions: functions?.length ?? 0 });\n if (!functions?.length) {\n return;\n }\n if (!space.db.graph.runtimeSchemaRegistry.hasSchema(FunctionDef)) {\n space.db.graph.runtimeSchemaRegistry.registerSchema(FunctionDef);\n }\n\n // Sync definitions.\n const { objects: existing } = await space.db.query(Filter.schema(FunctionDef)).run();\n const { added } = diff(existing, functions, (a, b) => a.uri === b.uri);\n // TODO(burdon): Update existing templates.\n added.forEach((def) => space.db.add(create(FunctionDef, def)));\n }\n\n protected override async _open(): Promise<void> {\n log.info('opening...');\n const spacesSubscription = this._client.spaces.subscribe(async (spaces) => {\n for (const space of spaces) {\n if (this._functionBySpaceKey.has(space.key)) {\n continue;\n }\n\n const registered: FunctionDef[] = [];\n this._functionBySpaceKey.set(space.key, registered);\n await space.waitUntilReady();\n if (this._ctx.disposed) {\n break;\n }\n\n // Subscribe to updates.\n this._ctx.onDispose(\n space.db.query(Filter.schema(FunctionDef)).subscribe(({ objects }) => {\n const { added } = diff(registered, objects, (a, b) => a.uri === b.uri);\n // TODO(burdon): Update and remove.\n if (added.length > 0) {\n registered.push(...added);\n this.registered.emit({ space, added });\n }\n }),\n );\n }\n });\n\n // TODO(burdon): API: Normalize unsubscribe methods.\n this._ctx.onDispose(() => spacesSubscription.unsubscribe());\n }\n\n protected override async _close(_: Context): Promise<void> {\n log.info('closing...');\n this._functionBySpaceKey.clear();\n }\n}\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport { type Client, PublicKey } from '@dxos/client';\nimport { type Space } from '@dxos/client/echo';\nimport { type EchoReactiveObject } from '@dxos/echo-schema';\nimport { log } from '@dxos/log';\nimport { nonNullable } from '@dxos/util';\n\n// TODO(burdon): Model after http request. Ref Lambda/OpenFaaS.\n// https://docs.aws.amazon.com/lambda/latest/dg/typescript-handler.html\n// https://www.serverless.com/framework/docs/providers/aws/guide/serverless.yml/#functions\n// https://www.npmjs.com/package/aws-lambda\n\n/**\n * Function handler.\n */\nexport type FunctionHandler<TData = {}, TMeta = {}> = (params: {\n context: FunctionContext;\n event: FunctionEvent<TData, TMeta>;\n response: FunctionResponse;\n}) => Promise<FunctionResponse | void>;\n\n/**\n * Function context.\n */\nexport interface FunctionContext {\n // TODO(burdon): Limit access to individual space.\n client: Client;\n // TODO(burdon): Replace with storage service abstraction.\n dataDir?: string;\n}\n\n/**\n * Event payload.\n */\nexport type FunctionEvent<TData = {}, TMeta = {}> = {\n data: FunctionEventMeta<TMeta> & TData;\n};\n\n/**\n * Metadata from trigger.\n */\nexport type FunctionEventMeta<TMeta = {}> = {\n meta: TMeta;\n};\n\n/**\n * Function response.\n */\nexport interface FunctionResponse {\n status(code: number): FunctionResponse;\n}\n\n//\n// Subscription utils.\n//\n\nexport type RawSubscriptionData = {\n spaceKey?: string;\n objects?: string[];\n};\n\nexport type SubscriptionData = {\n space?: Space;\n objects?: EchoReactiveObject<any>[];\n};\n\n/**\n * Handler wrapper for subscription events; extracts space and objects.\n *\n * To test:\n * ```\n * curl -s -X POST -H \"Content-Type: application/json\" --data '{\"space\": \"0446...1cbb\"}' http://localhost:7100/dev/email-extractor\n * ```\n *\n * NOTE: Get space key from devtools or `dx space list --json`\n */\nexport const subscriptionHandler = <TMeta>(\n handler: FunctionHandler<SubscriptionData, TMeta>,\n): FunctionHandler<RawSubscriptionData, TMeta> => {\n return ({ event: { data }, context, ...rest }) => {\n const { client } = context;\n const space = data.spaceKey ? client.spaces.get(PublicKey.from(data.spaceKey)) : undefined;\n const objects = space\n ? data.objects?.map<EchoReactiveObject<any> | undefined>((id) => space!.db.getObjectById(id)).filter(nonNullable)\n : [];\n\n if (!!data.spaceKey && !space) {\n log.warn('invalid space', { data });\n } else {\n log.info('handler', { space: space?.key.truncate(), objects: objects?.length });\n }\n\n return handler({ event: { data: { ...data, space, objects } }, context, ...rest });\n };\n};\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport express from 'express';\nimport { getPort } from 'get-port-please';\nimport type http from 'http';\nimport { join } from 'node:path';\n\nimport { Event, Trigger } from '@dxos/async';\nimport { type Client } from '@dxos/client';\nimport { Context } from '@dxos/context';\nimport { invariant } from '@dxos/invariant';\nimport { log } from '@dxos/log';\n\nimport { type FunctionRegistry } from '../function';\nimport { type FunctionContext, type FunctionEvent, type FunctionHandler, type FunctionResponse } from '../handler';\nimport { type FunctionDef } from '../types';\n\nexport type DevServerOptions = {\n baseDir: string;\n port?: number;\n reload?: boolean;\n dataDir?: string;\n};\n\n/**\n * Functions dev server provides a local HTTP server for testing functions.\n */\nexport class DevServer {\n private _ctx = createContext();\n\n // Function handlers indexed by name (URL path).\n private readonly _handlers: Record<string, { def: FunctionDef; handler: FunctionHandler<any> }> = {};\n\n private _server?: http.Server;\n private _port?: number;\n private _functionServiceRegistration?: string;\n private _proxy?: string;\n private _seq = 0;\n\n public readonly update = new Event<number>();\n\n constructor(\n private readonly _client: Client,\n private readonly _functionsRegistry: FunctionRegistry,\n private readonly _options: DevServerOptions,\n ) {\n // TODO(burdon): Add/remove listener in start/stop.\n this._functionsRegistry.registered.on(async ({ added }) => {\n added.forEach((def) => this._load(def));\n await this._safeUpdateRegistration();\n log('new functions loaded', { added });\n });\n }\n\n get stats() {\n return {\n seq: this._seq,\n };\n }\n\n get endpoint() {\n invariant(this._port);\n return `http://localhost:${this._port}`;\n }\n\n get proxy() {\n return this._proxy;\n }\n\n get functions() {\n return Object.values(this._handlers);\n }\n\n async start() {\n invariant(!this._server);\n log.info('starting...');\n this._ctx = createContext();\n\n // TODO(burdon): Move to hono.\n const app = express();\n app.use(express.json());\n\n app.post('/:path', async (req, res) => {\n const { path } = req.params;\n try {\n log.info('calling', { path });\n if (this._options.reload) {\n const { def } = this._handlers['/' + path];\n await this._load(def, true);\n }\n\n // TODO(burdon): Get function context.\n res.statusCode = await this.invoke('/' + path, req.body);\n res.end();\n } catch (err: any) {\n log.catch(err);\n res.statusCode = 500;\n res.end();\n }\n });\n\n this._port = await getPort({ host: 'localhost', port: 7200, portRange: [7200, 7299] });\n this._server = app.listen(this._port);\n\n try {\n // Register functions.\n const { registrationId, endpoint } = await this._client.services.services.FunctionRegistryService!.register({\n endpoint: this.endpoint,\n });\n\n log.info('registered', { endpoint });\n this._proxy = endpoint;\n this._functionServiceRegistration = registrationId;\n\n // Open after registration, so that it can be updated with the list of function definitions.\n await this._functionsRegistry.open(this._ctx);\n } catch (err: any) {\n await this.stop();\n throw new Error('FunctionRegistryService not available (check plugin is configured).');\n }\n\n log.info('started', { port: this._port });\n }\n\n async stop() {\n invariant(this._server);\n log.info('stopping...');\n\n const trigger = new Trigger();\n this._server.close(async () => {\n log.info('server stopped');\n try {\n if (this._functionServiceRegistration) {\n invariant(this._client.services.services.FunctionRegistryService);\n await this._client.services.services.FunctionRegistryService.unregister({\n registrationId: this._functionServiceRegistration,\n });\n\n log.info('unregistered', { registrationId: this._functionServiceRegistration });\n this._functionServiceRegistration = undefined;\n this._proxy = undefined;\n }\n\n trigger.wake();\n } catch (err) {\n trigger.throw(err as Error);\n }\n });\n\n await trigger.wait();\n this._port = undefined;\n this._server = undefined;\n log.info('stopped');\n }\n\n /**\n * Load function.\n */\n private async _load(def: FunctionDef, force?: boolean | undefined) {\n const { uri, route, handler } = def;\n const filePath = join(this._options.baseDir, handler);\n log.info('loading', { uri, force });\n\n // Remove from cache.\n if (force) {\n Object.keys(require.cache)\n .filter((key) => key.startsWith(filePath))\n .forEach((key) => {\n delete require.cache[key];\n });\n }\n\n // TODO(burdon): Import types.\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const module = require(filePath);\n if (typeof module.default !== 'function') {\n throw new Error(`Handler must export default function: ${uri}`);\n }\n\n this._handlers[route] = { def, handler: module.default };\n }\n\n private async _safeUpdateRegistration(): Promise<void> {\n invariant(this._functionServiceRegistration);\n try {\n await this._client.services.services.FunctionRegistryService!.updateRegistration({\n registrationId: this._functionServiceRegistration,\n functions: this.functions.map(({ def: { id, route } }) => ({ id, route })),\n });\n } catch (err) {\n log.catch(err);\n }\n }\n\n /**\n * Invoke function.\n */\n public async invoke(path: string, data: any): Promise<number> {\n const seq = ++this._seq;\n const now = Date.now();\n\n log.info('req', { seq, path });\n const statusCode = await this._invoke(path, { data });\n\n log.info('res', { seq, path, statusCode, duration: Date.now() - now });\n this.update.emit(statusCode);\n return statusCode;\n }\n\n private async _invoke(path: string, event: FunctionEvent) {\n const { handler } = this._handlers[path] ?? {};\n invariant(handler, `invalid path: ${path}`);\n const context: FunctionContext = {\n client: this._client,\n dataDir: this._options.dataDir,\n };\n\n let statusCode = 200;\n const response: FunctionResponse = {\n status: (code: number) => {\n statusCode = code;\n return response;\n },\n };\n\n await handler({ context, event, response });\n return statusCode;\n }\n}\n\nconst createContext = () => new Context({ name: 'DevServer' });\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport path from 'node:path';\n\nimport { Mutex } from '@dxos/async';\nimport { type Space } from '@dxos/client/echo';\nimport { Context } from '@dxos/context';\nimport { log } from '@dxos/log';\n\nimport { type FunctionRegistry } from '../function';\nimport { type FunctionEventMeta } from '../handler';\nimport { type TriggerRegistry } from '../trigger';\nimport { type FunctionDef, type FunctionManifest, type FunctionTrigger } from '../types';\n\nexport type Callback = (data: any) => Promise<void | number>;\n\nexport type SchedulerOptions = {\n endpoint?: string;\n callback?: Callback;\n};\n\n/**\n * The scheduler triggers function execution based on various triggers.\n */\nexport class Scheduler {\n private _ctx = createContext();\n\n private readonly _functionUriToCallMutex = new Map<string, Mutex>();\n\n constructor(\n public readonly functions: FunctionRegistry,\n public readonly triggers: TriggerRegistry,\n private readonly _options: SchedulerOptions = {},\n ) {\n this.functions.registered.on(async ({ space, added }) => {\n await this._safeActivateTriggers(space, this.triggers.getInactiveTriggers(space), added);\n });\n this.triggers.registered.on(async ({ space, triggers }) => {\n await this._safeActivateTriggers(space, triggers, this.functions.getFunctions(space));\n });\n }\n\n async start() {\n await this._ctx.dispose();\n this._ctx = createContext();\n await this.functions.open(this._ctx);\n await this.triggers.open(this._ctx);\n }\n\n async stop() {\n await this._ctx.dispose();\n await this.functions.close();\n await this.triggers.close();\n }\n\n // TODO(burdon): Remove and update registries directly.\n public async register(space: Space, manifest: FunctionManifest) {\n await this.functions.register(space, manifest.functions);\n await this.triggers.register(space, manifest);\n }\n\n private async _safeActivateTriggers(\n space: Space,\n triggers: FunctionTrigger[],\n functions: FunctionDef[],\n ): Promise<void> {\n const mountTasks = triggers.map((trigger) => {\n return this.activate(space, functions, trigger);\n });\n await Promise.all(mountTasks).catch(log.catch);\n }\n\n private async activate(space: Space, functions: FunctionDef[], trigger: FunctionTrigger) {\n const definition = functions.find((def) => def.uri === trigger.function);\n if (!definition) {\n log.info('function is not found for trigger', { trigger });\n return;\n }\n\n await this.triggers.activate(space, trigger, async (args) => {\n const mutex = this._functionUriToCallMutex.get(definition.uri) ?? new Mutex();\n this._functionUriToCallMutex.set(definition.uri, mutex);\n\n log.info('function triggered, waiting for mutex', { uri: definition.uri });\n return mutex.executeSynchronized(() => {\n log.info('mutex acquired', { uri: definition.uri });\n return this._execFunction(definition, trigger, {\n meta: trigger.meta ?? {},\n data: { ...args, spaceKey: space.key },\n });\n });\n });\n\n log('activated trigger', { space: space.key, trigger });\n }\n\n private async _execFunction<TData, TMeta>(\n def: FunctionDef,\n trigger: FunctionTrigger,\n { data, meta }: { data: TData; meta?: TMeta },\n ): Promise<number> {\n let status = 0;\n try {\n // TODO(burdon): Pass in Space key (common context)?\n const payload = Object.assign({}, meta && ({ meta } satisfies FunctionEventMeta<TMeta>), data);\n\n const { endpoint, callback } = this._options;\n if (endpoint) {\n // TODO(burdon): Move out of scheduler (generalize as callback).\n const url = path.join(endpoint, def.route);\n log.info('exec', { function: def.uri, url, triggerType: trigger.spec.type });\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(payload),\n });\n\n status = response.status;\n } else if (callback) {\n log.info('exec', { function: def.uri });\n status = (await callback(payload)) ?? 200;\n }\n\n // Check errors.\n if (status && status >= 400) {\n throw new Error(`Response: ${status}`);\n }\n\n // const result = await response.json();\n log.info('done', { function: def.uri, status });\n } catch (err: any) {\n log.error('error', { function: def.uri, error: err.message });\n status = 500;\n }\n\n return status;\n }\n}\n\nconst createContext = () => new Context({ name: 'FunctionScheduler' });\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { Event } from '@dxos/async';\nimport { type Client } from '@dxos/client';\nimport { create, Filter, getMeta, type Space } from '@dxos/client/echo';\nimport { Context, Resource } from '@dxos/context';\nimport { compareForeignKeys, ECHO_ATTR_META, foreignKey } from '@dxos/echo-schema';\nimport { invariant } from '@dxos/invariant';\nimport { PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { ComplexMap, diff } from '@dxos/util';\n\nimport { createSubscriptionTrigger, createTimerTrigger, createWebhookTrigger, createWebsocketTrigger } from './type';\nimport { type FunctionManifest, FunctionTrigger, type FunctionTriggerType, type TriggerSpec } from '../types';\n\ntype ResponseCode = number;\n\nexport type TriggerCallback = (args: object) => Promise<ResponseCode>;\n\n// TODO(burdon): Make object?\nexport type TriggerFactory<Spec extends TriggerSpec, Options = any> = (\n ctx: Context,\n space: Space,\n spec: Spec,\n callback: TriggerCallback,\n options?: Options,\n) => Promise<void>;\n\nexport type TriggerHandlerMap = { [type in FunctionTriggerType]: TriggerFactory<any> };\n\nconst triggerHandlers: TriggerHandlerMap = {\n subscription: createSubscriptionTrigger,\n timer: createTimerTrigger,\n webhook: createWebhookTrigger,\n websocket: createWebsocketTrigger,\n};\n\nexport type TriggerEvent = {\n space: Space;\n triggers: FunctionTrigger[];\n};\n\ntype RegisteredTrigger = {\n activationCtx?: Context;\n trigger: FunctionTrigger;\n};\n\nexport class TriggerRegistry extends Resource {\n private readonly _triggersBySpaceKey = new ComplexMap<PublicKey, RegisteredTrigger[]>(PublicKey.hash);\n\n public readonly registered = new Event<TriggerEvent>();\n public readonly removed = new Event<TriggerEvent>();\n\n constructor(\n private readonly _client: Client,\n private readonly _options?: TriggerHandlerMap,\n ) {\n super();\n }\n\n public getActiveTriggers(space: Space): FunctionTrigger[] {\n return this._getTriggers(space, (t) => t.activationCtx != null);\n }\n\n public getInactiveTriggers(space: Space): FunctionTrigger[] {\n return this._getTriggers(space, (t) => t.activationCtx == null);\n }\n\n async activate(space: Space, trigger: FunctionTrigger, callback: TriggerCallback): Promise<void> {\n log('activate', { space: space.key, trigger });\n\n const activationCtx = new Context({ name: `FunctionTrigger-${trigger.function}` });\n this._ctx.onDispose(() => activationCtx.dispose());\n const registeredTrigger = this._triggersBySpaceKey.get(space.key)?.find((reg) => reg.trigger.id === trigger.id);\n invariant(registeredTrigger, `Trigger is not registered: ${trigger.function}`);\n registeredTrigger.activationCtx = activationCtx;\n\n try {\n const options = this._options?.[trigger.spec.type];\n await triggerHandlers[trigger.spec.type](activationCtx, space, trigger.spec, callback, options);\n } catch (err) {\n delete registeredTrigger.activationCtx;\n throw err;\n }\n }\n\n /**\n * Loads triggers from the manifest into the space.\n */\n public async register(space: Space, manifest: FunctionManifest): Promise<void> {\n log('register', { space: space.key });\n if (!manifest.triggers?.length) {\n return;\n }\n\n if (!space.db.graph.runtimeSchemaRegistry.hasSchema(FunctionTrigger)) {\n space.db.graph.runtimeSchemaRegistry.registerSchema(FunctionTrigger);\n }\n\n // Create FK to enable syncing if none are set (NOTE: Possible collision).\n const manifestTriggers = manifest.triggers.map((trigger) => {\n let keys = trigger[ECHO_ATTR_META]?.keys;\n delete trigger[ECHO_ATTR_META];\n if (!keys?.length) {\n keys = [foreignKey('manifest', [trigger.function, trigger.spec.type].join(':'))];\n }\n\n return create(FunctionTrigger, trigger, { keys });\n });\n\n // Sync triggers.\n const { objects: existing } = await space.db.query(Filter.schema(FunctionTrigger)).run();\n const { added } = diff(existing, manifestTriggers, compareForeignKeys);\n\n // TODO(burdon): Update existing.\n added.forEach((trigger) => {\n space.db.add(trigger);\n log.info('added', { meta: getMeta(trigger) });\n });\n\n if (added.length > 0) {\n await space.db.flush();\n }\n }\n\n protected override async _open(): Promise<void> {\n log.info('open...');\n const spaceListSubscription = this._client.spaces.subscribe(async (spaces) => {\n for (const space of spaces) {\n if (this._triggersBySpaceKey.has(space.key)) {\n continue;\n }\n\n const registered: RegisteredTrigger[] = [];\n this._triggersBySpaceKey.set(space.key, registered);\n await space.waitUntilReady();\n if (this._ctx.disposed) {\n break;\n }\n\n // Subscribe to updates.\n this._ctx.onDispose(\n space.db.query(Filter.schema(FunctionTrigger)).subscribe(async ({ objects: current }) => {\n log.info('update', { space: space.key, registered: registered.length, current: current.length });\n await this._handleRemovedTriggers(space, current, registered);\n this._handleNewTriggers(space, current, registered);\n }),\n );\n }\n });\n\n this._ctx.onDispose(() => spaceListSubscription.unsubscribe());\n log.info('opened');\n }\n\n protected override async _close(_: Context): Promise<void> {\n log.info('close...');\n this._triggersBySpaceKey.clear();\n log.info('closed');\n }\n\n private _handleNewTriggers(space: Space, current: FunctionTrigger[], registered: RegisteredTrigger[]) {\n const added = current.filter((candidate) => {\n return candidate.enabled && registered.find((reg) => reg.trigger.id === candidate.id) == null;\n });\n\n if (added.length > 0) {\n const newRegisteredTriggers: RegisteredTrigger[] = added.map((trigger) => ({ trigger }));\n registered.push(...newRegisteredTriggers);\n log.info('added', () => ({\n spaceKey: space.key,\n triggers: added.map((trigger) => trigger.function),\n }));\n\n this.registered.emit({ space, triggers: added });\n }\n }\n\n private async _handleRemovedTriggers(\n space: Space,\n current: FunctionTrigger[],\n registered: RegisteredTrigger[],\n ): Promise<void> {\n const removed: FunctionTrigger[] = [];\n for (let i = registered.length - 1; i >= 0; i--) {\n const wasRemoved =\n current.filter((trigger) => trigger.enabled).find((trigger) => trigger.id === registered[i].trigger.id) == null;\n if (wasRemoved) {\n const unregistered = registered.splice(i, 1)[0];\n await unregistered.activationCtx?.dispose();\n removed.push(unregistered.trigger);\n }\n }\n\n if (removed.length > 0) {\n log.info('removed', () => ({\n spaceKey: space.key,\n triggers: removed.map((trigger) => trigger.function),\n }));\n\n this.removed.emit({ space, triggers: removed });\n }\n }\n\n private _getTriggers(space: Space, predicate: (trigger: RegisteredTrigger) => boolean): FunctionTrigger[] {\n const allSpaceTriggers = this._triggersBySpaceKey.get(space.key) ?? [];\n return allSpaceTriggers.filter(predicate).map((trigger) => trigger.trigger);\n }\n}\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { TextV0Type } from '@braneframe/types';\nimport { debounce, UpdateScheduler } from '@dxos/async';\nimport { Filter, type Space } from '@dxos/client/echo';\nimport { type Context } from '@dxos/context';\nimport { createSubscription, getAutomergeObjectCore, type Query } from '@dxos/echo-db';\nimport { log } from '@dxos/log';\n\nimport type { SubscriptionTrigger } from '../../types';\nimport { type TriggerCallback, type TriggerFactory } from '../trigger-registry';\n\nexport const createSubscriptionTrigger: TriggerFactory<SubscriptionTrigger> = async (\n ctx: Context,\n space: Space,\n spec: SubscriptionTrigger,\n callback: TriggerCallback,\n) => {\n const objectIds = new Set<string>();\n const task = new UpdateScheduler(\n ctx,\n async () => {\n if (objectIds.size > 0) {\n const objects = Array.from(objectIds);\n objectIds.clear();\n await callback({ objects });\n }\n },\n { maxFrequency: 4 },\n );\n\n // TODO(burdon): Factor out diff.\n // TODO(burdon): Don't fire initially?\n // TODO(burdon): Create queue. Only allow one invocation per trigger at a time?\n const subscriptions: (() => void)[] = [];\n const subscription = createSubscription(({ added, updated }) => {\n const sizeBefore = objectIds.size;\n for (const object of added) {\n objectIds.add(object.id);\n }\n for (const object of updated) {\n objectIds.add(object.id);\n }\n if (objectIds.size > sizeBefore) {\n log.info('updated', { added: added.length, updated: updated.length });\n task.trigger();\n }\n });\n\n subscriptions.push(() => subscription.unsubscribe());\n\n // TODO(burdon): Disable trigger if keeps failing.\n const { filter, options: { deep, delay } = {} } = spec;\n const update = ({ objects }: Query) => {\n log.info('update', { objects: objects.length });\n subscription.update(objects);\n\n // TODO(burdon): Hack to monitor changes to Document's text object.\n if (deep) {\n for (const object of objects) {\n const content = object.content;\n if (content instanceof TextV0Type) {\n subscriptions.push(\n getAutomergeObjectCore(content).updates.on(debounce(() => subscription.update([object]), 1_000)),\n );\n }\n }\n }\n };\n\n // TODO(burdon): OR not working.\n // TODO(burdon): [Bug]: all callbacks are fired on the first mutation.\n // TODO(burdon): [Bug]: not updated when document is deleted (either top or hierarchically).\n log.info('subscription', { filter });\n // const query = triggerCtx.space.db.query(Filter.or(filter.map(({ type, props }) => Filter.typename(type, props))));\n if (filter) {\n const query = space.db.query(Filter.typename(filter[0].type, filter[0].props));\n subscriptions.push(query.subscribe(delay ? debounce(update, delay) : update));\n }\n\n ctx.onDispose(() => {\n subscriptions.forEach((unsubscribe) => unsubscribe());\n });\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { CronJob } from 'cron';\n\nimport { DeferredTask } from '@dxos/async';\nimport { type Space } from '@dxos/client/echo';\nimport { type Context } from '@dxos/context';\nimport { log } from '@dxos/log';\n\nimport type { TimerTrigger } from '../../types';\nimport { type TriggerCallback, type TriggerFactory } from '../trigger-registry';\n\nexport const createTimerTrigger: TriggerFactory<TimerTrigger> = async (\n ctx: Context,\n space: Space,\n spec: TimerTrigger,\n callback: TriggerCallback,\n) => {\n const task = new DeferredTask(ctx, async () => {\n await callback({});\n });\n\n let last = 0;\n let run = 0;\n // https://www.npmjs.com/package/cron#constructor\n const job = CronJob.from({\n cronTime: spec.cron,\n runOnInit: false,\n onTick: () => {\n // TODO(burdon): Check greater than 30s (use cron-parser).\n const now = Date.now();\n const delta = last ? now - last : 0;\n last = now;\n\n run++;\n log.info('tick', { space: space.key.truncate(), count: run, delta });\n task.schedule();\n },\n });\n\n job.start();\n ctx.onDispose(() => job.stop());\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { getPort } from 'get-port-please';\nimport http from 'node:http';\n\nimport { type Space } from '@dxos/client/echo';\nimport { type Context } from '@dxos/context';\nimport { log } from '@dxos/log';\n\nimport type { WebhookTrigger } from '../../types';\nimport { type TriggerCallback, type TriggerFactory } from '../trigger-registry';\n\nexport const createWebhookTrigger: TriggerFactory<WebhookTrigger> = async (\n ctx: Context,\n space: Space,\n spec: WebhookTrigger,\n callback: TriggerCallback,\n) => {\n // TODO(burdon): Enable POST hook with payload.\n const server = http.createServer(async (req, res) => {\n if (req.method !== spec.method) {\n res.statusCode = 405;\n return res.end();\n }\n res.statusCode = await callback({});\n res.end();\n });\n\n // TODO(burdon): Not used.\n // const DEF_PORT_RANGE = { min: 7500, max: 7599 };\n // const portRange = Object.assign({}, trigger.port, DEF_PORT_RANGE) as WebhookTrigger['port'];\n const port = await getPort({\n random: true,\n // portRange: [portRange!.min, portRange!.max],\n });\n\n // TODO(burdon): Update trigger object with actual port.\n server.listen(port, () => {\n log.info('started webhook', { port });\n spec.port = port;\n });\n\n ctx.onDispose(() => {\n server.close();\n });\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport WebSocket from 'ws';\n\nimport { sleep, Trigger } from '@dxos/async';\nimport { type Space } from '@dxos/client/echo';\nimport { type Context } from '@dxos/context';\nimport { log } from '@dxos/log';\n\nimport { type WebsocketTrigger } from '../../types';\nimport { type TriggerCallback, type TriggerFactory } from '../trigger-registry';\n\ninterface WebsocketTriggerOptions {\n retryDelay: number;\n maxAttempts: number;\n}\n\n/**\n * Websocket.\n * NOTE: The port must be unique, so the same hook cannot be used for multiple spaces.\n */\nexport const createWebsocketTrigger: TriggerFactory<WebsocketTrigger, WebsocketTriggerOptions> = async (\n ctx: Context,\n space: Space,\n spec: WebsocketTrigger,\n callback: TriggerCallback,\n options: WebsocketTriggerOptions = { retryDelay: 2, maxAttempts: 5 },\n) => {\n const { url, init } = spec;\n\n let ws: WebSocket;\n for (let attempt = 1; attempt <= options.maxAttempts; attempt++) {\n const open = new Trigger<boolean>();\n\n ws = new WebSocket(url);\n Object.assign(ws, {\n onopen: () => {\n log.info('opened', { url });\n if (spec.init) {\n ws.send(new TextEncoder().encode(JSON.stringify(init)));\n }\n\n open.wake(true);\n },\n\n onclose: (event) => {\n log.info('closed', { url, code: event.code });\n // Reconnect if server closes (e.g., CF restart).\n // https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent/code\n if (event.code === 1006) {\n setTimeout(async () => {\n log.info(`reconnecting in ${options.retryDelay}s...`, { url });\n await createWebsocketTrigger(ctx, space, spec, callback, options);\n }, options.retryDelay * 1_000);\n }\n\n open.wake(false);\n },\n\n onerror: (event) => {\n log.catch(event.error, { url });\n },\n\n onmessage: async (event) => {\n try {\n log.info('message');\n const data = JSON.parse(new TextDecoder().decode(event.data as Uint8Array));\n await callback({ data });\n } catch (err) {\n log.catch(err, { url });\n }\n },\n } satisfies Partial<WebSocket>);\n\n const isOpen = await open.wait();\n if (isOpen) {\n break;\n } else {\n const wait = Math.pow(attempt, 2) * options.retryDelay;\n if (attempt < options.maxAttempts) {\n log.warn(`failed to connect; trying again in ${wait}s`, { attempt });\n await sleep(wait * 1_000);\n }\n }\n }\n\n ctx.onDispose(() => {\n ws?.close();\n });\n};\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,mBAAsB;AAEtB,kBAA2C;AAC3C,qBAAuC;AACvC,kBAA0B;AAC1B,iBAAoB;AACpB,kBAAiC;ACNjC,oBAAuC;AAGvC,IAAAA,cAAoB;AACpB,IAAAC,eAA4B;ACJ5B,qBAAoB;AACpB,6BAAwB;AAExB,uBAAqB;AAErB,IAAAC,gBAA+B;AAE/B,IAAAC,kBAAwB;AACxB,uBAA0B;AAC1B,IAAAH,cAAoB;ACTpB,IAAAI,oBAAiB;AAEjB,IAAAF,gBAAsB;AAEtB,IAAAC,kBAAwB;AACxB,IAAAH,cAAoB;ACLpB,IAAAE,gBAAsB;AAEtB,IAAAG,eAAoD;AACpD,IAAAF,kBAAkC;AAClC,yBAA+D;AAC/D,IAAAG,oBAA0B;AAC1B,IAAAC,eAA0B;AAC1B,IAAAP,cAAoB;AACpB,IAAAC,eAAiC;ACRjC,mBAA2B;AAC3B,IAAAC,gBAA0C;AAC1C,IAAAG,eAAmC;AAEnC,qBAAuE;AACvE,IAAAL,cAAoB;ACLpB,kBAAwB;AAExB,IAAAE,gBAA6B;AAG7B,IAAAF,cAAoB;ACLpB,IAAAQ,0BAAwB;AACxB,uBAAiB;AAIjB,IAAAR,cAAoB;ACLpB,gBAAsB;AAEtB,IAAAE,gBAA+B;AAG/B,IAAAF,cAAoB;;ARUb,IAAMS,mBAAN,cAA+BC,wBAAAA;EAKpCC,YAA6BC,SAAiB;AAC5C,UAAK;SADsBA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CAAA;AACnC,aAASqB,IAAI7Q,WAAWS,SAAS,GAAGoQ,KAAK,GAAGA,KAAK;AAC/C,YAAMC,aACJP,QAAQ1M,OAAO,CAACqD,YAAYA,QAAQyJ,OAAO,EAAE/G,KAAK,CAAC1C,YAAYA,QAAQvD,OAAO3D,WAAW6Q,CAAAA,EAAG3J,QAAQvD,EAAE,KAAK;AAC7G,UAAImN,YAAY;AACd,cAAMC,eAAe/Q,WAAWgR,OAAOH,GAAG,CAAA,EAAG,CAAA;AAC7C,cAAME,aAAanB,eAAevG,QAAAA;AAClCmG,gBAAQ9M,KAAKqO,aAAa7J,OAAO;MACnC;IACF;AAEA,QAAIsI,QAAQ/O,SAAS,GAAG;AACtBD,kBAAAA,IAAIwB,KAAK,WAAW,OAAO;QACzBuB,UAAUpD,MAAME;QAChB2I,UAAUwG,QAAQ9L,IAAI,CAACwD,YAAYA,QAAQ2C,QAAQ;MACrD,IAAA;;;;;;AAEA,WAAK2F,QAAQ7M,KAAK;QAAExC;QAAO6I,UAAUwG;MAAQ,CAAA;IAC/C;EACF;EAEQE,aAAavP,OAAc8Q,WAAuE;AACxG,UAAMC,mBAAmB,KAAK3B,oBAAoBnP,IAAID,MAAME,GAAG,KAAK,CAAA;AACpE,WAAO6Q,iBAAiBrN,OAAOoN,SAAAA,EAAWvN,IAAI,CAACwD,YAAYA,QAAQA,OAAO;EAC5E;AACF;",
6
+ "names": ["import_log", "import_util", "import_async", "import_context", "import_node_path", "import_echo", "import_invariant", "import_keys", "import_get_port_please", "FunctionRegistry", "Resource", "constructor", "_client", "_functionBySpaceKey", "ComplexMap", "PublicKey", "hash", "registered", "Event", "getFunctions", "space", "get", "key", "register", "functions", "log", "length", "db", "graph", "runtimeSchemaRegistry", "hasSchema", "FunctionDef", "registerSchema", "objects", "existing", "query", "Filter", "schema", "run", "added", "diff", "a", "b", "uri", "forEach", "def", "add", "create", "_open", "info", "spacesSubscription", "spaces", "subscribe", "has", "set", "waitUntilReady", "_ctx", "disposed", "onDispose", "push", "emit", "unsubscribe", "_close", "_", "clear", "subscriptionHandler", "handler", "event", "data", "context", "rest", "client", "spaceKey", "from", "undefined", "map", "id", "getObjectById", "filter", "nonNullable", "warn", "truncate", "DevServer", "_functionsRegistry", "_options", "createContext", "_handlers", "_seq", "update", "on", "_load", "_safeUpdateRegistration", "stats", "seq", "endpoint", "invariant", "_port", "proxy", "_proxy", "Object", "values", "start", "_server", "app", "express", "use", "json", "post", "req", "res", "path", "params", "reload", "statusCode", "invoke", "body", "end", "err", "catch", "getPort", "host", "port", "portRange", "listen", "registrationId", "services", "FunctionRegistryService", "_functionServiceRegistration", "open", "stop", "Error", "trigger", "Trigger", "close", "unregister", "wake", "throw", "wait", "force", "route", "filePath", "join", "baseDir", "keys", "require", "cache", "startsWith", "module", "default", "updateRegistration", "now", "Date", "_invoke", "duration", "dataDir", "response", "status", "code", "Context", "name", "Scheduler", "triggers", "_functionUriToCallMutex", "Map", "_safeActivateTriggers", "getInactiveTriggers", "dispose", "manifest", "mountTasks", "activate", "Promise", "all", "definition", "find", "function", "args", "mutex", "Mutex", "executeSynchronized", "_execFunction", "meta", "payload", "assign", "callback", "url", "triggerType", "spec", "type", "fetch", "method", "headers", "JSON", "stringify", "error", "message", "createSubscriptionTrigger", "ctx", "objectIds", "Set", "task", "UpdateScheduler", "size", "Array", "maxFrequency", "subscriptions", "subscription", "createSubscription", "updated", "sizeBefore", "object", "options", "deep", "delay", "content", "TextV0Type", "getAutomergeObjectCore", "updates", "debounce", "typename", "props", "createTimerTrigger", "DeferredTask", "last", "job", "CronJob", "cronTime", "cron", "runOnInit", "onTick", "delta", "count", "schedule", "createWebhookTrigger", "server", "http", "createServer", "random", "createWebsocketTrigger", "retryDelay", "maxAttempts", "init", "ws", "attempt", "WebSocket", "onopen", "send", "TextEncoder", "encode", "onclose", "setTimeout", "onerror", "onmessage", "parse", "TextDecoder", "decode", "isOpen", "Math", "pow", "sleep", "triggerHandlers", "timer", "webhook", "websocket", "TriggerRegistry", "_triggersBySpaceKey", "removed", "getActiveTriggers", "_getTriggers", "t", "activationCtx", "registeredTrigger", "reg", "FunctionTrigger", "manifestTriggers", "ECHO_ATTR_META", "foreignKey", "compareForeignKeys", "getMeta", "flush", "spaceListSubscription", "current", "_handleRemovedTriggers", "_handleNewTriggers", "candidate", "enabled", "newRegisteredTriggers", "i", "wasRemoved", "unregistered", "splice", "predicate", "allSpaceTriggers"]
7
7
  }
@@ -1 +1 @@
1
- {"inputs":{"packages/core/functions/src/types.ts":{"bytes":9711,"imports":[{"path":"@dxos/echo-schema","kind":"import-statement","external":true}],"format":"esm"},"packages/core/functions/src/function/function-registry.ts":{"bytes":11375,"imports":[{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/client/echo","kind":"import-statement","external":true},{"path":"@dxos/context","kind":"import-statement","external":true},{"path":"@dxos/keys","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"packages/core/functions/src/types.ts","kind":"import-statement","original":"../types"}],"format":"esm"},"packages/core/functions/src/function/index.ts":{"bytes":529,"imports":[{"path":"packages/core/functions/src/function/function-registry.ts","kind":"import-statement","original":"./function-registry"}],"format":"esm"},"packages/core/functions/src/handler.ts":{"bytes":9375,"imports":[{"path":"@braneframe/types","kind":"import-statement","external":true},{"path":"@dxos/client","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true}],"format":"esm"},"packages/core/functions/src/runtime/dev-server.ts":{"bytes":27983,"imports":[{"path":"express","kind":"import-statement","external":true},{"path":"get-port-please","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/context","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"<runtime>","kind":"import-statement","external":true}],"format":"esm"},"packages/core/functions/src/runtime/scheduler.ts":{"bytes":18003,"imports":[{"path":"node:path","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/context","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true}],"format":"esm"},"packages/core/functions/src/runtime/index.ts":{"bytes":598,"imports":[{"path":"packages/core/functions/src/runtime/dev-server.ts","kind":"import-statement","original":"./dev-server"},{"path":"packages/core/functions/src/runtime/scheduler.ts","kind":"import-statement","original":"./scheduler"}],"format":"esm"},"packages/core/functions/src/trigger/type/subscription-trigger.ts":{"bytes":10741,"imports":[{"path":"@braneframe/types","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/client/echo","kind":"import-statement","external":true},{"path":"@dxos/echo-db","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true}],"format":"esm"},"packages/core/functions/src/trigger/type/timer-trigger.ts":{"bytes":4173,"imports":[{"path":"cron","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true}],"format":"esm"},"packages/core/functions/src/trigger/type/webhook-trigger.ts":{"bytes":4388,"imports":[{"path":"get-port-please","kind":"import-statement","external":true},{"path":"node:http","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true}],"format":"esm"},"packages/core/functions/src/trigger/type/websocket-trigger.ts":{"bytes":10551,"imports":[{"path":"ws","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true}],"format":"esm"},"packages/core/functions/src/trigger/type/index.ts":{"bytes":865,"imports":[{"path":"packages/core/functions/src/trigger/type/subscription-trigger.ts","kind":"import-statement","original":"./subscription-trigger"},{"path":"packages/core/functions/src/trigger/type/timer-trigger.ts","kind":"import-statement","original":"./timer-trigger"},{"path":"packages/core/functions/src/trigger/type/webhook-trigger.ts","kind":"import-statement","original":"./webhook-trigger"},{"path":"packages/core/functions/src/trigger/type/websocket-trigger.ts","kind":"import-statement","original":"./websocket-trigger"}],"format":"esm"},"packages/core/functions/src/trigger/trigger-registry.ts":{"bytes":27381,"imports":[{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/client/echo","kind":"import-statement","external":true},{"path":"@dxos/context","kind":"import-statement","external":true},{"path":"@dxos/echo-schema","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/keys","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"packages/core/functions/src/trigger/type/index.ts","kind":"import-statement","original":"./type"},{"path":"packages/core/functions/src/types.ts","kind":"import-statement","original":"../types"}],"format":"esm"},"packages/core/functions/src/trigger/index.ts":{"bytes":523,"imports":[{"path":"packages/core/functions/src/trigger/trigger-registry.ts","kind":"import-statement","original":"./trigger-registry"}],"format":"esm"},"packages/core/functions/src/index.ts":{"bytes":837,"imports":[{"path":"packages/core/functions/src/function/index.ts","kind":"import-statement","original":"./function"},{"path":"packages/core/functions/src/handler.ts","kind":"import-statement","original":"./handler"},{"path":"packages/core/functions/src/runtime/index.ts","kind":"import-statement","original":"./runtime"},{"path":"packages/core/functions/src/trigger/index.ts","kind":"import-statement","original":"./trigger"},{"path":"packages/core/functions/src/types.ts","kind":"import-statement","original":"./types"}],"format":"esm"}},"outputs":{"packages/core/functions/dist/lib/node/index.cjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":58379},"packages/core/functions/dist/lib/node/index.cjs":{"imports":[{"path":"packages/core/functions/dist/lib/node/chunk-3UYUR5N5.cjs","kind":"import-statement"},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/client/echo","kind":"import-statement","external":true},{"path":"@dxos/context","kind":"import-statement","external":true},{"path":"@dxos/keys","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"@braneframe/types","kind":"import-statement","external":true},{"path":"@dxos/client","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"express","kind":"import-statement","external":true},{"path":"get-port-please","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/context","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/context","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/client/echo","kind":"import-statement","external":true},{"path":"@dxos/context","kind":"import-statement","external":true},{"path":"@dxos/echo-schema","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/keys","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"@braneframe/types","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/client/echo","kind":"import-statement","external":true},{"path":"@dxos/echo-db","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"cron","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"get-port-please","kind":"import-statement","external":true},{"path":"node:http","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"ws","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true}],"exports":["DevServer","FUNCTION_SCHEMA","FunctionDef","FunctionManifestSchema","FunctionRegistry","FunctionTrigger","Scheduler","TriggerRegistry","subscriptionHandler"],"entryPoint":"packages/core/functions/src/index.ts","inputs":{"packages/core/functions/src/function/function-registry.ts":{"bytesInOutput":2655},"packages/core/functions/src/function/index.ts":{"bytesInOutput":0},"packages/core/functions/src/index.ts":{"bytesInOutput":0},"packages/core/functions/src/handler.ts":{"bytesInOutput":1724},"packages/core/functions/src/runtime/dev-server.ts":{"bytesInOutput":7762},"packages/core/functions/src/runtime/index.ts":{"bytesInOutput":0},"packages/core/functions/src/runtime/scheduler.ts":{"bytesInOutput":4602},"packages/core/functions/src/trigger/trigger-registry.ts":{"bytesInOutput":6996},"packages/core/functions/src/trigger/type/subscription-trigger.ts":{"bytesInOutput":2387},"packages/core/functions/src/trigger/type/index.ts":{"bytesInOutput":0},"packages/core/functions/src/trigger/type/timer-trigger.ts":{"bytesInOutput":898},"packages/core/functions/src/trigger/type/webhook-trigger.ts":{"bytesInOutput":829},"packages/core/functions/src/trigger/type/websocket-trigger.ts":{"bytesInOutput":2837},"packages/core/functions/src/trigger/index.ts":{"bytesInOutput":0}},"bytes":31627},"packages/core/functions/dist/lib/node/types.cjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":93},"packages/core/functions/dist/lib/node/types.cjs":{"imports":[{"path":"packages/core/functions/dist/lib/node/chunk-3UYUR5N5.cjs","kind":"import-statement"}],"exports":["FUNCTION_SCHEMA","FunctionDef","FunctionManifestSchema","FunctionTrigger"],"entryPoint":"packages/core/functions/src/types.ts","inputs":{},"bytes":243},"packages/core/functions/dist/lib/node/chunk-3UYUR5N5.cjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":5388},"packages/core/functions/dist/lib/node/chunk-3UYUR5N5.cjs":{"imports":[{"path":"@dxos/echo-schema","kind":"import-statement","external":true}],"exports":["FUNCTION_SCHEMA","FunctionDef","FunctionManifestSchema","FunctionTrigger","__require"],"inputs":{"packages/core/functions/src/types.ts":{"bytesInOutput":1848}},"bytes":2406}}}
1
+ {"inputs":{"packages/core/functions/src/types.ts":{"bytes":9711,"imports":[{"path":"@dxos/echo-schema","kind":"import-statement","external":true}],"format":"esm"},"packages/core/functions/src/function/function-registry.ts":{"bytes":11375,"imports":[{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/client/echo","kind":"import-statement","external":true},{"path":"@dxos/context","kind":"import-statement","external":true},{"path":"@dxos/keys","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"packages/core/functions/src/types.ts","kind":"import-statement","original":"../types"}],"format":"esm"},"packages/core/functions/src/function/index.ts":{"bytes":529,"imports":[{"path":"packages/core/functions/src/function/function-registry.ts","kind":"import-statement","original":"./function-registry"}],"format":"esm"},"packages/core/functions/src/handler.ts":{"bytes":6970,"imports":[{"path":"@dxos/client","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true}],"format":"esm"},"packages/core/functions/src/runtime/dev-server.ts":{"bytes":27983,"imports":[{"path":"express","kind":"import-statement","external":true},{"path":"get-port-please","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/context","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"<runtime>","kind":"import-statement","external":true}],"format":"esm"},"packages/core/functions/src/runtime/scheduler.ts":{"bytes":18003,"imports":[{"path":"node:path","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/context","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true}],"format":"esm"},"packages/core/functions/src/runtime/index.ts":{"bytes":598,"imports":[{"path":"packages/core/functions/src/runtime/dev-server.ts","kind":"import-statement","original":"./dev-server"},{"path":"packages/core/functions/src/runtime/scheduler.ts","kind":"import-statement","original":"./scheduler"}],"format":"esm"},"packages/core/functions/src/trigger/type/subscription-trigger.ts":{"bytes":10741,"imports":[{"path":"@braneframe/types","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/client/echo","kind":"import-statement","external":true},{"path":"@dxos/echo-db","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true}],"format":"esm"},"packages/core/functions/src/trigger/type/timer-trigger.ts":{"bytes":4173,"imports":[{"path":"cron","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true}],"format":"esm"},"packages/core/functions/src/trigger/type/webhook-trigger.ts":{"bytes":4388,"imports":[{"path":"get-port-please","kind":"import-statement","external":true},{"path":"node:http","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true}],"format":"esm"},"packages/core/functions/src/trigger/type/websocket-trigger.ts":{"bytes":10551,"imports":[{"path":"ws","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true}],"format":"esm"},"packages/core/functions/src/trigger/type/index.ts":{"bytes":865,"imports":[{"path":"packages/core/functions/src/trigger/type/subscription-trigger.ts","kind":"import-statement","original":"./subscription-trigger"},{"path":"packages/core/functions/src/trigger/type/timer-trigger.ts","kind":"import-statement","original":"./timer-trigger"},{"path":"packages/core/functions/src/trigger/type/webhook-trigger.ts","kind":"import-statement","original":"./webhook-trigger"},{"path":"packages/core/functions/src/trigger/type/websocket-trigger.ts","kind":"import-statement","original":"./websocket-trigger"}],"format":"esm"},"packages/core/functions/src/trigger/trigger-registry.ts":{"bytes":27381,"imports":[{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/client/echo","kind":"import-statement","external":true},{"path":"@dxos/context","kind":"import-statement","external":true},{"path":"@dxos/echo-schema","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/keys","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"packages/core/functions/src/trigger/type/index.ts","kind":"import-statement","original":"./type"},{"path":"packages/core/functions/src/types.ts","kind":"import-statement","original":"../types"}],"format":"esm"},"packages/core/functions/src/trigger/index.ts":{"bytes":523,"imports":[{"path":"packages/core/functions/src/trigger/trigger-registry.ts","kind":"import-statement","original":"./trigger-registry"}],"format":"esm"},"packages/core/functions/src/index.ts":{"bytes":837,"imports":[{"path":"packages/core/functions/src/function/index.ts","kind":"import-statement","original":"./function"},{"path":"packages/core/functions/src/handler.ts","kind":"import-statement","original":"./handler"},{"path":"packages/core/functions/src/runtime/index.ts","kind":"import-statement","original":"./runtime"},{"path":"packages/core/functions/src/trigger/index.ts","kind":"import-statement","original":"./trigger"},{"path":"packages/core/functions/src/types.ts","kind":"import-statement","original":"./types"}],"format":"esm"}},"outputs":{"packages/core/functions/dist/lib/node/index.cjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":57216},"packages/core/functions/dist/lib/node/index.cjs":{"imports":[{"path":"packages/core/functions/dist/lib/node/chunk-3UYUR5N5.cjs","kind":"import-statement"},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/client/echo","kind":"import-statement","external":true},{"path":"@dxos/context","kind":"import-statement","external":true},{"path":"@dxos/keys","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"@dxos/client","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"express","kind":"import-statement","external":true},{"path":"get-port-please","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/context","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/context","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/client/echo","kind":"import-statement","external":true},{"path":"@dxos/context","kind":"import-statement","external":true},{"path":"@dxos/echo-schema","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/keys","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"@braneframe/types","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/client/echo","kind":"import-statement","external":true},{"path":"@dxos/echo-db","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"cron","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"get-port-please","kind":"import-statement","external":true},{"path":"node:http","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"ws","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true}],"exports":["DevServer","FUNCTION_SCHEMA","FunctionDef","FunctionManifestSchema","FunctionRegistry","FunctionTrigger","Scheduler","TriggerRegistry","subscriptionHandler"],"entryPoint":"packages/core/functions/src/index.ts","inputs":{"packages/core/functions/src/function/function-registry.ts":{"bytesInOutput":2655},"packages/core/functions/src/function/index.ts":{"bytesInOutput":0},"packages/core/functions/src/index.ts":{"bytesInOutput":0},"packages/core/functions/src/handler.ts":{"bytesInOutput":1152},"packages/core/functions/src/runtime/dev-server.ts":{"bytesInOutput":7762},"packages/core/functions/src/runtime/index.ts":{"bytesInOutput":0},"packages/core/functions/src/runtime/scheduler.ts":{"bytesInOutput":4602},"packages/core/functions/src/trigger/trigger-registry.ts":{"bytesInOutput":6996},"packages/core/functions/src/trigger/type/subscription-trigger.ts":{"bytesInOutput":2371},"packages/core/functions/src/trigger/type/index.ts":{"bytesInOutput":0},"packages/core/functions/src/trigger/type/timer-trigger.ts":{"bytesInOutput":898},"packages/core/functions/src/trigger/type/webhook-trigger.ts":{"bytesInOutput":829},"packages/core/functions/src/trigger/type/websocket-trigger.ts":{"bytesInOutput":2837},"packages/core/functions/src/trigger/index.ts":{"bytesInOutput":0}},"bytes":31039},"packages/core/functions/dist/lib/node/types.cjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":93},"packages/core/functions/dist/lib/node/types.cjs":{"imports":[{"path":"packages/core/functions/dist/lib/node/chunk-3UYUR5N5.cjs","kind":"import-statement"}],"exports":["FUNCTION_SCHEMA","FunctionDef","FunctionManifestSchema","FunctionTrigger"],"entryPoint":"packages/core/functions/src/types.ts","inputs":{},"bytes":243},"packages/core/functions/dist/lib/node/chunk-3UYUR5N5.cjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":5388},"packages/core/functions/dist/lib/node/chunk-3UYUR5N5.cjs":{"imports":[{"path":"@dxos/echo-schema","kind":"import-statement","external":true}],"exports":["FUNCTION_SCHEMA","FunctionDef","FunctionManifestSchema","FunctionTrigger","__require"],"inputs":{"packages/core/functions/src/types.ts":{"bytesInOutput":1848}},"bytes":2406}}}
@@ -1,6 +1,6 @@
1
1
  import { type Client } from '@dxos/client';
2
2
  import { type Space } from '@dxos/client/echo';
3
- import { type EchoReactiveObject, type S } from '@dxos/echo-schema';
3
+ import { type EchoReactiveObject } from '@dxos/echo-schema';
4
4
  /**
5
5
  * Function handler.
6
6
  */
@@ -52,5 +52,5 @@ export type SubscriptionData = {
52
52
  *
53
53
  * NOTE: Get space key from devtools or `dx space list --json`
54
54
  */
55
- export declare const subscriptionHandler: <TMeta>(handler: FunctionHandler<SubscriptionData, TMeta>, types?: S.Schema<any>[]) => FunctionHandler<RawSubscriptionData, TMeta>;
55
+ export declare const subscriptionHandler: <TMeta>(handler: FunctionHandler<SubscriptionData, TMeta>) => FunctionHandler<RawSubscriptionData, TMeta>;
56
56
  //# sourceMappingURL=handler.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"handler.d.ts","sourceRoot":"","sources":["../../../src/handler.ts"],"names":[],"mappings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B,GAAG;IAChC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC;CACpB,CAAC;AAEF,MAAM,MAAM,gBAAgB,GAAG;IAC7B,KAAK,CAAC,EAAE,KAAK,CAAC;IACd,OAAO,CAAC,EAAE,kBAAkB,CAAC,GAAG,CAAC,EAAE,CAAC;CACrC,CAAC;AAEF;;;;;;;;;GASG;AACH,eAAO,MAAM,mBAAmB,mBACrB,gBAAgB,gBAAgB,EAAE,KAAK,CAAC,KAChD,gBAAgB,mBAAmB,EAAE,KAAK,CAgB5C,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dxos/functions",
3
- "version": "0.5.4-main.f022b2e",
3
+ "version": "0.5.4-main.fb3ef83",
4
4
  "description": "Functions API and runtime.",
5
5
  "homepage": "https://dxos.org",
6
6
  "bugs": "https://github.com/dxos/dxos/issues",
@@ -40,23 +40,23 @@
40
40
  "express": "^4.19.2",
41
41
  "get-port-please": "^3.1.1",
42
42
  "ws": "^8.14.2",
43
- "@braneframe/types": "0.5.4-main.f022b2e",
44
- "@dxos/async": "0.5.4-main.f022b2e",
45
- "@dxos/echo-schema": "0.5.4-main.f022b2e",
46
- "@dxos/client": "0.5.4-main.f022b2e",
47
- "@dxos/context": "0.5.4-main.f022b2e",
48
- "@dxos/invariant": "0.5.4-main.f022b2e",
49
- "@dxos/keys": "0.5.4-main.f022b2e",
50
- "@dxos/echo-db": "0.5.4-main.f022b2e",
51
- "@dxos/log": "0.5.4-main.f022b2e",
52
- "@dxos/util": "0.5.4-main.f022b2e",
53
- "@dxos/protocols": "0.5.4-main.f022b2e",
54
- "@dxos/node-std": "0.5.4-main.f022b2e"
43
+ "@braneframe/types": "0.5.4-main.fb3ef83",
44
+ "@dxos/async": "0.5.4-main.fb3ef83",
45
+ "@dxos/context": "0.5.4-main.fb3ef83",
46
+ "@dxos/client": "0.5.4-main.fb3ef83",
47
+ "@dxos/echo-db": "0.5.4-main.fb3ef83",
48
+ "@dxos/invariant": "0.5.4-main.fb3ef83",
49
+ "@dxos/echo-schema": "0.5.4-main.fb3ef83",
50
+ "@dxos/keys": "0.5.4-main.fb3ef83",
51
+ "@dxos/log": "0.5.4-main.fb3ef83",
52
+ "@dxos/node-std": "0.5.4-main.fb3ef83",
53
+ "@dxos/util": "0.5.4-main.fb3ef83",
54
+ "@dxos/protocols": "0.5.4-main.fb3ef83"
55
55
  },
56
56
  "devDependencies": {
57
57
  "@types/express": "^4.17.17",
58
58
  "@types/ws": "^7.4.0",
59
- "@dxos/agent": "0.5.4-main.f022b2e"
59
+ "@dxos/agent": "0.5.4-main.fb3ef83"
60
60
  },
61
61
  "publishConfig": {
62
62
  "access": "public"
package/src/handler.ts CHANGED
@@ -2,10 +2,9 @@
2
2
  // Copyright 2023 DXOS.org
3
3
  //
4
4
 
5
- import { TextV0Type } from '@braneframe/types';
6
5
  import { type Client, PublicKey } from '@dxos/client';
7
6
  import { type Space } from '@dxos/client/echo';
8
- import { type EchoReactiveObject, type S } from '@dxos/echo-schema';
7
+ import { type EchoReactiveObject } from '@dxos/echo-schema';
9
8
  import { log } from '@dxos/log';
10
9
  import { nonNullable } from '@dxos/util';
11
10
 
@@ -78,20 +77,12 @@ export type SubscriptionData = {
78
77
  *
79
78
  * NOTE: Get space key from devtools or `dx space list --json`
80
79
  */
81
- // TODO(burdon): Evolve into plugin definition like Composer.
82
80
  export const subscriptionHandler = <TMeta>(
83
81
  handler: FunctionHandler<SubscriptionData, TMeta>,
84
- types?: S.Schema<any>[],
85
82
  ): FunctionHandler<RawSubscriptionData, TMeta> => {
86
- return async ({ event: { data }, context, response, ...rest }) => {
83
+ return ({ event: { data }, context, ...rest }) => {
87
84
  const { client } = context;
88
85
  const space = data.spaceKey ? client.spaces.get(PublicKey.from(data.spaceKey)) : undefined;
89
- if (!space) {
90
- log.error('Invalid space');
91
- return response.status(500);
92
- }
93
-
94
- registerTypes(space, types);
95
86
  const objects = space
96
87
  ? data.objects?.map<EchoReactiveObject<any> | undefined>((id) => space!.db.getObjectById(id)).filter(nonNullable)
97
88
  : [];
@@ -102,16 +93,6 @@ export const subscriptionHandler = <TMeta>(
102
93
  log.info('handler', { space: space?.key.truncate(), objects: objects?.length });
103
94
  }
104
95
 
105
- return handler({ event: { data: { ...data, space, objects } }, context, response, ...rest });
96
+ return handler({ event: { data: { ...data, space, objects } }, context, ...rest });
106
97
  };
107
98
  };
108
-
109
- // TODO(burdon): Evolve types as part of function metadata.
110
- const registerTypes = (space: Space, types: S.Schema<any>[] = []) => {
111
- const registry = space.db.graph.runtimeSchemaRegistry;
112
- for (const type of [...types, TextV0Type]) {
113
- if (!registry.hasSchema(type)) {
114
- registry.registerSchema(type);
115
- }
116
- }
117
- };