@dxos/functions 0.8.3 → 0.8.4-main.1f223c7

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