@dxos/functions 0.8.4-main.b97322e → 0.8.4-main.c4373fc

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (145) hide show
  1. package/dist/lib/browser/bundler/index.mjs +61 -39
  2. package/dist/lib/browser/bundler/index.mjs.map +3 -3
  3. package/dist/lib/browser/chunk-J5LGTIGS.mjs +10 -0
  4. package/dist/lib/browser/chunk-J5LGTIGS.mjs.map +7 -0
  5. package/dist/lib/browser/chunk-LKYT2SAL.mjs +665 -0
  6. package/dist/lib/browser/chunk-LKYT2SAL.mjs.map +7 -0
  7. package/dist/lib/browser/edge/index.mjs +22 -8
  8. package/dist/lib/browser/edge/index.mjs.map +3 -3
  9. package/dist/lib/browser/index.mjs +1035 -143
  10. package/dist/lib/browser/index.mjs.map +4 -4
  11. package/dist/lib/browser/meta.json +1 -1
  12. package/dist/lib/browser/testing/index.mjs +81 -41
  13. package/dist/lib/browser/testing/index.mjs.map +3 -3
  14. package/dist/lib/node-esm/bundler/index.mjs +60 -39
  15. package/dist/lib/node-esm/bundler/index.mjs.map +3 -3
  16. package/dist/lib/node-esm/chunk-HSLMI22Q.mjs +11 -0
  17. package/dist/lib/node-esm/chunk-HSLMI22Q.mjs.map +7 -0
  18. package/dist/lib/node-esm/chunk-NAQIKLZB.mjs +667 -0
  19. package/dist/lib/node-esm/chunk-NAQIKLZB.mjs.map +7 -0
  20. package/dist/lib/node-esm/edge/index.mjs +21 -8
  21. package/dist/lib/node-esm/edge/index.mjs.map +3 -3
  22. package/dist/lib/node-esm/index.mjs +1035 -143
  23. package/dist/lib/node-esm/index.mjs.map +4 -4
  24. package/dist/lib/node-esm/meta.json +1 -1
  25. package/dist/lib/node-esm/testing/index.mjs +81 -41
  26. package/dist/lib/node-esm/testing/index.mjs.map +3 -3
  27. package/dist/types/src/bundler/bundler.d.ts +11 -12
  28. package/dist/types/src/bundler/bundler.d.ts.map +1 -1
  29. package/dist/types/src/edge/functions.d.ts +3 -2
  30. package/dist/types/src/edge/functions.d.ts.map +1 -1
  31. package/dist/types/src/errors.d.ts +89 -20
  32. package/dist/types/src/errors.d.ts.map +1 -1
  33. package/dist/types/src/examples/fib.d.ts +7 -0
  34. package/dist/types/src/examples/fib.d.ts.map +1 -0
  35. package/dist/types/src/examples/index.d.ts +4 -0
  36. package/dist/types/src/examples/index.d.ts.map +1 -0
  37. package/dist/types/src/examples/reply.d.ts +3 -0
  38. package/dist/types/src/examples/reply.d.ts.map +1 -0
  39. package/dist/types/src/examples/sleep.d.ts +5 -0
  40. package/dist/types/src/examples/sleep.d.ts.map +1 -0
  41. package/dist/types/src/executor/executor.d.ts +7 -1
  42. package/dist/types/src/executor/executor.d.ts.map +1 -1
  43. package/dist/types/src/handler.d.ts +56 -9
  44. package/dist/types/src/handler.d.ts.map +1 -1
  45. package/dist/types/src/index.d.ts +3 -1
  46. package/dist/types/src/index.d.ts.map +1 -1
  47. package/dist/types/src/schema.d.ts +11 -6
  48. package/dist/types/src/schema.d.ts.map +1 -1
  49. package/dist/types/src/services/credentials.d.ts +20 -3
  50. package/dist/types/src/services/credentials.d.ts.map +1 -1
  51. package/dist/types/src/services/database.d.ts +44 -6
  52. package/dist/types/src/services/database.d.ts.map +1 -1
  53. package/dist/types/src/services/event-logger.d.ts +68 -30
  54. package/dist/types/src/services/event-logger.d.ts.map +1 -1
  55. package/dist/types/src/services/function-invocation-service.d.ts +28 -0
  56. package/dist/types/src/services/function-invocation-service.d.ts.map +1 -0
  57. package/dist/types/src/services/function-invocation-service.test.d.ts +2 -0
  58. package/dist/types/src/services/function-invocation-service.test.d.ts.map +1 -0
  59. package/dist/types/src/services/index.d.ts +5 -3
  60. package/dist/types/src/services/index.d.ts.map +1 -1
  61. package/dist/types/src/services/local-function-execution.d.ts +34 -0
  62. package/dist/types/src/services/local-function-execution.d.ts.map +1 -0
  63. package/dist/types/src/services/queues.d.ts +23 -6
  64. package/dist/types/src/services/queues.d.ts.map +1 -1
  65. package/dist/types/src/services/remote-function-execution-service.d.ts +22 -0
  66. package/dist/types/src/services/remote-function-execution-service.d.ts.map +1 -0
  67. package/dist/types/src/services/service-container.d.ts +7 -6
  68. package/dist/types/src/services/service-container.d.ts.map +1 -1
  69. package/dist/types/src/services/service-registry.d.ts +4 -2
  70. package/dist/types/src/services/service-registry.d.ts.map +1 -1
  71. package/dist/types/src/services/tracing.d.ts +39 -5
  72. package/dist/types/src/services/tracing.d.ts.map +1 -1
  73. package/dist/types/src/testing/layer.d.ts +11 -3
  74. package/dist/types/src/testing/layer.d.ts.map +1 -1
  75. package/dist/types/src/testing/logger.d.ts +4 -4
  76. package/dist/types/src/testing/logger.d.ts.map +1 -1
  77. package/dist/types/src/testing/persist-database.test.d.ts +2 -0
  78. package/dist/types/src/testing/persist-database.test.d.ts.map +1 -0
  79. package/dist/types/src/testing/services.d.ts +7 -18
  80. package/dist/types/src/testing/services.d.ts.map +1 -1
  81. package/dist/types/src/trace.d.ts +21 -23
  82. package/dist/types/src/trace.d.ts.map +1 -1
  83. package/dist/types/src/triggers/index.d.ts +4 -0
  84. package/dist/types/src/triggers/index.d.ts.map +1 -0
  85. package/dist/types/src/triggers/input-builder.d.ts +3 -0
  86. package/dist/types/src/triggers/input-builder.d.ts.map +1 -0
  87. package/dist/types/src/triggers/invocation-tracer.d.ts +37 -0
  88. package/dist/types/src/triggers/invocation-tracer.d.ts.map +1 -0
  89. package/dist/types/src/triggers/trigger-dispatcher.d.ts +78 -0
  90. package/dist/types/src/triggers/trigger-dispatcher.d.ts.map +1 -0
  91. package/dist/types/src/triggers/trigger-dispatcher.test.d.ts +2 -0
  92. package/dist/types/src/triggers/trigger-dispatcher.test.d.ts.map +1 -0
  93. package/dist/types/src/triggers/trigger-state-store.d.ts +28 -0
  94. package/dist/types/src/triggers/trigger-state-store.d.ts.map +1 -0
  95. package/dist/types/src/types.d.ts +71 -252
  96. package/dist/types/src/types.d.ts.map +1 -1
  97. package/dist/types/src/url.d.ts +11 -7
  98. package/dist/types/src/url.d.ts.map +1 -1
  99. package/dist/types/tsconfig.tsbuildinfo +1 -1
  100. package/package.json +38 -42
  101. package/src/bundler/bundler.test.ts +8 -9
  102. package/src/bundler/bundler.ts +38 -35
  103. package/src/edge/functions.ts +8 -5
  104. package/src/errors.ts +13 -5
  105. package/src/examples/fib.ts +32 -0
  106. package/src/examples/index.ts +7 -0
  107. package/src/examples/reply.ts +21 -0
  108. package/src/examples/sleep.ts +24 -0
  109. package/src/executor/executor.ts +14 -10
  110. package/src/handler.ts +125 -20
  111. package/src/index.ts +3 -3
  112. package/src/schema.ts +16 -2
  113. package/src/services/credentials.ts +86 -3
  114. package/src/services/database.ts +123 -18
  115. package/src/services/event-logger.ts +71 -37
  116. package/src/services/function-invocation-service.test.ts +81 -0
  117. package/src/services/function-invocation-service.ts +84 -0
  118. package/src/services/index.ts +5 -3
  119. package/src/services/local-function-execution.ts +153 -0
  120. package/src/services/queues.ts +39 -10
  121. package/src/services/remote-function-execution-service.ts +63 -0
  122. package/src/services/service-container.ts +13 -11
  123. package/src/services/service-registry.test.ts +4 -1
  124. package/src/services/service-registry.ts +11 -4
  125. package/src/services/tracing.ts +112 -11
  126. package/src/testing/layer.ts +87 -4
  127. package/src/testing/logger.ts +5 -4
  128. package/src/testing/persist-database.test.ts +87 -0
  129. package/src/testing/services.ts +11 -64
  130. package/src/trace.ts +19 -21
  131. package/src/triggers/index.ts +7 -0
  132. package/src/triggers/input-builder.ts +35 -0
  133. package/src/triggers/invocation-tracer.ts +101 -0
  134. package/src/triggers/trigger-dispatcher.test.ts +665 -0
  135. package/src/triggers/trigger-dispatcher.ts +533 -0
  136. package/src/triggers/trigger-state-store.ts +61 -0
  137. package/src/types.ts +44 -37
  138. package/src/url.ts +14 -11
  139. package/dist/lib/browser/chunk-3NGCSUEW.mjs +0 -328
  140. package/dist/lib/browser/chunk-3NGCSUEW.mjs.map +0 -7
  141. package/dist/lib/node-esm/chunk-FJ2MU7TL.mjs +0 -330
  142. package/dist/lib/node-esm/chunk-FJ2MU7TL.mjs.map +0 -7
  143. package/dist/types/src/services/function-call-service.d.ts +0 -16
  144. package/dist/types/src/services/function-call-service.d.ts.map +0 -1
  145. package/src/services/function-call-service.ts +0 -64
@@ -1,48 +1,52 @@
1
1
  import {
2
+ ComputeEvent,
3
+ ComputeEventLogger,
4
+ ComputeEventPayload,
2
5
  ConfiguredCredentialsService,
3
6
  ContextQueueService,
4
7
  CredentialsService,
5
8
  DatabaseService,
6
- EventLogger,
7
- FunctionCallService,
9
+ FUNCTIONS_META_KEY,
10
+ FUNCTIONS_PRESET_META_KEY,
11
+ FunctionError,
12
+ FunctionNotFoundError,
13
+ MESSAGE_PROPERTY_TOOL_CALL_ID,
8
14
  QueueService,
15
+ RemoteFunctionExecutionService,
9
16
  SERVICE_TAGS,
10
17
  ServiceContainer,
18
+ ServiceNotAvailableError,
11
19
  TracingService,
20
+ TriggerStateNotFoundError,
12
21
  createDefectLogger,
13
22
  createEventLogger,
14
- logCustomEvent
15
- } from "./chunk-3NGCSUEW.mjs";
23
+ getInvocationUrl,
24
+ getUserFunctionIdInMetadata,
25
+ logCustomEvent,
26
+ setUserFunctionIdInMetadata,
27
+ withAuthorization
28
+ } from "./chunk-LKYT2SAL.mjs";
29
+ import {
30
+ __export
31
+ } from "./chunk-J5LGTIGS.mjs";
16
32
 
17
33
  // src/handler.ts
18
- import { Schema } from "effect";
19
- var defineFunction = ({ name, description, inputSchema, outputSchema = Schema.Any, handler }) => {
20
- if (!Schema.isSchema(inputSchema)) {
21
- throw new Error("Input schema must be a valid schema");
22
- }
23
- if (typeof handler !== "function") {
24
- throw new Error("Handler must be a function");
25
- }
26
- return {
27
- name,
28
- description,
29
- inputSchema,
30
- outputSchema,
31
- handler
32
- };
33
- };
34
+ import * as Effect from "effect/Effect";
35
+ import * as Schema2 from "effect/Schema";
36
+ import { Obj, Type as Type2 } from "@dxos/echo";
37
+ import { assertArgument } from "@dxos/invariant";
34
38
 
35
39
  // src/schema.ts
36
- import { Schema as Schema2 } from "effect";
40
+ import * as Schema from "effect/Schema";
37
41
  import { Type } from "@dxos/echo";
38
- import { JsonSchemaType, LabelAnnotation, Ref } from "@dxos/echo-schema";
42
+ import { JsonSchemaType, LabelAnnotation, Ref } from "@dxos/echo/internal";
39
43
  import { DataType } from "@dxos/schema";
40
- var ScriptType = Schema2.Struct({
41
- name: Schema2.optional(Schema2.String),
42
- description: Schema2.optional(Schema2.String),
44
+ var ScriptType = Schema.Struct({
45
+ name: Schema.optional(Schema.String),
46
+ description: Schema.optional(Schema.String),
43
47
  // TODO(burdon): Change to hash of deployed content.
44
48
  // Whether source has changed since last deploy.
45
- changed: Schema2.optional(Schema2.Boolean),
49
+ changed: Schema.optional(Schema.Boolean),
46
50
  source: Ref(DataType.Text)
47
51
  }).pipe(Type.Obj({
48
52
  typename: "dxos.org/type/Script",
@@ -50,18 +54,28 @@ var ScriptType = Schema2.Struct({
50
54
  }), LabelAnnotation.set([
51
55
  "name"
52
56
  ]));
53
- var FunctionType = Schema2.Struct({
57
+ var FunctionType = Schema.Struct({
58
+ /**
59
+ * Global registry ID.
60
+ * NOTE: The `key` property refers to the original registry entry.
61
+ */
62
+ // TODO(burdon): Create Format type for DXN-like ids, such as this and schema type.
63
+ // TODO(dmaretskyi): Consider making it part of ECHO meta.
64
+ // TODO(dmaretskyi): Make required.
65
+ key: Schema.optional(Schema.String).annotations({
66
+ description: "Unique registration key for the blueprint"
67
+ }),
54
68
  // TODO(burdon): Rename to id/uri?
55
- name: Schema2.NonEmptyString,
56
- version: Schema2.String,
57
- description: Schema2.optional(Schema2.String),
69
+ name: Schema.NonEmptyString,
70
+ version: Schema.String,
71
+ description: Schema.optional(Schema.String),
58
72
  // Reference to a source script if it exists within ECHO.
59
73
  // TODO(burdon): Don't ref ScriptType directly (core).
60
- source: Schema2.optional(Ref(ScriptType)),
61
- inputSchema: Schema2.optional(JsonSchemaType),
62
- outputSchema: Schema2.optional(JsonSchemaType),
74
+ source: Schema.optional(Ref(ScriptType)),
75
+ inputSchema: Schema.optional(JsonSchemaType),
76
+ outputSchema: Schema.optional(JsonSchemaType),
63
77
  // Local binding to a function name.
64
- binding: Schema2.optional(Schema2.String)
78
+ binding: Schema.optional(Schema.String)
65
79
  }).pipe(Type.Obj({
66
80
  typename: "dxos.org/type/Function",
67
81
  version: "0.1.0"
@@ -69,25 +83,117 @@ var FunctionType = Schema2.Struct({
69
83
  "name"
70
84
  ]));
71
85
 
86
+ // src/handler.ts
87
+ var typeId = Symbol.for("@dxos/functions/FunctionDefinition");
88
+ var defineFunction = ({ key, name, description, inputSchema, outputSchema = Schema2.Any, handler }) => {
89
+ if (!Schema2.isSchema(inputSchema)) {
90
+ throw new Error("Input schema must be a valid schema");
91
+ }
92
+ if (typeof handler !== "function") {
93
+ throw new Error("Handler must be a function");
94
+ }
95
+ const limit = Error.stackTraceLimit;
96
+ Error.stackTraceLimit = 2;
97
+ const traceError = new Error();
98
+ Error.stackTraceLimit = limit;
99
+ let cache = false;
100
+ const captureStackTrace = () => {
101
+ if (cache !== false) {
102
+ return cache;
103
+ }
104
+ if (traceError.stack !== void 0) {
105
+ const stack = traceError.stack.split("\n");
106
+ if (stack[2] !== void 0) {
107
+ cache = stack[2].trim();
108
+ return cache;
109
+ }
110
+ }
111
+ };
112
+ const handlerWithSpan = (...args) => {
113
+ const result = handler(...args);
114
+ if (Effect.isEffect(result)) {
115
+ return Effect.withSpan(result, `${key ?? name}`, {
116
+ captureStackTrace
117
+ });
118
+ }
119
+ return result;
120
+ };
121
+ return {
122
+ [typeId]: true,
123
+ key,
124
+ name,
125
+ description,
126
+ inputSchema,
127
+ outputSchema,
128
+ handler: handlerWithSpan
129
+ };
130
+ };
131
+ var FunctionDefinition = {
132
+ make: defineFunction,
133
+ isFunction: (value) => {
134
+ return typeof value === "object" && value !== null && Symbol.for("@dxos/functions/FunctionDefinition") in value;
135
+ },
136
+ serialize: (functionDef) => {
137
+ assertArgument(FunctionDefinition.isFunction(functionDef), "functionDef");
138
+ return serializeFunction(functionDef);
139
+ },
140
+ deserialize: (functionObj) => {
141
+ assertArgument(Obj.instanceOf(FunctionType, functionObj), "functionObj");
142
+ return deserializeFunction(functionObj);
143
+ }
144
+ };
145
+ var serializeFunction = (functionDef) => {
146
+ const fn6 = Obj.make(FunctionType, {
147
+ key: functionDef.key,
148
+ name: functionDef.name,
149
+ version: "0.1.0",
150
+ description: functionDef.description,
151
+ inputSchema: Type2.toJsonSchema(functionDef.inputSchema),
152
+ outputSchema: !functionDef.outputSchema ? void 0 : Type2.toJsonSchema(functionDef.outputSchema)
153
+ });
154
+ if (functionDef.meta?.deployedFunctionId) {
155
+ setUserFunctionIdInMetadata(Obj.getMeta(fn6), functionDef.meta.deployedFunctionId);
156
+ }
157
+ return fn6;
158
+ };
159
+ var deserializeFunction = (functionObj) => {
160
+ return {
161
+ [typeId]: true,
162
+ // TODO(dmaretskyi): Fix key.
163
+ key: functionObj.key ?? functionObj.name,
164
+ name: functionObj.name,
165
+ description: functionObj.description,
166
+ inputSchema: !functionObj.inputSchema ? Schema2.Unknown : Type2.toEffectSchema(functionObj.inputSchema),
167
+ outputSchema: !functionObj.outputSchema ? void 0 : Type2.toEffectSchema(functionObj.outputSchema),
168
+ // TODO(dmaretskyi): This should throw error.
169
+ handler: () => {
170
+ },
171
+ meta: {
172
+ deployedFunctionId: getUserFunctionIdInMetadata(Obj.getMeta(functionObj))
173
+ }
174
+ };
175
+ };
176
+
72
177
  // src/trace.ts
73
- import { Schema as Schema4 } from "effect";
74
- import { Type as Type2 } from "@dxos/echo";
178
+ import * as Schema4 from "effect/Schema";
179
+ import { Type as Type4 } from "@dxos/echo";
180
+ import { ObjectId } from "@dxos/echo/internal";
75
181
  import { Queue } from "@dxos/echo-db";
76
- import { ObjectId } from "@dxos/echo-schema";
77
182
  import { log } from "@dxos/log";
78
183
 
79
184
  // src/types.ts
80
- import { Schema as Schema3, SchemaAST } from "effect";
81
- import { Expando, OptionsAnnotationId, TypedObject, Ref as Ref2, RawObject } from "@dxos/echo-schema";
185
+ import * as Schema3 from "effect/Schema";
186
+ import * as SchemaAST from "effect/SchemaAST";
187
+ import { Obj as Obj2, QueryAST, Type as Type3 } from "@dxos/echo";
188
+ import { Expando, OptionsAnnotationId, RawObject, Ref as Ref2 } from "@dxos/echo/internal";
82
189
  import { DXN } from "@dxos/keys";
83
- var TriggerKind = /* @__PURE__ */ function(TriggerKind2) {
84
- TriggerKind2["Timer"] = "timer";
85
- TriggerKind2["Webhook"] = "webhook";
86
- TriggerKind2["Subscription"] = "subscription";
87
- TriggerKind2["Email"] = "email";
88
- TriggerKind2["Queue"] = "queue";
89
- return TriggerKind2;
90
- }({});
190
+ var TriggerKinds = [
191
+ "timer",
192
+ "webhook",
193
+ "subscription",
194
+ "email",
195
+ "queue"
196
+ ];
91
197
  var kindLiteralAnnotations = {
92
198
  title: "Kind"
93
199
  };
@@ -105,6 +211,7 @@ var EmailTriggerSchema = Schema3.Struct({
105
211
  }).pipe(Schema3.mutable);
106
212
  var QueueTriggerSchema = Schema3.Struct({
107
213
  kind: Schema3.Literal("queue").annotations(kindLiteralAnnotations),
214
+ // TODO(dmaretskyi): Change to a reference.
108
215
  queue: DXN.Schema
109
216
  }).pipe(Schema3.mutable);
110
217
  var WebhookTriggerSchema = Schema3.Struct({
@@ -120,21 +227,14 @@ var WebhookTriggerSchema = Schema3.Struct({
120
227
  title: "Port"
121
228
  }))
122
229
  }).pipe(Schema3.mutable);
123
- var QuerySchema = Schema3.Struct({
124
- type: Schema3.optional(Schema3.String.annotations({
125
- title: "Type"
126
- })),
127
- props: Schema3.optional(Schema3.Record({
128
- key: Schema3.String,
129
- value: Schema3.Any
130
- }))
131
- }).annotations({
132
- title: "Query"
133
- });
134
230
  var SubscriptionTriggerSchema = Schema3.Struct({
135
231
  kind: Schema3.Literal("subscription").annotations(kindLiteralAnnotations),
136
- // TODO(burdon): Define query DSL (from ECHO). Reconcile with Table.Query.
137
- filter: QuerySchema,
232
+ query: Schema3.Struct({
233
+ string: Schema3.optional(Schema3.String.annotations({
234
+ title: "Query"
235
+ })),
236
+ ast: QueryAST.Query
237
+ }).pipe(Schema3.mutable),
138
238
  options: Schema3.optional(Schema3.Struct({
139
239
  // Watch changes to object (not just creation).
140
240
  deep: Schema3.optional(Schema3.Boolean.annotations({
@@ -172,14 +272,25 @@ var QueueTriggerOutput = Schema3.mutable(Schema3.Struct({
172
272
  item: Schema3.Any,
173
273
  cursor: Schema3.String
174
274
  }));
175
- var SubscriptionTriggerOutput = Schema3.mutable(Schema3.Struct({
275
+ var SubscriptionTriggerOutput = Schema3.Struct({
276
+ /**
277
+ * Type of the mutation.
278
+ */
279
+ // TODO(dmaretskyi): Specify enum.
176
280
  type: Schema3.String,
177
- changedObjectId: Schema3.String
178
- }));
281
+ /**
282
+ * Reference to the object that was changed or created.
283
+ */
284
+ subject: Type3.Ref(Obj2.Any),
285
+ /**
286
+ * @deprecated
287
+ */
288
+ changedObjectId: Schema3.optional(Schema3.String)
289
+ }).pipe(Schema3.mutable);
179
290
  var TimerTriggerOutput = Schema3.mutable(Schema3.Struct({
180
291
  tick: Schema3.Number
181
292
  }));
182
- var FunctionTriggerSchema = Schema3.Struct({
293
+ var FunctionTrigger_ = Schema3.Struct({
183
294
  /**
184
295
  * Function or workflow to invoke.
185
296
  */
@@ -214,12 +325,11 @@ var FunctionTriggerSchema = Schema3.Struct({
214
325
  key: Schema3.String,
215
326
  value: Schema3.Any
216
327
  })))
217
- });
218
- var FunctionTrigger = class extends TypedObject({
328
+ }).pipe(Type3.Obj({
219
329
  typename: "dxos.org/type/FunctionTrigger",
220
330
  version: "0.2.0"
221
- })(FunctionTriggerSchema.fields) {
222
- };
331
+ }));
332
+ var FunctionTrigger = FunctionTrigger_;
223
333
  var FunctionManifestSchema = Schema3.Struct({
224
334
  functions: Schema3.optional(Schema3.mutable(Schema3.Array(RawObject(FunctionType)))),
225
335
  triggers: Schema3.optional(Schema3.mutable(Schema3.Array(RawObject(FunctionTrigger))))
@@ -231,19 +341,19 @@ var FUNCTION_TYPES = [
231
341
 
232
342
  // src/trace.ts
233
343
  var __dxlog_file = "/__w/dxos/dxos/packages/core/functions/src/trace.ts";
234
- var InvocationOutcome = /* @__PURE__ */ function(InvocationOutcome2) {
344
+ var InvocationOutcome = /* @__PURE__ */ (function(InvocationOutcome2) {
235
345
  InvocationOutcome2["SUCCESS"] = "success";
236
346
  InvocationOutcome2["FAILURE"] = "failure";
237
347
  InvocationOutcome2["PENDING"] = "pending";
238
348
  return InvocationOutcome2;
239
- }({});
240
- var InvocationTraceEventType = /* @__PURE__ */ function(InvocationTraceEventType2) {
349
+ })({});
350
+ var InvocationTraceEventType = /* @__PURE__ */ (function(InvocationTraceEventType2) {
241
351
  InvocationTraceEventType2["START"] = "start";
242
352
  InvocationTraceEventType2["END"] = "end";
243
353
  return InvocationTraceEventType2;
244
- }({});
354
+ })({});
245
355
  var TraceEventException = Schema4.Struct({
246
- timestampMs: Schema4.Number,
356
+ timestamp: Schema4.Number,
247
357
  message: Schema4.String,
248
358
  name: Schema4.String,
249
359
  stack: Schema4.optional(Schema4.String)
@@ -261,7 +371,7 @@ var InvocationTraceStartEvent = Schema4.Struct({
261
371
  /**
262
372
  * Event generation time.
263
373
  */
264
- timestampMs: Schema4.Number,
374
+ timestamp: Schema4.Number,
265
375
  /**
266
376
  * Data passed to function / workflow as an argument.
267
377
  */
@@ -270,16 +380,16 @@ var InvocationTraceStartEvent = Schema4.Struct({
270
380
  /**
271
381
  * Queue for function/workflow invocation events.
272
382
  */
273
- invocationTraceQueue: Type2.Ref(Queue),
383
+ invocationTraceQueue: Schema4.optional(Type4.Ref(Queue)),
274
384
  /**
275
385
  * DXN of the invoked function/workflow.
276
386
  */
277
- invocationTarget: Type2.Ref(Type2.Expando),
387
+ invocationTarget: Schema4.optional(Type4.Ref(Type4.Expando)),
278
388
  /**
279
389
  * Present for automatic invocations.
280
390
  */
281
- trigger: Schema4.optional(Type2.Ref(FunctionTrigger))
282
- }).pipe(Type2.Obj({
391
+ trigger: Schema4.optional(Type4.Ref(FunctionTrigger))
392
+ }).pipe(Type4.Obj({
283
393
  typename: "dxos.org/type/InvocationTraceStart",
284
394
  version: "0.1.0"
285
395
  }));
@@ -297,15 +407,15 @@ var InvocationTraceEndEvent = Schema4.Struct({
297
407
  * Event generation time.
298
408
  */
299
409
  // TODO(burdon): Remove ms suffix.
300
- timestampMs: Schema4.Number,
410
+ timestamp: Schema4.Number,
301
411
  outcome: Schema4.Enums(InvocationOutcome),
302
412
  exception: Schema4.optional(TraceEventException)
303
- }).pipe(Type2.Obj({
413
+ }).pipe(Type4.Obj({
304
414
  typename: "dxos.org/type/InvocationTraceEnd",
305
415
  version: "0.1.0"
306
416
  }));
307
417
  var TraceEventLog = Schema4.Struct({
308
- timestampMs: Schema4.Number,
418
+ timestamp: Schema4.Number,
309
419
  level: Schema4.String,
310
420
  message: Schema4.String,
311
421
  context: Schema4.optional(Schema4.Object)
@@ -315,13 +425,11 @@ var TraceEvent = Schema4.Struct({
315
425
  // TODO(burdon): Need enum/numeric result (not string).
316
426
  outcome: Schema4.String,
317
427
  truncated: Schema4.Boolean,
318
- /**
319
- * Time when the event was persisted.
320
- */
321
- ingestionTimestampMs: Schema4.Number,
428
+ /** Time when the event was persisted. */
429
+ ingestionTimestamp: Schema4.Number,
322
430
  logs: Schema4.Array(TraceEventLog),
323
431
  exceptions: Schema4.Array(TraceEventException)
324
- }).pipe(Type2.Obj({
432
+ }).pipe(Type4.Obj({
325
433
  typename: "dxos.org/type/TraceEvent",
326
434
  version: "0.1.0"
327
435
  }));
@@ -354,7 +462,7 @@ var createInvocationSpans = (items) => {
354
462
  invocationId
355
463
  }, {
356
464
  F: __dxlog_file,
357
- L: 160,
465
+ L: 158,
358
466
  S: void 0,
359
467
  C: (f, a) => f(...a)
360
468
  });
@@ -363,8 +471,8 @@ var createInvocationSpans = (items) => {
363
471
  const isInProgress = end === void 0;
364
472
  result.push({
365
473
  id: invocationId,
366
- timestampMs: start.timestampMs,
367
- durationMs: isInProgress ? now - start.timestampMs : end.timestampMs - start.timestampMs,
474
+ timestamp: start.timestamp,
475
+ duration: isInProgress ? now - start.timestamp : end.timestamp - start.timestamp,
368
476
  outcome: end?.outcome ?? "pending",
369
477
  exception: end?.exception,
370
478
  input: start.input,
@@ -376,107 +484,884 @@ var createInvocationSpans = (items) => {
376
484
  return result;
377
485
  };
378
486
 
379
- // src/url.ts
380
- var FUNCTIONS_META_KEY = "dxos.org/service/function";
381
- var FUNCTIONS_PRESET_META_KEY = "dxos.org/service/function-preset";
382
- var isSecure = (protocol) => {
383
- return protocol === "https:" || protocol === "wss:";
487
+ // src/triggers/invocation-tracer.ts
488
+ import * as Context3 from "effect/Context";
489
+ import * as Effect4 from "effect/Effect";
490
+ import * as Layer3 from "effect/Layer";
491
+ import { Obj as Obj3, Ref as Ref3 } from "@dxos/echo";
492
+ import { DXN as DXN2, ObjectId as ObjectId2 } from "@dxos/keys";
493
+
494
+ // src/services/function-invocation-service.ts
495
+ import * as Context2 from "effect/Context";
496
+ import * as Effect3 from "effect/Effect";
497
+ import * as Layer2 from "effect/Layer";
498
+ import { AiService as AiService2 } from "@dxos/ai";
499
+
500
+ // src/services/local-function-execution.ts
501
+ import * as Context from "effect/Context";
502
+ import * as Effect2 from "effect/Effect";
503
+ import * as Layer from "effect/Layer";
504
+ import * as Schema5 from "effect/Schema";
505
+ import { AiService } from "@dxos/ai";
506
+ import { todo } from "@dxos/debug";
507
+ import { log as log2 } from "@dxos/log";
508
+ function _define_property(obj, key, value) {
509
+ if (key in obj) {
510
+ Object.defineProperty(obj, key, {
511
+ value,
512
+ enumerable: true,
513
+ configurable: true,
514
+ writable: true
515
+ });
516
+ } else {
517
+ obj[key] = value;
518
+ }
519
+ return obj;
520
+ }
521
+ var __dxlog_file2 = "/__w/dxos/dxos/packages/core/functions/src/services/local-function-execution.ts";
522
+ var _Context_Tag;
523
+ var LocalFunctionExecutionService = class extends (_Context_Tag = Context.Tag("@dxos/functions/LocalFunctionExecutionService")()) {
384
524
  };
385
- var getUserFunctionUrlInMetadata = (meta) => {
386
- return meta.keys.find((key) => key.source === FUNCTIONS_META_KEY)?.id;
525
+ _define_property(LocalFunctionExecutionService, "layerLive", Layer.effect(LocalFunctionExecutionService, Effect2.gen(function* () {
526
+ const resolver = yield* FunctionImplementationResolver;
527
+ const ai = yield* AiService.AiService;
528
+ const credentials = yield* CredentialsService;
529
+ const database = yield* DatabaseService;
530
+ const queues = yield* QueueService;
531
+ const functionCallService = yield* RemoteFunctionExecutionService;
532
+ return {
533
+ // TODO(dmaretskyi): Better error types.
534
+ invokeFunction: (functionDef, input) => Effect2.gen(function* () {
535
+ const resolved = yield* resolver.resolveFunctionImplementation(functionDef).pipe(Effect2.orDie);
536
+ const output = yield* invokeFunction(resolved, input);
537
+ return output;
538
+ }).pipe(Effect2.provideService(AiService.AiService, ai), Effect2.provideService(CredentialsService, credentials), Effect2.provideService(DatabaseService, database), Effect2.provideService(QueueService, queues), Effect2.provideService(RemoteFunctionExecutionService, functionCallService))
539
+ };
540
+ })));
541
+ _define_property(LocalFunctionExecutionService, "invokeFunction", Effect2.serviceFunctionEffect(LocalFunctionExecutionService, (_) => _.invokeFunction));
542
+ var invokeFunction = (functionDef, input) => Effect2.gen(function* () {
543
+ try {
544
+ const assertInput = functionDef.inputSchema.pipe(Schema5.asserts);
545
+ assertInput(input);
546
+ } catch (e) {
547
+ throw new FunctionError({
548
+ message: "Invalid function input",
549
+ context: {
550
+ name: functionDef.name
551
+ },
552
+ cause: e
553
+ });
554
+ }
555
+ const context = {
556
+ space: void 0,
557
+ getService: () => todo(),
558
+ getSpace: async (_spaceId) => {
559
+ throw new Error("Not available. Use the database service instead.");
560
+ }
561
+ };
562
+ log2.info("invoking function", {
563
+ name: functionDef.name,
564
+ input
565
+ }, {
566
+ F: __dxlog_file2,
567
+ L: 98,
568
+ S: this,
569
+ C: (f, a) => f(...a)
570
+ });
571
+ const data = yield* Effect2.gen(function* () {
572
+ const result = functionDef.handler({
573
+ context,
574
+ data: input
575
+ });
576
+ if (Effect2.isEffect(result)) {
577
+ return yield* result.pipe(Effect2.orDie);
578
+ } else if (typeof result === "object" && result !== null && "then" in result && typeof result.then === "function") {
579
+ return yield* Effect2.promise(() => result);
580
+ } else {
581
+ return result;
582
+ }
583
+ }).pipe(Effect2.orDie, Effect2.catchAllDefect((defect) => Effect2.die(new FunctionError({
584
+ context: {
585
+ name: functionDef.name
586
+ },
587
+ cause: defect
588
+ }))));
589
+ log2.info("completed", {
590
+ function: functionDef.name,
591
+ input,
592
+ data
593
+ }, {
594
+ F: __dxlog_file2,
595
+ L: 122,
596
+ S: this,
597
+ C: (f, a) => f(...a)
598
+ });
599
+ try {
600
+ const assertOutput = functionDef.outputSchema?.pipe(Schema5.asserts);
601
+ assertOutput(data);
602
+ } catch (e) {
603
+ throw new FunctionError({
604
+ message: "Invalid function output",
605
+ context: {
606
+ name: functionDef.name
607
+ },
608
+ cause: e
609
+ });
610
+ }
611
+ return data;
612
+ }).pipe(Effect2.withSpan("invokeFunction", {
613
+ attributes: {
614
+ name: functionDef.name
615
+ }
616
+ }));
617
+ var _Context_Tag1;
618
+ var FunctionImplementationResolver = class extends (_Context_Tag1 = Context.Tag("@dxos/functions/FunctionImplementationResolver")()) {
387
619
  };
388
- var setUserFunctionUrlInMetadata = (meta, functionUrl) => {
389
- const key = meta.keys.find((key2) => key2.source === FUNCTIONS_META_KEY);
390
- if (key) {
391
- if (key.id !== functionUrl) {
392
- throw new Error("Metadata mismatch");
620
+ _define_property(FunctionImplementationResolver, "layerTest", ({ functions }) => Layer.succeed(FunctionImplementationResolver, {
621
+ resolveFunctionImplementation: (functionDef) => {
622
+ const resolved = functions.find((f) => f.key === functionDef.key);
623
+ if (!resolved) {
624
+ return Effect2.fail(new FunctionNotFoundError(functionDef.name));
393
625
  }
626
+ return Effect2.succeed(resolved);
627
+ }
628
+ }));
629
+
630
+ // src/services/function-invocation-service.ts
631
+ function _define_property2(obj, key, value) {
632
+ if (key in obj) {
633
+ Object.defineProperty(obj, key, {
634
+ value,
635
+ enumerable: true,
636
+ configurable: true,
637
+ writable: true
638
+ });
394
639
  } else {
395
- meta.keys.push({
396
- source: FUNCTIONS_META_KEY,
397
- id: functionUrl
640
+ obj[key] = value;
641
+ }
642
+ return obj;
643
+ }
644
+ var _Context_Tag2;
645
+ var FunctionInvocationService = class extends (_Context_Tag2 = Context2.Tag("@dxos/functions/FunctionInvocationService")()) {
646
+ };
647
+ _define_property2(FunctionInvocationService, "invokeFunction", Effect3.serviceFunctionEffect(FunctionInvocationService, (_) => _.invokeFunction));
648
+ _define_property2(FunctionInvocationService, "layer", Layer2.effect(FunctionInvocationService, Effect3.gen(function* () {
649
+ const localExecutioner = yield* LocalFunctionExecutionService;
650
+ const remoteExecutioner = yield* RemoteFunctionExecutionService;
651
+ return {
652
+ invokeFunction: (functionDef, input) => Effect3.gen(function* () {
653
+ if (functionDef.meta?.deployedFunctionId) {
654
+ return yield* remoteExecutioner.callFunction(functionDef.meta.deployedFunctionId, input);
655
+ }
656
+ return yield* localExecutioner.invokeFunction(functionDef, input);
657
+ })
658
+ };
659
+ })));
660
+ _define_property2(FunctionInvocationService, "layerTest", ({ functions = [] } = {}) => FunctionInvocationService.layer.pipe(Layer2.provide(LocalFunctionExecutionService.layerLive), Layer2.provide(FunctionImplementationResolver.layerTest({
661
+ functions
662
+ })), Layer2.provide(RemoteFunctionExecutionService.layerMock)));
663
+ _define_property2(FunctionInvocationService, "layerTestMocked", ({ functions }) => FunctionInvocationService.layerTest({
664
+ functions
665
+ }).pipe(Layer2.provide(AiService2.notAvailable), Layer2.provide(CredentialsService.configuredLayer([])), Layer2.provide(DatabaseService.notAvailable), Layer2.provide(QueueService.notAvailable)));
666
+
667
+ // src/triggers/invocation-tracer.ts
668
+ function _define_property3(obj, key, value) {
669
+ if (key in obj) {
670
+ Object.defineProperty(obj, key, {
671
+ value,
672
+ enumerable: true,
673
+ configurable: true,
674
+ writable: true
398
675
  });
676
+ } else {
677
+ obj[key] = value;
399
678
  }
679
+ return obj;
680
+ }
681
+ var _Context_Tag3;
682
+ var InvocationTracer = class extends (_Context_Tag3 = Context3.Tag("@dxos/functions/InvocationTracer")()) {
400
683
  };
401
- var makeFunctionUrl = (fn) => `/${fn.functionId}`;
402
- var getInvocationUrl = (functionUrl, edgeUrl, options = {}) => {
403
- const baseUrl = new URL("functions/", edgeUrl);
404
- const relativeUrl = functionUrl.replace(/^\//, "");
405
- const url = new URL(`./${relativeUrl}`, baseUrl.toString());
406
- options.spaceId && url.searchParams.set("spaceId", options.spaceId);
407
- options.subjectId && url.searchParams.set("subjectId", options.subjectId);
408
- url.protocol = isSecure(url.protocol) ? "https" : "http";
409
- return url.toString();
684
+ _define_property3(InvocationTracer, "layerLive", (opts) => Layer3.effect(InvocationTracer, Effect4.gen(function* () {
685
+ return {
686
+ traceInvocationStart: Effect4.fn("traceInvocationStart")(function* ({ payload, target }) {
687
+ const invocationId = ObjectId2.random();
688
+ const invocationTraceQueue = yield* QueueService.createQueue({
689
+ subspaceTag: "trace"
690
+ });
691
+ const now = Date.now();
692
+ const traceEvent = Obj3.make(InvocationTraceStartEvent, {
693
+ type: InvocationTraceEventType.START,
694
+ invocationId,
695
+ timestamp: now,
696
+ // TODO(dmaretskyi): Not json-stringifying this makes ECHO fail when one ECHO object becomes embedded in another ECHO object.
697
+ input: JSON.parse(JSON.stringify(payload.data ?? {})),
698
+ invocationTraceQueue: Ref3.fromDXN(invocationTraceQueue.dxn),
699
+ invocationTarget: target ? Ref3.fromDXN(target) : void 0,
700
+ trigger: payload.trigger ? Ref3.fromDXN(DXN2.fromLocalObjectId(payload.trigger.id)) : void 0
701
+ });
702
+ yield* QueueService.append(opts.invocationTraceQueue, [
703
+ traceEvent
704
+ ]);
705
+ return {
706
+ invocationId,
707
+ invocationTraceQueue
708
+ };
709
+ }),
710
+ traceInvocationEnd: Effect4.fn("traceInvocationEnd")(function* ({ trace, exception }) {
711
+ const now = Date.now();
712
+ const traceEvent = Obj3.make(InvocationTraceEndEvent, {
713
+ type: InvocationTraceEventType.END,
714
+ invocationId: trace.invocationId,
715
+ timestamp: now,
716
+ outcome: exception ? InvocationOutcome.FAILURE : InvocationOutcome.SUCCESS,
717
+ exception: exception ? {
718
+ name: exception.constructor.name,
719
+ timestamp: now,
720
+ message: exception?.message ?? "Unknown error",
721
+ stack: exception?.stack
722
+ } : void 0
723
+ });
724
+ yield* QueueService.append(opts.invocationTraceQueue, [
725
+ traceEvent
726
+ ]);
727
+ })
728
+ };
729
+ })));
730
+ _define_property3(InvocationTracer, "layerTest", Layer3.unwrapEffect(Effect4.gen(function* () {
731
+ const queue = yield* QueueService.createQueue({
732
+ subspaceTag: "trace"
733
+ });
734
+ return InvocationTracer.layerLive({
735
+ invocationTraceQueue: queue
736
+ });
737
+ })));
738
+
739
+ // src/triggers/trigger-dispatcher.ts
740
+ import * as Cause from "effect/Cause";
741
+ import * as Context5 from "effect/Context";
742
+ import * as Cron from "effect/Cron";
743
+ import * as Duration from "effect/Duration";
744
+ import * as Effect6 from "effect/Effect";
745
+ import * as Either from "effect/Either";
746
+ import * as Exit from "effect/Exit";
747
+ import * as Fiber from "effect/Fiber";
748
+ import * as Layer5 from "effect/Layer";
749
+ import * as Option2 from "effect/Option";
750
+ import * as Record3 from "effect/Record";
751
+ import * as Schedule from "effect/Schedule";
752
+ import { DXN as DXN3, Filter, Obj as Obj4, Query } from "@dxos/echo";
753
+ import { causeToError } from "@dxos/effect";
754
+ import { invariant } from "@dxos/invariant";
755
+ import { log as log3 } from "@dxos/log";
756
+ import { KEY_QUEUE_POSITION } from "@dxos/protocols";
757
+
758
+ // src/triggers/input-builder.ts
759
+ var createInvocationPayload = (trigger, event) => {
760
+ if (!trigger.input) {
761
+ return event;
762
+ }
763
+ const payload = {};
764
+ for (const [key, value] of Object.entries(trigger.input)) {
765
+ if (typeof value !== "string" || !(value.startsWith("{{") && value.endsWith("}}"))) {
766
+ payload[key] = value;
767
+ continue;
768
+ }
769
+ const propertyPath = value.slice(2, -2);
770
+ let valueSubstitution = propertyPath.startsWith("trigger.") ? trigger : propertyPath.startsWith("event.") ? event : void 0;
771
+ for (const pathSegment of propertyPath.split(".").slice(1)) {
772
+ if (valueSubstitution && typeof valueSubstitution === "object") {
773
+ valueSubstitution = valueSubstitution[pathSegment];
774
+ }
775
+ }
776
+ payload[key] = valueSubstitution;
777
+ }
778
+ return payload;
779
+ };
780
+
781
+ // src/triggers/trigger-state-store.ts
782
+ import * as KeyValueStore from "@effect/platform/KeyValueStore";
783
+ import * as Context4 from "effect/Context";
784
+ import * as Effect5 from "effect/Effect";
785
+ import * as Layer4 from "effect/Layer";
786
+ import * as Option from "effect/Option";
787
+ import * as Schema6 from "effect/Schema";
788
+ import { ObjectId as ObjectId3 } from "@dxos/keys";
789
+ function _define_property4(obj, key, value) {
790
+ if (key in obj) {
791
+ Object.defineProperty(obj, key, {
792
+ value,
793
+ enumerable: true,
794
+ configurable: true,
795
+ writable: true
796
+ });
797
+ } else {
798
+ obj[key] = value;
799
+ }
800
+ return obj;
801
+ }
802
+ var TriggerState = Schema6.Struct({
803
+ version: Schema6.Literal("1"),
804
+ triggerId: Schema6.String,
805
+ state: Schema6.optional(Schema6.Union(Schema6.TaggedStruct("subscription", {
806
+ processedVersions: Schema6.Record({
807
+ key: ObjectId3,
808
+ value: Schema6.String
809
+ })
810
+ })))
811
+ });
812
+ var _Context_Tag4;
813
+ var TriggerStateStore = class extends (_Context_Tag4 = Context4.Tag("@dxos/functions/TriggerStateStore")()) {
410
814
  };
815
+ _define_property4(TriggerStateStore, "getState", Effect5.serviceFunctionEffect(TriggerStateStore, (_) => _.getState));
816
+ _define_property4(TriggerStateStore, "saveState", Effect5.serviceFunctionEffect(TriggerStateStore, (_) => _.saveState));
817
+ _define_property4(TriggerStateStore, "layerKv", Layer4.effect(TriggerStateStore, Effect5.gen(function* () {
818
+ const kv = yield* KeyValueStore.KeyValueStore;
819
+ const schemaStore = kv.forSchema(Schema6.parseJson(TriggerState));
820
+ const store = {
821
+ getState: Effect5.fn("TriggerStateStore.getState")(function* (triggerId) {
822
+ const valueOption = yield* schemaStore.get(triggerId).pipe(Effect5.orDie);
823
+ if (Option.isNone(valueOption)) {
824
+ return yield* Effect5.fail(new TriggerStateNotFoundError());
825
+ }
826
+ return valueOption.value;
827
+ }),
828
+ saveState: Effect5.fn("TriggerStateStore.saveState")(function* (state) {
829
+ yield* schemaStore.set(state.triggerId, state).pipe(Effect5.orDie);
830
+ })
831
+ };
832
+ return store;
833
+ })));
834
+ _define_property4(TriggerStateStore, "layerMemory", TriggerStateStore.layerKv.pipe(Layer4.provide(KeyValueStore.layerMemory)));
835
+
836
+ // src/triggers/trigger-dispatcher.ts
837
+ function _define_property5(obj, key, value) {
838
+ if (key in obj) {
839
+ Object.defineProperty(obj, key, {
840
+ value,
841
+ enumerable: true,
842
+ configurable: true,
843
+ writable: true
844
+ });
845
+ } else {
846
+ obj[key] = value;
847
+ }
848
+ return obj;
849
+ }
850
+ var __dxlog_file3 = "/__w/dxos/dxos/packages/core/functions/src/triggers/trigger-dispatcher.ts";
851
+ var _Context_Tag5;
852
+ var TriggerDispatcher = class extends (_Context_Tag5 = Context5.Tag("@dxos/functions/TriggerDispatcher")()) {
853
+ };
854
+ _define_property5(TriggerDispatcher, "layer", (options) => Layer5.effect(TriggerDispatcher, Effect6.gen(function* () {
855
+ return new TriggerDispatcherImpl(options);
856
+ })));
857
+ var TriggerDispatcherImpl = class {
858
+ get running() {
859
+ return this._running;
860
+ }
861
+ constructor(options) {
862
+ _define_property5(this, "livePollInterval", void 0);
863
+ _define_property5(this, "timeControl", void 0);
864
+ _define_property5(this, "_running", false);
865
+ _define_property5(this, "_internalTime", void 0);
866
+ _define_property5(this, "_timerFiber", void 0);
867
+ _define_property5(this, "_scheduledTriggers", /* @__PURE__ */ new Map());
868
+ _define_property5(this, "start", () => Effect6.gen(this, function* () {
869
+ if (this._running) {
870
+ return;
871
+ }
872
+ this._running = true;
873
+ if (this.timeControl === "natural") {
874
+ this._timerFiber = yield* this._startNaturalTimeProcessing().pipe(Effect6.tapErrorCause((cause) => {
875
+ const error = causeToError(cause);
876
+ log3.error("trigger dispatcher error", {
877
+ error
878
+ }, {
879
+ F: __dxlog_file3,
880
+ L: 187,
881
+ S: this,
882
+ C: (f, a) => f(...a)
883
+ });
884
+ this._running = false;
885
+ return Effect6.void;
886
+ }), Effect6.forkDaemon);
887
+ } else {
888
+ return yield* Effect6.dieMessage("TriggerDispatcher started in manual time control mode");
889
+ }
890
+ log3.info("TriggerDispatcher started", {
891
+ timeControl: this.timeControl
892
+ }, {
893
+ F: __dxlog_file3,
894
+ L: 197,
895
+ S: this,
896
+ C: (f, a) => f(...a)
897
+ });
898
+ }));
899
+ _define_property5(this, "stop", () => Effect6.gen(this, function* () {
900
+ if (!this._running) {
901
+ return;
902
+ }
903
+ this._running = false;
904
+ if (this._timerFiber) {
905
+ yield* Fiber.interrupt(this._timerFiber);
906
+ this._timerFiber = void 0;
907
+ }
908
+ this._scheduledTriggers.clear();
909
+ log3.info("TriggerDispatcher stopped", void 0, {
910
+ F: __dxlog_file3,
911
+ L: 217,
912
+ S: this,
913
+ C: (f, a) => f(...a)
914
+ });
915
+ }));
916
+ _define_property5(this, "invokeTrigger", (options2) => Effect6.gen(this, function* () {
917
+ const { trigger, event } = options2;
918
+ log3.info("running trigger", {
919
+ triggerId: trigger.id,
920
+ spec: trigger.spec,
921
+ event
922
+ }, {
923
+ F: __dxlog_file3,
924
+ L: 225,
925
+ S: this,
926
+ C: (f, a) => f(...a)
927
+ });
928
+ const tracer = yield* InvocationTracer;
929
+ const trace = yield* tracer.traceInvocationStart({
930
+ target: trigger.function?.dxn,
931
+ payload: {
932
+ trigger: {
933
+ id: trigger.id,
934
+ // TODO(dmaretskyi): Is `spec` always there>
935
+ kind: trigger.spec.kind
936
+ },
937
+ data: event
938
+ }
939
+ });
940
+ const result = yield* Effect6.gen(this, function* () {
941
+ if (!trigger.enabled) {
942
+ return yield* Effect6.dieMessage("Attempting to invoke disabled trigger");
943
+ }
944
+ if (!trigger.function) {
945
+ return yield* Effect6.dieMessage("Trigger has no function reference");
946
+ }
947
+ const serialiedFunction = yield* DatabaseService.load(trigger.function).pipe(Effect6.orDie);
948
+ invariant(Obj4.instanceOf(FunctionType, serialiedFunction), void 0, {
949
+ F: __dxlog_file3,
950
+ L: 252,
951
+ S: this,
952
+ A: [
953
+ "Obj.instanceOf(FunctionType, serialiedFunction)",
954
+ ""
955
+ ]
956
+ });
957
+ const functionDef = deserializeFunction(serialiedFunction);
958
+ const inputData = this._prepareInputData(trigger, event);
959
+ return yield* FunctionInvocationService.invokeFunction(functionDef, inputData).pipe(Effect6.provide(ComputeEventLogger.layerFromTracing.pipe(Layer5.provideMerge(TracingService.layerQueue(trace.invocationTraceQueue)))));
960
+ }).pipe(Effect6.exit);
961
+ const triggerExecutionResult = {
962
+ triggerId: trigger.id,
963
+ result
964
+ };
965
+ if (Exit.isSuccess(result)) {
966
+ log3.info("trigger execution success", {
967
+ triggerId: trigger.id
968
+ }, {
969
+ F: __dxlog_file3,
970
+ L: 273,
971
+ S: this,
972
+ C: (f, a) => f(...a)
973
+ });
974
+ } else {
975
+ log3.error("trigger execution failure", {
976
+ error: causeToError(result.cause)
977
+ }, {
978
+ F: __dxlog_file3,
979
+ L: 277,
980
+ S: this,
981
+ C: (f, a) => f(...a)
982
+ });
983
+ }
984
+ yield* tracer.traceInvocationEnd({
985
+ trace,
986
+ // TODO(dmaretskyi): Might miss errors.
987
+ exception: Exit.isFailure(result) ? Cause.prettyErrors(result.cause)[0] : void 0
988
+ });
989
+ return triggerExecutionResult;
990
+ }));
991
+ _define_property5(this, "invokeScheduledTriggers", ({ kinds = [
992
+ "timer",
993
+ "queue",
994
+ "subscription"
995
+ ] } = {}) => Effect6.gen(this, function* () {
996
+ const invocations = [];
997
+ for (const kind of kinds) {
998
+ switch (kind) {
999
+ case "timer":
1000
+ {
1001
+ yield* this.refreshTriggers();
1002
+ const now = this.getCurrentTime();
1003
+ const triggersToInvoke = [];
1004
+ for (const [triggerId, scheduledTrigger] of this._scheduledTriggers.entries()) {
1005
+ if (scheduledTrigger.nextExecution <= now) {
1006
+ triggersToInvoke.push(scheduledTrigger.trigger);
1007
+ scheduledTrigger.nextExecution = Cron.next(scheduledTrigger.cron, now);
1008
+ }
1009
+ }
1010
+ invocations.push(...yield* Effect6.forEach(triggersToInvoke, (trigger) => this.invokeTrigger({
1011
+ trigger,
1012
+ event: {
1013
+ tick: now.getTime()
1014
+ }
1015
+ }), {
1016
+ concurrency: 1
1017
+ }));
1018
+ }
1019
+ break;
1020
+ case "queue": {
1021
+ const triggers = yield* this._fetchTriggers();
1022
+ for (const trigger of triggers) {
1023
+ const spec = trigger.spec;
1024
+ if (spec?.kind !== "queue") {
1025
+ continue;
1026
+ }
1027
+ const cursor = Obj4.getKeys(trigger, KEY_QUEUE_CURSOR).at(0)?.id;
1028
+ const queue = yield* QueueService.getQueue(DXN3.parse(spec.queue));
1029
+ const objects = yield* Effect6.promise(() => queue.queryObjects());
1030
+ for (const object of objects) {
1031
+ const objectPos = Obj4.getKeys(object, KEY_QUEUE_POSITION).at(0)?.id;
1032
+ if (!objectPos || cursor && parseInt(cursor) >= parseInt(objectPos)) {
1033
+ continue;
1034
+ }
1035
+ invocations.push(yield* this.invokeTrigger({
1036
+ trigger,
1037
+ event: {
1038
+ queue: spec.queue,
1039
+ item: object,
1040
+ cursor: objectPos
1041
+ }
1042
+ }));
1043
+ Obj4.deleteKeys(trigger, KEY_QUEUE_CURSOR);
1044
+ Obj4.getMeta(trigger).keys.push({
1045
+ source: KEY_QUEUE_CURSOR,
1046
+ id: objectPos
1047
+ });
1048
+ yield* DatabaseService.flush();
1049
+ break;
1050
+ }
1051
+ }
1052
+ break;
1053
+ }
1054
+ case "subscription": {
1055
+ const triggers = yield* this._fetchTriggers();
1056
+ for (const trigger of triggers) {
1057
+ const spec = Obj4.getSnapshot(trigger).spec;
1058
+ if (spec?.kind !== "subscription") {
1059
+ continue;
1060
+ }
1061
+ const { objects } = yield* DatabaseService.runQuery(Query.fromAst(spec.query.ast));
1062
+ const state = yield* TriggerStateStore.getState(trigger.id).pipe(Effect6.catchTag("TRIGGER_STATE_NOT_FOUND", () => Effect6.succeed({
1063
+ version: "1",
1064
+ triggerId: trigger.id,
1065
+ state: {
1066
+ _tag: "subscription",
1067
+ processedVersions: {}
1068
+ }
1069
+ })));
1070
+ invariant(state.state?._tag === "subscription", void 0, {
1071
+ F: __dxlog_file3,
1072
+ L: 390,
1073
+ S: this,
1074
+ A: [
1075
+ "state.state?._tag === 'subscription'",
1076
+ ""
1077
+ ]
1078
+ });
1079
+ let updated = false;
1080
+ for (const object of objects) {
1081
+ const existingVersion = Record3.get(state.state.processedVersions, object.id).pipe(Option2.map(Obj4.decodeVersion));
1082
+ const currentVersion = Obj4.version(object);
1083
+ const run = Option2.isNone(existingVersion) || Obj4.compareVersions(currentVersion, existingVersion.value) === "different";
1084
+ if (!run) {
1085
+ continue;
1086
+ }
1087
+ const { db } = yield* DatabaseService;
1088
+ invocations.push(yield* this.invokeTrigger({
1089
+ trigger,
1090
+ event: {
1091
+ // TODO(dmaretskyi): Change type not supported.
1092
+ type: "unknown",
1093
+ subject: db.ref(Obj4.getDXN(object)),
1094
+ changedObjectId: object.id
1095
+ }
1096
+ }));
1097
+ state.state.processedVersions[object.id] = Obj4.encodeVersion(currentVersion);
1098
+ updated = true;
1099
+ }
1100
+ if (updated) {
1101
+ yield* TriggerStateStore.saveState(state);
1102
+ }
1103
+ }
1104
+ break;
1105
+ }
1106
+ default: {
1107
+ return yield* Effect6.dieMessage(`Unknown trigger kind: ${kind}`);
1108
+ }
1109
+ }
1110
+ }
1111
+ return invocations;
1112
+ }));
1113
+ _define_property5(this, "advanceTime", (duration) => Effect6.gen(this, function* () {
1114
+ if (this.timeControl !== "manual") {
1115
+ return yield* Effect6.dieMessage("advanceTime can only be used in manual time control mode");
1116
+ }
1117
+ const millis = Duration.toMillis(duration);
1118
+ this._internalTime = new Date(this._internalTime.getTime() + millis);
1119
+ log3("Advanced internal time", {
1120
+ newTime: this._internalTime,
1121
+ advancedBy: Duration.format(duration)
1122
+ }, {
1123
+ F: __dxlog_file3,
1124
+ L: 447,
1125
+ S: this,
1126
+ C: (f, a) => f(...a)
1127
+ });
1128
+ }).pipe(Effect6.orDie));
1129
+ _define_property5(this, "getCurrentTime", () => {
1130
+ if (this.timeControl === "natural") {
1131
+ return /* @__PURE__ */ new Date();
1132
+ } else {
1133
+ return new Date(this._internalTime);
1134
+ }
1135
+ });
1136
+ _define_property5(this, "refreshTriggers", () => Effect6.gen(this, function* () {
1137
+ const triggers = yield* this._fetchTriggers();
1138
+ const currentTriggerIds = new Set(triggers.map((t) => t.id));
1139
+ for (const triggerId of this._scheduledTriggers.keys()) {
1140
+ if (!currentTriggerIds.has(triggerId)) {
1141
+ this._scheduledTriggers.delete(triggerId);
1142
+ }
1143
+ }
1144
+ for (const trigger of triggers) {
1145
+ if (trigger.spec?.kind === "timer" && trigger.enabled) {
1146
+ const timerSpec = trigger.spec;
1147
+ const cronEither = Cron.parse(timerSpec.cron);
1148
+ if (Either.isRight(cronEither)) {
1149
+ const cron = cronEither.right;
1150
+ const existing = this._scheduledTriggers.get(trigger.id);
1151
+ const now = this.getCurrentTime();
1152
+ const nextExecution = existing?.nextExecution ?? Cron.next(cron, now);
1153
+ log3("Updated scheduled trigger", {
1154
+ triggerId: trigger.id,
1155
+ cron: timerSpec.cron,
1156
+ nextExecution,
1157
+ now
1158
+ }, {
1159
+ F: __dxlog_file3,
1160
+ L: 487,
1161
+ S: this,
1162
+ C: (f, a) => f(...a)
1163
+ });
1164
+ this._scheduledTriggers.set(trigger.id, {
1165
+ trigger,
1166
+ cron,
1167
+ nextExecution
1168
+ });
1169
+ } else {
1170
+ log3.error("Invalid cron expression", {
1171
+ triggerId: trigger.id,
1172
+ cron: timerSpec.cron,
1173
+ error: cronEither.left.message
1174
+ }, {
1175
+ F: __dxlog_file3,
1176
+ L: 499,
1177
+ S: this,
1178
+ C: (f, a) => f(...a)
1179
+ });
1180
+ }
1181
+ }
1182
+ }
1183
+ log3("Updated scheduled triggers", {
1184
+ count: this._scheduledTriggers.size
1185
+ }, {
1186
+ F: __dxlog_file3,
1187
+ L: 508,
1188
+ S: this,
1189
+ C: (f, a) => f(...a)
1190
+ });
1191
+ }).pipe(Effect6.withSpan("TriggerDispatcher.refreshTriggers")));
1192
+ _define_property5(this, "_fetchTriggers", () => Effect6.gen(this, function* () {
1193
+ const { objects } = yield* DatabaseService.runQuery(Filter.type(FunctionTrigger));
1194
+ return objects;
1195
+ }).pipe(Effect6.withSpan("TriggerDispatcher.fetchTriggers")));
1196
+ _define_property5(this, "_startNaturalTimeProcessing", () => Effect6.gen(this, function* () {
1197
+ yield* this.invokeScheduledTriggers();
1198
+ }).pipe(Effect6.repeat(Schedule.fixed(this.livePollInterval)), Effect6.asVoid));
1199
+ _define_property5(this, "_prepareInputData", (trigger, event) => {
1200
+ return createInvocationPayload(trigger, event);
1201
+ });
1202
+ this.timeControl = options.timeControl;
1203
+ this.livePollInterval = options.livePollInterval ?? Duration.seconds(1);
1204
+ this._internalTime = options.startingTime ?? /* @__PURE__ */ new Date();
1205
+ }
1206
+ };
1207
+ var KEY_QUEUE_CURSOR = "dxos.org/key/local-trigger-dispatcher/queue-cursor";
411
1208
 
412
1209
  // src/executor/executor.ts
413
- import { Effect, Schema as Schema5 } from "effect";
1210
+ import * as Effect7 from "effect/Effect";
1211
+ import * as Schema7 from "effect/Schema";
414
1212
  import { runAndForwardErrors } from "@dxos/effect";
415
- var FunctionExecutor = class {
416
- constructor(_services) {
417
- this._services = _services;
1213
+ function _define_property6(obj, key, value) {
1214
+ if (key in obj) {
1215
+ Object.defineProperty(obj, key, {
1216
+ value,
1217
+ enumerable: true,
1218
+ configurable: true,
1219
+ writable: true
1220
+ });
1221
+ } else {
1222
+ obj[key] = value;
418
1223
  }
1224
+ return obj;
1225
+ }
1226
+ var FunctionExecutor = class {
1227
+ /**
1228
+ * Invoke function.
1229
+ */
419
1230
  // TODO(dmaretskyi): Invocation context: queue, space, etc...
420
- async invoke(fnDef, input) {
421
- const assertInput = fnDef.inputSchema.pipe(Schema5.asserts);
1231
+ async invoke(functionDef, input) {
1232
+ const assertInput = functionDef.inputSchema.pipe(Schema7.asserts);
422
1233
  assertInput(input);
423
1234
  const context = {
1235
+ space: void 0,
424
1236
  getService: this._services.getService.bind(this._services),
425
1237
  getSpace: async (_spaceId) => {
426
1238
  throw new Error("Not available. Use the database service instead.");
427
- },
428
- space: void 0,
429
- get ai() {
430
- throw new Error("Not available. Use the ai service instead.");
431
1239
  }
432
1240
  };
433
- const result = fnDef.handler({
1241
+ const result = functionDef.handler({
434
1242
  context,
435
1243
  data: input
436
1244
  });
437
1245
  let data;
438
- if (Effect.isEffect(result)) {
439
- data = await result.pipe(Effect.provide(this._services.createLayer()), runAndForwardErrors);
1246
+ if (Effect7.isEffect(result)) {
1247
+ data = await result.pipe(Effect7.provide(this._services.createLayer()), runAndForwardErrors);
440
1248
  } else {
441
1249
  data = await result;
442
1250
  }
443
- const assertOutput = fnDef.outputSchema?.pipe(Schema5.asserts);
1251
+ const assertOutput = functionDef.outputSchema?.pipe(Schema7.asserts);
444
1252
  assertOutput(data);
445
1253
  return data;
446
1254
  }
447
- };
448
-
449
- // src/errors.ts
450
- import { BaseError } from "@dxos/errors";
451
- var ServiceNotAvailableError = class extends BaseError.extend("SERVICE_NOT_AVAILABLE") {
452
- constructor(serviceName) {
453
- super(`Service not available: ${serviceName}`);
1255
+ constructor(_services) {
1256
+ _define_property6(this, "_services", void 0);
1257
+ this._services = _services;
454
1258
  }
455
1259
  };
456
- var FunctionError = class extends BaseError.extend("FUNCTION_ERROR") {
457
- };
1260
+
1261
+ // src/examples/index.ts
1262
+ var examples_exports = {};
1263
+ __export(examples_exports, {
1264
+ fib: () => fib_default,
1265
+ reply: () => reply_default,
1266
+ sleep: () => sleep_default
1267
+ });
1268
+
1269
+ // src/examples/fib.ts
1270
+ import * as Effect8 from "effect/Effect";
1271
+ import * as Schema8 from "effect/Schema";
1272
+ var fib_default = defineFunction({
1273
+ key: "example.org/function/fib",
1274
+ name: "Fibonacci",
1275
+ description: "Function that calculates a Fibonacci number",
1276
+ inputSchema: Schema8.Struct({
1277
+ iterations: Schema8.optional(Schema8.Number).annotations({
1278
+ description: "Number of iterations",
1279
+ default: 1e5
1280
+ })
1281
+ }),
1282
+ outputSchema: Schema8.Struct({
1283
+ result: Schema8.String
1284
+ }),
1285
+ handler: Effect8.fn(function* ({ data: { iterations = 1e5 } }) {
1286
+ let a = 0n;
1287
+ let b = 1n;
1288
+ for (let i = 0; i < iterations; i++) {
1289
+ a += b;
1290
+ b = a - b;
1291
+ }
1292
+ return {
1293
+ result: a.toString()
1294
+ };
1295
+ })
1296
+ });
1297
+
1298
+ // src/examples/reply.ts
1299
+ import * as Console from "effect/Console";
1300
+ import * as Effect9 from "effect/Effect";
1301
+ import * as Schema9 from "effect/Schema";
1302
+ var reply_default = defineFunction({
1303
+ key: "example.org/function/reply",
1304
+ name: "Reply",
1305
+ description: "Function that echoes the input",
1306
+ inputSchema: Schema9.Any,
1307
+ outputSchema: Schema9.Any,
1308
+ handler: Effect9.fn(function* ({ data }) {
1309
+ yield* Console.log("reply", {
1310
+ data
1311
+ });
1312
+ return data;
1313
+ })
1314
+ });
1315
+
1316
+ // src/examples/sleep.ts
1317
+ import * as Effect10 from "effect/Effect";
1318
+ import * as Schema10 from "effect/Schema";
1319
+ var sleep_default = defineFunction({
1320
+ key: "example.org/function/sleep",
1321
+ name: "Sleep",
1322
+ description: "Function that sleeps for a given amount of time",
1323
+ inputSchema: Schema10.Struct({
1324
+ duration: Schema10.optional(Schema10.Number).annotations({
1325
+ description: "Milliseconds to sleep",
1326
+ default: 1e5
1327
+ })
1328
+ }),
1329
+ outputSchema: Schema10.Void,
1330
+ handler: Effect10.fn(function* ({ data: { duration = 1e5 } }) {
1331
+ yield* Effect10.sleep(duration);
1332
+ })
1333
+ });
458
1334
  export {
1335
+ ComputeEvent,
1336
+ ComputeEventLogger,
1337
+ ComputeEventPayload,
459
1338
  ConfiguredCredentialsService,
460
1339
  ContextQueueService,
461
1340
  CredentialsService,
462
1341
  DatabaseService,
463
1342
  EmailTriggerOutput,
464
- EventLogger,
1343
+ FUNCTIONS_META_KEY,
465
1344
  FUNCTIONS_PRESET_META_KEY,
466
1345
  FUNCTION_TYPES,
467
- FunctionCallService,
1346
+ FunctionDefinition,
468
1347
  FunctionError,
469
1348
  FunctionExecutor,
1349
+ FunctionImplementationResolver,
1350
+ FunctionInvocationService,
470
1351
  FunctionManifestSchema,
1352
+ FunctionNotFoundError,
471
1353
  FunctionTrigger,
472
- FunctionTriggerSchema,
473
1354
  FunctionType,
474
1355
  InvocationOutcome,
475
1356
  InvocationTraceEndEvent,
476
1357
  InvocationTraceEventType,
477
1358
  InvocationTraceStartEvent,
1359
+ InvocationTracer,
1360
+ LocalFunctionExecutionService,
1361
+ MESSAGE_PROPERTY_TOOL_CALL_ID,
478
1362
  QueueService,
479
1363
  QueueTriggerOutput,
1364
+ RemoteFunctionExecutionService,
480
1365
  SERVICE_TAGS,
481
1366
  ScriptType,
482
1367
  ServiceContainer,
@@ -487,17 +1372,24 @@ export {
487
1372
  TraceEventException,
488
1373
  TraceEventLog,
489
1374
  TracingService,
490
- TriggerKind,
1375
+ TriggerDispatcher,
1376
+ TriggerKinds,
491
1377
  TriggerSchema,
1378
+ TriggerState,
1379
+ TriggerStateNotFoundError,
1380
+ TriggerStateStore,
492
1381
  WebhookTriggerOutput,
493
1382
  createDefectLogger,
494
1383
  createEventLogger,
495
1384
  createInvocationSpans,
496
1385
  defineFunction,
1386
+ deserializeFunction,
1387
+ examples_exports as exampleFunctions,
497
1388
  getInvocationUrl,
498
- getUserFunctionUrlInMetadata,
1389
+ getUserFunctionIdInMetadata,
499
1390
  logCustomEvent,
500
- makeFunctionUrl,
501
- setUserFunctionUrlInMetadata
1391
+ serializeFunction,
1392
+ setUserFunctionIdInMetadata,
1393
+ withAuthorization
502
1394
  };
503
1395
  //# sourceMappingURL=index.mjs.map