@dxos/functions 0.8.4-main.a4bbb77 → 0.8.4-main.ae835ea

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