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