@dxos/functions 0.8.4-main.5acf9ea → 0.8.4-main.5ad4a44

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 (142) 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 +1025 -131
  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 +80 -8
  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 +1025 -131
  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 +80 -8
  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 +19 -3
  50. package/dist/types/src/services/credentials.d.ts.map +1 -1
  51. package/dist/types/src/services/database.d.ts +43 -6
  52. package/dist/types/src/services/database.d.ts.map +1 -1
  53. package/dist/types/src/services/event-logger.d.ts +4 -1
  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 +4 -3
  60. package/dist/types/src/services/index.d.ts.map +1 -1
  61. package/dist/types/src/services/local-function-execution.d.ts +27 -4
  62. package/dist/types/src/services/local-function-execution.d.ts.map +1 -1
  63. package/dist/types/src/services/queues.d.ts +21 -5
  64. package/dist/types/src/services/queues.d.ts.map +1 -1
  65. package/dist/types/src/services/remote-function-execution-service.d.ts +11 -4
  66. package/dist/types/src/services/remote-function-execution-service.d.ts.map +1 -1
  67. package/dist/types/src/services/service-container.d.ts +3 -2
  68. package/dist/types/src/services/service-container.d.ts.map +1 -1
  69. package/dist/types/src/services/service-registry.d.ts +3 -1
  70. package/dist/types/src/services/service-registry.d.ts.map +1 -1
  71. package/dist/types/src/services/tracing.d.ts +37 -4
  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 +1 -1
  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 +2 -2
  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 +41 -50
  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 +85 -5
  114. package/src/services/database.ts +119 -18
  115. package/src/services/event-logger.ts +5 -2
  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 +4 -3
  119. package/src/services/local-function-execution.ts +104 -21
  120. package/src/services/queues.ts +36 -10
  121. package/src/services/remote-function-execution-service.ts +40 -43
  122. package/src/services/service-container.ts +6 -4
  123. package/src/services/service-registry.test.ts +4 -1
  124. package/src/services/service-registry.ts +7 -3
  125. package/src/services/tracing.ts +109 -10
  126. package/src/testing/layer.ts +87 -4
  127. package/src/testing/logger.ts +2 -1
  128. package/src/testing/persist-database.test.ts +87 -0
  129. package/src/testing/services.ts +4 -3
  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-6PTFLPCO.mjs +0 -462
  140. package/dist/lib/browser/chunk-6PTFLPCO.mjs.map +0 -7
  141. package/dist/lib/node-esm/chunk-NYJ2TSXO.mjs +0 -464
  142. package/dist/lib/node-esm/chunk-NYJ2TSXO.mjs.map +0 -7
@@ -6,48 +6,47 @@ import {
6
6
  ContextQueueService,
7
7
  CredentialsService,
8
8
  DatabaseService,
9
+ FUNCTIONS_META_KEY,
10
+ FUNCTIONS_PRESET_META_KEY,
9
11
  FunctionError,
10
- LocalFunctionExecutionService,
12
+ FunctionNotFoundError,
13
+ MESSAGE_PROPERTY_TOOL_CALL_ID,
11
14
  QueueService,
12
15
  RemoteFunctionExecutionService,
13
16
  SERVICE_TAGS,
14
17
  ServiceContainer,
15
18
  ServiceNotAvailableError,
16
19
  TracingService,
20
+ TriggerStateNotFoundError,
17
21
  createDefectLogger,
18
22
  createEventLogger,
19
- logCustomEvent
20
- } from "./chunk-6PTFLPCO.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";
21
32
 
22
33
  // src/handler.ts
23
- import { Schema } from "effect";
24
- var defineFunction = ({ name, description, inputSchema, outputSchema = Schema.Any, handler }) => {
25
- if (!Schema.isSchema(inputSchema)) {
26
- throw new Error("Input schema must be a valid schema");
27
- }
28
- if (typeof handler !== "function") {
29
- throw new Error("Handler must be a function");
30
- }
31
- return {
32
- name,
33
- description,
34
- inputSchema,
35
- outputSchema,
36
- handler
37
- };
38
- };
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";
39
38
 
40
39
  // src/schema.ts
41
- import { Schema as Schema2 } from "effect";
40
+ import * as Schema from "effect/Schema";
42
41
  import { Type } from "@dxos/echo";
43
- import { JsonSchemaType, LabelAnnotation, Ref } from "@dxos/echo-schema";
42
+ import { JsonSchemaType, LabelAnnotation, Ref } from "@dxos/echo/internal";
44
43
  import { DataType } from "@dxos/schema";
45
- var ScriptType = Schema2.Struct({
46
- name: Schema2.optional(Schema2.String),
47
- description: Schema2.optional(Schema2.String),
44
+ var ScriptType = Schema.Struct({
45
+ name: Schema.optional(Schema.String),
46
+ description: Schema.optional(Schema.String),
48
47
  // TODO(burdon): Change to hash of deployed content.
49
48
  // Whether source has changed since last deploy.
50
- changed: Schema2.optional(Schema2.Boolean),
49
+ changed: Schema.optional(Schema.Boolean),
51
50
  source: Ref(DataType.Text)
52
51
  }).pipe(Type.Obj({
53
52
  typename: "dxos.org/type/Script",
@@ -55,18 +54,28 @@ var ScriptType = Schema2.Struct({
55
54
  }), LabelAnnotation.set([
56
55
  "name"
57
56
  ]));
58
- 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
+ }),
59
68
  // TODO(burdon): Rename to id/uri?
60
- name: Schema2.NonEmptyString,
61
- version: Schema2.String,
62
- description: Schema2.optional(Schema2.String),
69
+ name: Schema.NonEmptyString,
70
+ version: Schema.String,
71
+ description: Schema.optional(Schema.String),
63
72
  // Reference to a source script if it exists within ECHO.
64
73
  // TODO(burdon): Don't ref ScriptType directly (core).
65
- source: Schema2.optional(Ref(ScriptType)),
66
- inputSchema: Schema2.optional(JsonSchemaType),
67
- outputSchema: Schema2.optional(JsonSchemaType),
74
+ source: Schema.optional(Ref(ScriptType)),
75
+ inputSchema: Schema.optional(JsonSchemaType),
76
+ outputSchema: Schema.optional(JsonSchemaType),
68
77
  // Local binding to a function name.
69
- binding: Schema2.optional(Schema2.String)
78
+ binding: Schema.optional(Schema.String)
70
79
  }).pipe(Type.Obj({
71
80
  typename: "dxos.org/type/Function",
72
81
  version: "0.1.0"
@@ -74,25 +83,117 @@ var FunctionType = Schema2.Struct({
74
83
  "name"
75
84
  ]));
76
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
+
77
177
  // src/trace.ts
78
- import { Schema as Schema4 } from "effect";
79
- 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";
80
181
  import { Queue } from "@dxos/echo-db";
81
- import { ObjectId } from "@dxos/echo-schema";
82
182
  import { log } from "@dxos/log";
83
183
 
84
184
  // src/types.ts
85
- import { Schema as Schema3, SchemaAST } from "effect";
86
- 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";
87
189
  import { DXN } from "@dxos/keys";
88
- var TriggerKind = /* @__PURE__ */ function(TriggerKind2) {
89
- TriggerKind2["Timer"] = "timer";
90
- TriggerKind2["Webhook"] = "webhook";
91
- TriggerKind2["Subscription"] = "subscription";
92
- TriggerKind2["Email"] = "email";
93
- TriggerKind2["Queue"] = "queue";
94
- return TriggerKind2;
95
- }({});
190
+ var TriggerKinds = [
191
+ "timer",
192
+ "webhook",
193
+ "subscription",
194
+ "email",
195
+ "queue"
196
+ ];
96
197
  var kindLiteralAnnotations = {
97
198
  title: "Kind"
98
199
  };
@@ -110,6 +211,7 @@ var EmailTriggerSchema = Schema3.Struct({
110
211
  }).pipe(Schema3.mutable);
111
212
  var QueueTriggerSchema = Schema3.Struct({
112
213
  kind: Schema3.Literal("queue").annotations(kindLiteralAnnotations),
214
+ // TODO(dmaretskyi): Change to a reference.
113
215
  queue: DXN.Schema
114
216
  }).pipe(Schema3.mutable);
115
217
  var WebhookTriggerSchema = Schema3.Struct({
@@ -125,21 +227,14 @@ var WebhookTriggerSchema = Schema3.Struct({
125
227
  title: "Port"
126
228
  }))
127
229
  }).pipe(Schema3.mutable);
128
- var QuerySchema = Schema3.Struct({
129
- type: Schema3.optional(Schema3.String.annotations({
130
- title: "Type"
131
- })),
132
- props: Schema3.optional(Schema3.Record({
133
- key: Schema3.String,
134
- value: Schema3.Any
135
- }))
136
- }).annotations({
137
- title: "Query"
138
- });
139
230
  var SubscriptionTriggerSchema = Schema3.Struct({
140
231
  kind: Schema3.Literal("subscription").annotations(kindLiteralAnnotations),
141
- // TODO(burdon): Define query DSL (from ECHO). Reconcile with Table.Query.
142
- 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),
143
238
  options: Schema3.optional(Schema3.Struct({
144
239
  // Watch changes to object (not just creation).
145
240
  deep: Schema3.optional(Schema3.Boolean.annotations({
@@ -177,14 +272,25 @@ var QueueTriggerOutput = Schema3.mutable(Schema3.Struct({
177
272
  item: Schema3.Any,
178
273
  cursor: Schema3.String
179
274
  }));
180
- var SubscriptionTriggerOutput = Schema3.mutable(Schema3.Struct({
275
+ var SubscriptionTriggerOutput = Schema3.Struct({
276
+ /**
277
+ * Type of the mutation.
278
+ */
279
+ // TODO(dmaretskyi): Specify enum.
181
280
  type: Schema3.String,
182
- changedObjectId: Schema3.String
183
- }));
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);
184
290
  var TimerTriggerOutput = Schema3.mutable(Schema3.Struct({
185
291
  tick: Schema3.Number
186
292
  }));
187
- var FunctionTriggerSchema = Schema3.Struct({
293
+ var FunctionTrigger_ = Schema3.Struct({
188
294
  /**
189
295
  * Function or workflow to invoke.
190
296
  */
@@ -219,12 +325,11 @@ var FunctionTriggerSchema = Schema3.Struct({
219
325
  key: Schema3.String,
220
326
  value: Schema3.Any
221
327
  })))
222
- });
223
- var FunctionTrigger = class extends TypedObject({
328
+ }).pipe(Type3.Obj({
224
329
  typename: "dxos.org/type/FunctionTrigger",
225
330
  version: "0.2.0"
226
- })(FunctionTriggerSchema.fields) {
227
- };
331
+ }));
332
+ var FunctionTrigger = FunctionTrigger_;
228
333
  var FunctionManifestSchema = Schema3.Struct({
229
334
  functions: Schema3.optional(Schema3.mutable(Schema3.Array(RawObject(FunctionType)))),
230
335
  triggers: Schema3.optional(Schema3.mutable(Schema3.Array(RawObject(FunctionTrigger))))
@@ -236,19 +341,19 @@ var FUNCTION_TYPES = [
236
341
 
237
342
  // src/trace.ts
238
343
  var __dxlog_file = "/__w/dxos/dxos/packages/core/functions/src/trace.ts";
239
- var InvocationOutcome = /* @__PURE__ */ function(InvocationOutcome2) {
344
+ var InvocationOutcome = /* @__PURE__ */ (function(InvocationOutcome2) {
240
345
  InvocationOutcome2["SUCCESS"] = "success";
241
346
  InvocationOutcome2["FAILURE"] = "failure";
242
347
  InvocationOutcome2["PENDING"] = "pending";
243
348
  return InvocationOutcome2;
244
- }({});
245
- var InvocationTraceEventType = /* @__PURE__ */ function(InvocationTraceEventType2) {
349
+ })({});
350
+ var InvocationTraceEventType = /* @__PURE__ */ (function(InvocationTraceEventType2) {
246
351
  InvocationTraceEventType2["START"] = "start";
247
352
  InvocationTraceEventType2["END"] = "end";
248
353
  return InvocationTraceEventType2;
249
- }({});
354
+ })({});
250
355
  var TraceEventException = Schema4.Struct({
251
- timestampMs: Schema4.Number,
356
+ timestamp: Schema4.Number,
252
357
  message: Schema4.String,
253
358
  name: Schema4.String,
254
359
  stack: Schema4.optional(Schema4.String)
@@ -266,7 +371,7 @@ var InvocationTraceStartEvent = Schema4.Struct({
266
371
  /**
267
372
  * Event generation time.
268
373
  */
269
- timestampMs: Schema4.Number,
374
+ timestamp: Schema4.Number,
270
375
  /**
271
376
  * Data passed to function / workflow as an argument.
272
377
  */
@@ -275,16 +380,16 @@ var InvocationTraceStartEvent = Schema4.Struct({
275
380
  /**
276
381
  * Queue for function/workflow invocation events.
277
382
  */
278
- invocationTraceQueue: Type2.Ref(Queue),
383
+ invocationTraceQueue: Schema4.optional(Type4.Ref(Queue)),
279
384
  /**
280
385
  * DXN of the invoked function/workflow.
281
386
  */
282
- invocationTarget: Type2.Ref(Type2.Expando),
387
+ invocationTarget: Schema4.optional(Type4.Ref(Type4.Expando)),
283
388
  /**
284
389
  * Present for automatic invocations.
285
390
  */
286
- trigger: Schema4.optional(Type2.Ref(FunctionTrigger))
287
- }).pipe(Type2.Obj({
391
+ trigger: Schema4.optional(Type4.Ref(FunctionTrigger))
392
+ }).pipe(Type4.Obj({
288
393
  typename: "dxos.org/type/InvocationTraceStart",
289
394
  version: "0.1.0"
290
395
  }));
@@ -302,15 +407,15 @@ var InvocationTraceEndEvent = Schema4.Struct({
302
407
  * Event generation time.
303
408
  */
304
409
  // TODO(burdon): Remove ms suffix.
305
- timestampMs: Schema4.Number,
410
+ timestamp: Schema4.Number,
306
411
  outcome: Schema4.Enums(InvocationOutcome),
307
412
  exception: Schema4.optional(TraceEventException)
308
- }).pipe(Type2.Obj({
413
+ }).pipe(Type4.Obj({
309
414
  typename: "dxos.org/type/InvocationTraceEnd",
310
415
  version: "0.1.0"
311
416
  }));
312
417
  var TraceEventLog = Schema4.Struct({
313
- timestampMs: Schema4.Number,
418
+ timestamp: Schema4.Number,
314
419
  level: Schema4.String,
315
420
  message: Schema4.String,
316
421
  context: Schema4.optional(Schema4.Object)
@@ -320,13 +425,11 @@ var TraceEvent = Schema4.Struct({
320
425
  // TODO(burdon): Need enum/numeric result (not string).
321
426
  outcome: Schema4.String,
322
427
  truncated: Schema4.Boolean,
323
- /**
324
- * Time when the event was persisted.
325
- */
326
- ingestionTimestampMs: Schema4.Number,
428
+ /** Time when the event was persisted. */
429
+ ingestionTimestamp: Schema4.Number,
327
430
  logs: Schema4.Array(TraceEventLog),
328
431
  exceptions: Schema4.Array(TraceEventException)
329
- }).pipe(Type2.Obj({
432
+ }).pipe(Type4.Obj({
330
433
  typename: "dxos.org/type/TraceEvent",
331
434
  version: "0.1.0"
332
435
  }));
@@ -359,7 +462,7 @@ var createInvocationSpans = (items) => {
359
462
  invocationId
360
463
  }, {
361
464
  F: __dxlog_file,
362
- L: 160,
465
+ L: 158,
363
466
  S: void 0,
364
467
  C: (f, a) => f(...a)
365
468
  });
@@ -368,8 +471,8 @@ var createInvocationSpans = (items) => {
368
471
  const isInProgress = end === void 0;
369
472
  result.push({
370
473
  id: invocationId,
371
- timestampMs: start.timestampMs,
372
- durationMs: isInProgress ? now - start.timestampMs : end.timestampMs - start.timestampMs,
474
+ timestamp: start.timestamp,
475
+ duration: isInProgress ? now - start.timestamp : end.timestamp - start.timestamp,
373
476
  outcome: end?.outcome ?? "pending",
374
477
  exception: end?.exception,
375
478
  input: start.input,
@@ -381,75 +484,853 @@ var createInvocationSpans = (items) => {
381
484
  return result;
382
485
  };
383
486
 
384
- // src/url.ts
385
- var FUNCTIONS_META_KEY = "dxos.org/service/function";
386
- var FUNCTIONS_PRESET_META_KEY = "dxos.org/service/function-preset";
387
- var isSecure = (protocol) => {
388
- 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")()) {
524
+ };
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")()) {
619
+ };
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));
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
+ });
639
+ } else {
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")()) {
389
646
  };
390
- var getUserFunctionUrlInMetadata = (meta) => {
391
- return meta.keys.find((key) => key.source === FUNCTIONS_META_KEY)?.id;
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
675
+ });
676
+ } else {
677
+ obj[key] = value;
678
+ }
679
+ return obj;
680
+ }
681
+ var _Context_Tag3;
682
+ var InvocationTracer = class extends (_Context_Tag3 = Context3.Tag("@dxos/functions/InvocationTracer")()) {
392
683
  };
393
- var setUserFunctionUrlInMetadata = (meta, functionUrl) => {
394
- const key = meta.keys.find((key2) => key2.source === FUNCTIONS_META_KEY);
395
- if (key) {
396
- if (key.id !== functionUrl) {
397
- throw new Error("Metadata mismatch");
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
+ }
398
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
+ });
399
797
  } else {
400
- meta.keys.push({
401
- source: FUNCTIONS_META_KEY,
402
- id: functionUrl
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")()) {
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
403
844
  });
845
+ } else {
846
+ obj[key] = value;
404
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")()) {
405
853
  };
406
- var makeFunctionUrl = (fn) => `/${fn.functionId}`;
407
- var getInvocationUrl = (functionUrl, edgeUrl, options = {}) => {
408
- const baseUrl = new URL("functions/", edgeUrl);
409
- const relativeUrl = functionUrl.replace(/^\//, "");
410
- const url = new URL(`./${relativeUrl}`, baseUrl.toString());
411
- options.spaceId && url.searchParams.set("spaceId", options.spaceId);
412
- options.subjectId && url.searchParams.set("subjectId", options.subjectId);
413
- url.protocol = isSecure(url.protocol) ? "https" : "http";
414
- return url.toString();
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
+ }
415
1206
  };
1207
+ var KEY_QUEUE_CURSOR = "dxos.org/key/local-trigger-dispatcher/queue-cursor";
416
1208
 
417
1209
  // src/executor/executor.ts
418
- import { Effect, Schema as Schema5 } from "effect";
1210
+ import * as Effect7 from "effect/Effect";
1211
+ import * as Schema7 from "effect/Schema";
419
1212
  import { runAndForwardErrors } from "@dxos/effect";
420
- var FunctionExecutor = class {
421
- constructor(_services) {
422
- 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;
423
1223
  }
1224
+ return obj;
1225
+ }
1226
+ var FunctionExecutor = class {
1227
+ /**
1228
+ * Invoke function.
1229
+ */
424
1230
  // TODO(dmaretskyi): Invocation context: queue, space, etc...
425
- async invoke(fnDef, input) {
426
- const assertInput = fnDef.inputSchema.pipe(Schema5.asserts);
1231
+ async invoke(functionDef, input) {
1232
+ const assertInput = functionDef.inputSchema.pipe(Schema7.asserts);
427
1233
  assertInput(input);
428
1234
  const context = {
1235
+ space: void 0,
429
1236
  getService: this._services.getService.bind(this._services),
430
1237
  getSpace: async (_spaceId) => {
431
1238
  throw new Error("Not available. Use the database service instead.");
432
- },
433
- space: void 0,
434
- get ai() {
435
- throw new Error("Not available. Use the ai service instead.");
436
1239
  }
437
1240
  };
438
- const result = fnDef.handler({
1241
+ const result = functionDef.handler({
439
1242
  context,
440
1243
  data: input
441
1244
  });
442
1245
  let data;
443
- if (Effect.isEffect(result)) {
444
- 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);
445
1248
  } else {
446
1249
  data = await result;
447
1250
  }
448
- const assertOutput = fnDef.outputSchema?.pipe(Schema5.asserts);
1251
+ const assertOutput = functionDef.outputSchema?.pipe(Schema7.asserts);
449
1252
  assertOutput(data);
450
1253
  return data;
451
1254
  }
1255
+ constructor(_services) {
1256
+ _define_property6(this, "_services", void 0);
1257
+ this._services = _services;
1258
+ }
452
1259
  };
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
+ });
453
1334
  export {
454
1335
  ComputeEvent,
455
1336
  ComputeEventLogger,
@@ -459,19 +1340,25 @@ export {
459
1340
  CredentialsService,
460
1341
  DatabaseService,
461
1342
  EmailTriggerOutput,
1343
+ FUNCTIONS_META_KEY,
462
1344
  FUNCTIONS_PRESET_META_KEY,
463
1345
  FUNCTION_TYPES,
1346
+ FunctionDefinition,
464
1347
  FunctionError,
465
1348
  FunctionExecutor,
1349
+ FunctionImplementationResolver,
1350
+ FunctionInvocationService,
466
1351
  FunctionManifestSchema,
1352
+ FunctionNotFoundError,
467
1353
  FunctionTrigger,
468
- FunctionTriggerSchema,
469
1354
  FunctionType,
470
1355
  InvocationOutcome,
471
1356
  InvocationTraceEndEvent,
472
1357
  InvocationTraceEventType,
473
1358
  InvocationTraceStartEvent,
1359
+ InvocationTracer,
474
1360
  LocalFunctionExecutionService,
1361
+ MESSAGE_PROPERTY_TOOL_CALL_ID,
475
1362
  QueueService,
476
1363
  QueueTriggerOutput,
477
1364
  RemoteFunctionExecutionService,
@@ -485,17 +1372,24 @@ export {
485
1372
  TraceEventException,
486
1373
  TraceEventLog,
487
1374
  TracingService,
488
- TriggerKind,
1375
+ TriggerDispatcher,
1376
+ TriggerKinds,
489
1377
  TriggerSchema,
1378
+ TriggerState,
1379
+ TriggerStateNotFoundError,
1380
+ TriggerStateStore,
490
1381
  WebhookTriggerOutput,
491
1382
  createDefectLogger,
492
1383
  createEventLogger,
493
1384
  createInvocationSpans,
494
1385
  defineFunction,
1386
+ deserializeFunction,
1387
+ examples_exports as exampleFunctions,
495
1388
  getInvocationUrl,
496
- getUserFunctionUrlInMetadata,
1389
+ getUserFunctionIdInMetadata,
497
1390
  logCustomEvent,
498
- makeFunctionUrl,
499
- setUserFunctionUrlInMetadata
1391
+ serializeFunction,
1392
+ setUserFunctionIdInMetadata,
1393
+ withAuthorization
500
1394
  };
501
1395
  //# sourceMappingURL=index.mjs.map