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