@dxos/functions 0.8.4-main.84f28bd → 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 (180) hide show
  1. package/dist/lib/browser/bundler/index.mjs +43 -34
  2. package/dist/lib/browser/bundler/index.mjs.map +3 -3
  3. package/dist/lib/browser/chunk-J5LGTIGS.mjs +10 -0
  4. package/dist/lib/browser/chunk-J5LGTIGS.mjs.map +7 -0
  5. package/dist/lib/browser/chunk-M6EXIREF.mjs +610 -0
  6. package/dist/lib/browser/chunk-M6EXIREF.mjs.map +7 -0
  7. package/dist/lib/browser/edge/index.mjs +22 -8
  8. package/dist/lib/browser/edge/index.mjs.map +3 -3
  9. package/dist/lib/browser/index.mjs +1106 -252
  10. package/dist/lib/browser/index.mjs.map +4 -4
  11. package/dist/lib/browser/meta.json +1 -1
  12. package/dist/lib/browser/testing/index.mjs +94 -42
  13. package/dist/lib/browser/testing/index.mjs.map +4 -4
  14. package/dist/lib/node-esm/bundler/index.mjs +42 -34
  15. package/dist/lib/node-esm/bundler/index.mjs.map +3 -3
  16. package/dist/lib/node-esm/chunk-HSLMI22Q.mjs +11 -0
  17. package/dist/lib/node-esm/chunk-HSLMI22Q.mjs.map +7 -0
  18. package/dist/lib/node-esm/chunk-P3IATZMZ.mjs +612 -0
  19. package/dist/lib/node-esm/chunk-P3IATZMZ.mjs.map +7 -0
  20. package/dist/lib/node-esm/edge/index.mjs +21 -8
  21. package/dist/lib/node-esm/edge/index.mjs.map +3 -3
  22. package/dist/lib/node-esm/index.mjs +1106 -252
  23. package/dist/lib/node-esm/index.mjs.map +4 -4
  24. package/dist/lib/node-esm/meta.json +1 -1
  25. package/dist/lib/node-esm/testing/index.mjs +94 -42
  26. package/dist/lib/node-esm/testing/index.mjs.map +4 -4
  27. package/dist/types/src/bundler/bundler.d.ts +11 -12
  28. package/dist/types/src/bundler/bundler.d.ts.map +1 -1
  29. package/dist/types/src/e2e/deploy.test.d.ts +2 -0
  30. package/dist/types/src/e2e/deploy.test.d.ts.map +1 -0
  31. package/dist/types/src/edge/functions.d.ts +4 -3
  32. package/dist/types/src/edge/functions.d.ts.map +1 -1
  33. package/dist/types/src/errors.d.ts +137 -0
  34. package/dist/types/src/errors.d.ts.map +1 -0
  35. package/dist/types/src/example/fib.d.ts +7 -0
  36. package/dist/types/src/example/fib.d.ts.map +1 -0
  37. package/dist/types/src/example/forex-effect.d.ts +3 -0
  38. package/dist/types/src/example/forex-effect.d.ts.map +1 -0
  39. package/dist/types/src/example/index.d.ts +12 -0
  40. package/dist/types/src/example/index.d.ts.map +1 -0
  41. package/dist/types/src/example/reply.d.ts +3 -0
  42. package/dist/types/src/example/reply.d.ts.map +1 -0
  43. package/dist/types/src/example/sleep.d.ts +5 -0
  44. package/dist/types/src/example/sleep.d.ts.map +1 -0
  45. package/dist/types/src/executor/executor.d.ts +7 -1
  46. package/dist/types/src/executor/executor.d.ts.map +1 -1
  47. package/dist/types/src/handler.d.ts +54 -13
  48. package/dist/types/src/handler.d.ts.map +1 -1
  49. package/dist/types/src/index.d.ts +5 -3
  50. package/dist/types/src/index.d.ts.map +1 -1
  51. package/dist/types/src/services/credentials.d.ts +21 -3
  52. package/dist/types/src/services/credentials.d.ts.map +1 -1
  53. package/dist/types/src/services/database.d.ts +58 -6
  54. package/dist/types/src/services/database.d.ts.map +1 -1
  55. package/dist/types/src/services/event-logger.d.ts +68 -30
  56. package/dist/types/src/services/event-logger.d.ts.map +1 -1
  57. package/dist/types/src/services/function-invocation-service.d.ts +28 -0
  58. package/dist/types/src/services/function-invocation-service.d.ts.map +1 -0
  59. package/dist/types/src/services/function-invocation-service.test.d.ts +2 -0
  60. package/dist/types/src/services/function-invocation-service.test.d.ts.map +1 -0
  61. package/dist/types/src/services/index.d.ts +5 -5
  62. package/dist/types/src/services/index.d.ts.map +1 -1
  63. package/dist/types/src/services/local-function-execution.d.ts +34 -0
  64. package/dist/types/src/services/local-function-execution.d.ts.map +1 -0
  65. package/dist/types/src/services/queues.d.ts +33 -4
  66. package/dist/types/src/services/queues.d.ts.map +1 -1
  67. package/dist/types/src/services/remote-function-execution-service.d.ts +22 -0
  68. package/dist/types/src/services/remote-function-execution-service.d.ts.map +1 -0
  69. package/dist/types/src/services/service-container.d.ts +29 -18
  70. package/dist/types/src/services/service-container.d.ts.map +1 -1
  71. package/dist/types/src/services/service-registry.d.ts +31 -0
  72. package/dist/types/src/services/service-registry.d.ts.map +1 -0
  73. package/dist/types/src/services/service-registry.test.d.ts +2 -0
  74. package/dist/types/src/services/service-registry.test.d.ts.map +1 -0
  75. package/dist/types/src/services/tracing.d.ts +48 -4
  76. package/dist/types/src/services/tracing.d.ts.map +1 -1
  77. package/dist/types/src/testing/index.d.ts +1 -0
  78. package/dist/types/src/testing/index.d.ts.map +1 -1
  79. package/dist/types/src/testing/layer.d.ts +18 -0
  80. package/dist/types/src/testing/layer.d.ts.map +1 -0
  81. package/dist/types/src/testing/logger.d.ts +4 -4
  82. package/dist/types/src/testing/logger.d.ts.map +1 -1
  83. package/dist/types/src/testing/persist-database.test.d.ts +2 -0
  84. package/dist/types/src/testing/persist-database.test.d.ts.map +1 -0
  85. package/dist/types/src/testing/services.d.ts +8 -20
  86. package/dist/types/src/testing/services.d.ts.map +1 -1
  87. package/dist/types/src/trace.d.ts +21 -23
  88. package/dist/types/src/trace.d.ts.map +1 -1
  89. package/dist/types/src/translations.d.ts +2 -2
  90. package/dist/types/src/translations.d.ts.map +1 -1
  91. package/dist/types/src/triggers/index.d.ts +4 -0
  92. package/dist/types/src/triggers/index.d.ts.map +1 -0
  93. package/dist/types/src/triggers/input-builder.d.ts +3 -0
  94. package/dist/types/src/triggers/input-builder.d.ts.map +1 -0
  95. package/dist/types/src/triggers/invocation-tracer.d.ts +37 -0
  96. package/dist/types/src/triggers/invocation-tracer.d.ts.map +1 -0
  97. package/dist/types/src/triggers/trigger-dispatcher.d.ts +78 -0
  98. package/dist/types/src/triggers/trigger-dispatcher.d.ts.map +1 -0
  99. package/dist/types/src/triggers/trigger-dispatcher.test.d.ts +2 -0
  100. package/dist/types/src/triggers/trigger-dispatcher.test.d.ts.map +1 -0
  101. package/dist/types/src/triggers/trigger-state-store.d.ts +28 -0
  102. package/dist/types/src/triggers/trigger-state-store.d.ts.map +1 -0
  103. package/dist/types/src/types/Function.d.ts +47 -0
  104. package/dist/types/src/types/Function.d.ts.map +1 -0
  105. package/dist/types/src/types/Script.d.ts +28 -0
  106. package/dist/types/src/types/Script.d.ts.map +1 -0
  107. package/dist/types/src/types/Trigger.d.ts +139 -0
  108. package/dist/types/src/types/Trigger.d.ts.map +1 -0
  109. package/dist/types/src/types/TriggerEvent.d.ts +44 -0
  110. package/dist/types/src/types/TriggerEvent.d.ts.map +1 -0
  111. package/dist/types/src/types/index.d.ts +5 -0
  112. package/dist/types/src/types/index.d.ts.map +1 -0
  113. package/dist/types/src/url.d.ts +11 -7
  114. package/dist/types/src/url.d.ts.map +1 -1
  115. package/dist/types/tsconfig.tsbuildinfo +1 -1
  116. package/package.json +37 -42
  117. package/src/bundler/bundler.test.ts +8 -9
  118. package/src/bundler/bundler.ts +38 -35
  119. package/src/e2e/deploy.test.ts +69 -0
  120. package/src/edge/functions.ts +9 -6
  121. package/src/errors.ts +21 -0
  122. package/src/example/fib.ts +32 -0
  123. package/src/example/forex-effect.ts +40 -0
  124. package/src/example/index.ts +13 -0
  125. package/src/example/reply.ts +21 -0
  126. package/src/example/sleep.ts +24 -0
  127. package/src/executor/executor.ts +14 -10
  128. package/src/handler.ts +139 -26
  129. package/src/index.ts +5 -5
  130. package/src/services/credentials.ts +93 -4
  131. package/src/services/database.ts +145 -20
  132. package/src/services/event-logger.ts +71 -37
  133. package/src/services/function-invocation-service.test.ts +81 -0
  134. package/src/services/function-invocation-service.ts +84 -0
  135. package/src/services/index.ts +5 -5
  136. package/src/services/local-function-execution.ts +153 -0
  137. package/src/services/queues.ts +50 -8
  138. package/src/services/remote-function-execution-service.ts +63 -0
  139. package/src/services/service-container.ts +46 -58
  140. package/src/services/service-registry.test.ts +45 -0
  141. package/src/services/service-registry.ts +63 -0
  142. package/src/services/tracing.ts +122 -6
  143. package/src/testing/index.ts +1 -0
  144. package/src/testing/layer.ts +114 -0
  145. package/src/testing/logger.ts +5 -4
  146. package/src/testing/persist-database.test.ts +87 -0
  147. package/src/testing/services.ts +12 -71
  148. package/src/trace.ts +20 -22
  149. package/src/translations.ts +2 -2
  150. package/src/triggers/index.ts +7 -0
  151. package/src/triggers/input-builder.ts +35 -0
  152. package/src/triggers/invocation-tracer.ts +101 -0
  153. package/src/triggers/trigger-dispatcher.test.ts +664 -0
  154. package/src/triggers/trigger-dispatcher.ts +521 -0
  155. package/src/triggers/trigger-state-store.ts +61 -0
  156. package/src/types/Function.ts +51 -0
  157. package/src/types/Script.ts +33 -0
  158. package/src/types/Trigger.ts +139 -0
  159. package/src/types/TriggerEvent.ts +62 -0
  160. package/src/types/index.ts +8 -0
  161. package/src/url.ts +14 -11
  162. package/dist/lib/browser/chunk-54U464M4.mjs +0 -360
  163. package/dist/lib/browser/chunk-54U464M4.mjs.map +0 -7
  164. package/dist/lib/node-esm/chunk-XDSX35BS.mjs +0 -362
  165. package/dist/lib/node-esm/chunk-XDSX35BS.mjs.map +0 -7
  166. package/dist/types/src/schema.d.ts +0 -38
  167. package/dist/types/src/schema.d.ts.map +0 -1
  168. package/dist/types/src/services/ai.d.ts +0 -12
  169. package/dist/types/src/services/ai.d.ts.map +0 -1
  170. package/dist/types/src/services/function-call-service.d.ts +0 -16
  171. package/dist/types/src/services/function-call-service.d.ts.map +0 -1
  172. package/dist/types/src/services/tool-resolver.d.ts +0 -14
  173. package/dist/types/src/services/tool-resolver.d.ts.map +0 -1
  174. package/dist/types/src/types.d.ts +0 -411
  175. package/dist/types/src/types.d.ts.map +0 -1
  176. package/src/schema.ts +0 -57
  177. package/src/services/ai.ts +0 -32
  178. package/src/services/function-call-service.ts +0 -64
  179. package/src/services/tool-resolver.ts +0 -31
  180. package/src/types.ts +0 -211
@@ -1,98 +1,173 @@
1
1
  import { createRequire } from 'node:module';const require = createRequire(import.meta.url);
2
2
  import {
3
- AiService,
3
+ ComputeEvent,
4
+ ComputeEventLogger,
5
+ ComputeEventPayload,
4
6
  ConfiguredCredentialsService,
7
+ ContextQueueService,
5
8
  CredentialsService,
6
9
  DatabaseService,
7
- EventLogger,
8
- FunctionCallService,
10
+ FUNCTIONS_META_KEY,
11
+ FUNCTIONS_PRESET_META_KEY,
12
+ FunctionError,
13
+ FunctionNotFoundError,
14
+ MESSAGE_PROPERTY_TOOL_CALL_ID,
9
15
  QueueService,
16
+ RemoteFunctionExecutionService,
10
17
  SERVICE_TAGS,
11
18
  ServiceContainer,
12
- ToolResolverService,
19
+ ServiceNotAvailableError,
13
20
  TracingService,
21
+ TriggerStateNotFoundError,
14
22
  createDefectLogger,
15
23
  createEventLogger,
16
- logCustomEvent
17
- } from "./chunk-XDSX35BS.mjs";
24
+ getInvocationUrl,
25
+ getUserFunctionIdInMetadata,
26
+ logCustomEvent,
27
+ setUserFunctionIdInMetadata,
28
+ withAuthorization
29
+ } from "./chunk-P3IATZMZ.mjs";
30
+ import {
31
+ __export
32
+ } from "./chunk-HSLMI22Q.mjs";
33
+
34
+ // src/example/fib.ts
35
+ import * as Effect2 from "effect/Effect";
36
+ import * as Schema6 from "effect/Schema";
18
37
 
19
38
  // src/handler.ts
20
- import { Schema } from "effect";
21
- var defineFunction = (params) => {
22
- if (!Schema.isSchema(params.inputSchema)) {
23
- throw new Error("Input schema must be a valid schema");
24
- }
25
- if (typeof params.handler !== "function") {
26
- throw new Error("Handler must be a function");
27
- }
28
- return {
29
- description: params.description,
30
- inputSchema: params.inputSchema,
31
- outputSchema: params.outputSchema ?? Schema.Any,
32
- handler: params.handler
33
- };
34
- };
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";
42
+ import { assertArgument } from "@dxos/invariant";
43
+
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";
35
53
 
36
- // src/schema.ts
37
- import { Schema as Schema2 } from "effect";
38
- import { Type } from "@dxos/echo";
39
- import { JsonSchemaType, LabelAnnotation, Ref } from "@dxos/echo-schema";
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";
40
63
  import { DataType } from "@dxos/schema";
41
- var ScriptType = Schema2.Struct({
42
- name: Schema2.optional(Schema2.String),
43
- description: Schema2.optional(Schema2.String),
64
+ var Script = Schema.Struct({
65
+ name: Schema.String.pipe(Schema.optional),
66
+ description: Schema.String.pipe(Schema.optional),
44
67
  // TODO(burdon): Change to hash of deployed content.
45
68
  // Whether source has changed since last deploy.
46
- changed: Schema2.optional(Schema2.Boolean),
47
- source: Ref(DataType.Text)
69
+ changed: Schema.Boolean.pipe(FormAnnotation.set(false), Schema.optional),
70
+ source: Type.Ref(DataType.Text).pipe(FormAnnotation.set(false))
48
71
  }).pipe(Type.Obj({
49
72
  typename: "dxos.org/type/Script",
50
73
  version: "0.1.0"
51
74
  }), LabelAnnotation.set([
52
75
  "name"
53
76
  ]));
54
- var FunctionType = Schema2.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({
84
+ /**
85
+ * Global registry ID.
86
+ * NOTE: The `key` property refers to the original registry entry.
87
+ */
88
+ // TODO(burdon): Create Format type for DXN-like ids, such as this and schema type.
89
+ // TODO(dmaretskyi): Consider making it part of ECHO meta.
90
+ // TODO(dmaretskyi): Make required.
91
+ key: Schema2.optional(Schema2.String).annotations({
92
+ description: "Unique registration key for the blueprint"
93
+ }),
55
94
  // TODO(burdon): Rename to id/uri?
56
95
  name: Schema2.NonEmptyString,
57
96
  version: Schema2.String,
58
97
  description: Schema2.optional(Schema2.String),
59
98
  // Reference to a source script if it exists within ECHO.
60
99
  // TODO(burdon): Don't ref ScriptType directly (core).
61
- source: Schema2.optional(Ref(ScriptType)),
100
+ source: Schema2.optional(Ref2(Script)),
62
101
  inputSchema: Schema2.optional(JsonSchemaType),
63
102
  outputSchema: Schema2.optional(JsonSchemaType),
64
103
  // Local binding to a function name.
65
104
  binding: Schema2.optional(Schema2.String)
66
- }).pipe(Type.Obj({
105
+ }).pipe(Type2.Obj({
67
106
  typename: "dxos.org/type/Function",
68
107
  version: "0.1.0"
69
- }), LabelAnnotation.set([
108
+ }), LabelAnnotation2.set([
70
109
  "name"
71
110
  ]));
111
+ var make2 = (props) => Obj2.make(Function, props);
72
112
 
73
- // src/trace.ts
74
- import { Schema as Schema4 } from "effect";
75
- import { Type as Type2 } from "@dxos/echo";
76
- import { Queue } from "@dxos/echo-db";
77
- import { ObjectId } from "@dxos/echo-schema";
78
- import { log } from "@dxos/log";
79
-
80
- // src/types.ts
81
- import { Schema as Schema3, SchemaAST } from "effect";
82
- import { Expando, OptionsAnnotationId, TypedObject, Ref as Ref2, RawObject } from "@dxos/echo-schema";
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";
83
130
  import { DXN } from "@dxos/keys";
84
- var TriggerKind = /* @__PURE__ */ function(TriggerKind2) {
85
- TriggerKind2["Timer"] = "timer";
86
- TriggerKind2["Webhook"] = "webhook";
87
- TriggerKind2["Subscription"] = "subscription";
88
- TriggerKind2["Email"] = "email";
89
- TriggerKind2["Queue"] = "queue";
90
- return TriggerKind2;
91
- }({});
131
+ var Kinds = [
132
+ "email",
133
+ "queue",
134
+ "subscription",
135
+ "timer",
136
+ "webhook"
137
+ ];
92
138
  var kindLiteralAnnotations = {
93
139
  title: "Kind"
94
140
  };
95
- var TimerTriggerSchema = Schema3.Struct({
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({
96
171
  kind: Schema3.Literal("timer").annotations(kindLiteralAnnotations),
97
172
  cron: Schema3.String.annotations({
98
173
  title: "Cron",
@@ -101,14 +176,7 @@ var TimerTriggerSchema = Schema3.Struct({
101
176
  ]
102
177
  })
103
178
  }).pipe(Schema3.mutable);
104
- var EmailTriggerSchema = Schema3.Struct({
105
- kind: Schema3.Literal("email").annotations(kindLiteralAnnotations)
106
- }).pipe(Schema3.mutable);
107
- var QueueTriggerSchema = Schema3.Struct({
108
- kind: Schema3.Literal("queue").annotations(kindLiteralAnnotations),
109
- queue: DXN.Schema
110
- }).pipe(Schema3.mutable);
111
- var WebhookTriggerSchema = Schema3.Struct({
179
+ var WebhookSpec = Schema3.Struct({
112
180
  kind: Schema3.Literal("webhook").annotations(kindLiteralAnnotations),
113
181
  method: Schema3.optional(Schema3.String.annotations({
114
182
  title: "Method",
@@ -121,71 +189,15 @@ var WebhookTriggerSchema = Schema3.Struct({
121
189
  title: "Port"
122
190
  }))
123
191
  }).pipe(Schema3.mutable);
124
- var QuerySchema = Schema3.Struct({
125
- type: Schema3.optional(Schema3.String.annotations({
126
- title: "Type"
127
- })),
128
- props: Schema3.optional(Schema3.Record({
129
- key: Schema3.String,
130
- value: Schema3.Any
131
- }))
132
- }).annotations({
133
- title: "Query"
134
- });
135
- var SubscriptionTriggerSchema = Schema3.Struct({
136
- kind: Schema3.Literal("subscription").annotations(kindLiteralAnnotations),
137
- // TODO(burdon): Define query DSL (from ECHO). Reconcile with Table.Query.
138
- filter: QuerySchema,
139
- options: Schema3.optional(Schema3.Struct({
140
- // Watch changes to object (not just creation).
141
- deep: Schema3.optional(Schema3.Boolean.annotations({
142
- title: "Nested"
143
- })),
144
- // Debounce changes (delay in ms).
145
- delay: Schema3.optional(Schema3.Number.annotations({
146
- title: "Delay"
147
- }))
148
- }).annotations({
149
- title: "Options"
150
- }))
151
- }).pipe(Schema3.mutable);
152
- var TriggerSchema = Schema3.Union(TimerTriggerSchema, WebhookTriggerSchema, SubscriptionTriggerSchema, EmailTriggerSchema, QueueTriggerSchema).annotations({
192
+ var Spec = Schema3.Union(EmailSpec, QueueSpec, SubscriptionSpec, TimerSpec, WebhookSpec).annotations({
153
193
  title: "Trigger"
154
194
  });
155
- var EmailTriggerOutput = Schema3.mutable(Schema3.Struct({
156
- from: Schema3.String,
157
- to: Schema3.String,
158
- subject: Schema3.String,
159
- created: Schema3.String,
160
- body: Schema3.String
161
- }));
162
- var WebhookTriggerOutput = Schema3.mutable(Schema3.Struct({
163
- url: Schema3.String,
164
- method: Schema3.Literal("GET", "POST"),
165
- headers: Schema3.Record({
166
- key: Schema3.String,
167
- value: Schema3.String
168
- }),
169
- bodyText: Schema3.String
170
- }));
171
- var QueueTriggerOutput = Schema3.mutable(Schema3.Struct({
172
- queue: DXN.Schema,
173
- item: Schema3.Any,
174
- cursor: Schema3.String
175
- }));
176
- var SubscriptionTriggerOutput = Schema3.mutable(Schema3.Struct({
177
- type: Schema3.String,
178
- changedObjectId: Schema3.String
179
- }));
180
- var TimerTriggerOutput = Schema3.mutable(Schema3.Struct({
181
- tick: Schema3.Number
182
- }));
183
- var FunctionTriggerSchema = Schema3.Struct({
195
+ var Trigger_ = Schema3.Struct({
184
196
  /**
185
197
  * Function or workflow to invoke.
186
198
  */
187
199
  // TODO(dmaretskyi): Can be a Ref(FunctionType) or Ref(ComputeGraphType).
188
- function: Schema3.optional(Ref2(Expando).annotations({
200
+ function: Schema3.optional(Ref3(Expando).annotations({
189
201
  title: "Function"
190
202
  })),
191
203
  /**
@@ -199,7 +211,7 @@ var FunctionTriggerSchema = Schema3.Struct({
199
211
  enabled: Schema3.optional(Schema3.Boolean.annotations({
200
212
  title: "Enabled"
201
213
  })),
202
- spec: Schema3.optional(TriggerSchema),
214
+ spec: Schema3.optional(Spec),
203
215
  /**
204
216
  * Passed as the input data to the function.
205
217
  * Must match the function's input schema.
@@ -215,46 +227,446 @@ var FunctionTriggerSchema = Schema3.Struct({
215
227
  key: Schema3.String,
216
228
  value: Schema3.Any
217
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
218
245
  });
219
- var FunctionTrigger = class extends TypedObject({
220
- typename: "dxos.org/type/FunctionTrigger",
221
- version: "0.2.0"
222
- })(FunctionTriggerSchema.fields) {
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
+ }));
287
+
288
+ // src/handler.ts
289
+ var typeId = Symbol.for("@dxos/functions/FunctionDefinition");
290
+ var defineFunction = ({ key, name, description, inputSchema, outputSchema = Schema5.Any, handler }) => {
291
+ if (!Schema5.isSchema(inputSchema)) {
292
+ throw new Error("Input schema must be a valid schema");
293
+ }
294
+ if (typeof handler !== "function") {
295
+ throw new Error("Handler must be a function");
296
+ }
297
+ const limit = Error.stackTraceLimit;
298
+ Error.stackTraceLimit = 2;
299
+ const traceError = new Error();
300
+ Error.stackTraceLimit = limit;
301
+ let cache = false;
302
+ const captureStackTrace = () => {
303
+ if (cache !== false) {
304
+ return cache;
305
+ }
306
+ if (traceError.stack !== void 0) {
307
+ const stack = traceError.stack.split("\n");
308
+ if (stack[2] !== void 0) {
309
+ cache = stack[2].trim();
310
+ return cache;
311
+ }
312
+ }
313
+ };
314
+ const handlerWithSpan = (...args) => {
315
+ const result = handler(...args);
316
+ if (Effect.isEffect(result)) {
317
+ return Effect.withSpan(result, `${key ?? name}`, {
318
+ captureStackTrace
319
+ });
320
+ }
321
+ return result;
322
+ };
323
+ return {
324
+ [typeId]: true,
325
+ key,
326
+ name,
327
+ description,
328
+ inputSchema,
329
+ outputSchema,
330
+ handler: handlerWithSpan
331
+ };
332
+ };
333
+ var FunctionDefinition = {
334
+ make: defineFunction,
335
+ isFunction: (value) => {
336
+ return typeof value === "object" && value !== null && Symbol.for("@dxos/functions/FunctionDefinition") in value;
337
+ },
338
+ serialize: (functionDef) => {
339
+ assertArgument(FunctionDefinition.isFunction(functionDef), "functionDef");
340
+ return serializeFunction(functionDef);
341
+ },
342
+ deserialize: (functionObj) => {
343
+ assertArgument(Obj5.instanceOf(Function_exports.Function, functionObj), "functionObj");
344
+ return deserializeFunction(functionObj);
345
+ }
346
+ };
347
+ var serializeFunction = (functionDef) => {
348
+ const fn6 = Function_exports.make({
349
+ key: functionDef.key,
350
+ name: functionDef.name,
351
+ version: "0.1.0",
352
+ description: functionDef.description,
353
+ inputSchema: Type5.toJsonSchema(functionDef.inputSchema),
354
+ outputSchema: !functionDef.outputSchema ? void 0 : Type5.toJsonSchema(functionDef.outputSchema)
355
+ });
356
+ if (functionDef.meta?.deployedFunctionId) {
357
+ setUserFunctionIdInMetadata(Obj5.getMeta(fn6), functionDef.meta.deployedFunctionId);
358
+ }
359
+ return fn6;
360
+ };
361
+ var deserializeFunction = (functionObj) => {
362
+ return {
363
+ [typeId]: true,
364
+ // TODO(dmaretskyi): Fix key.
365
+ key: functionObj.key ?? functionObj.name,
366
+ name: functionObj.name,
367
+ description: functionObj.description,
368
+ inputSchema: !functionObj.inputSchema ? Schema5.Unknown : Type5.toEffectSchema(functionObj.inputSchema),
369
+ outputSchema: !functionObj.outputSchema ? void 0 : Type5.toEffectSchema(functionObj.outputSchema),
370
+ // TODO(dmaretskyi): This should throw error.
371
+ handler: () => {
372
+ },
373
+ meta: {
374
+ deployedFunctionId: getUserFunctionIdInMetadata(Obj5.getMeta(functionObj))
375
+ }
376
+ };
223
377
  };
224
- var FunctionManifestSchema = Schema3.Struct({
225
- functions: Schema3.optional(Schema3.mutable(Schema3.Array(RawObject(FunctionType)))),
226
- triggers: Schema3.optional(Schema3.mutable(Schema3.Array(RawObject(FunctionTrigger))))
378
+
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
+ });
405
+
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;
421
+ })
422
+ });
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
+ })
436
+ }),
437
+ outputSchema: Schema8.Void,
438
+ handler: Effect4.fn(function* ({ data: { duration = 1e5 } }) {
439
+ yield* Effect4.sleep(duration);
440
+ })
227
441
  });
228
- var FUNCTION_TYPES = [
229
- FunctionType,
230
- FunctionTrigger
231
- ];
442
+
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
+ };
232
639
 
233
640
  // src/trace.ts
234
- var __dxlog_file = "/__w/dxos/dxos/packages/core/functions/src/trace.ts";
235
- var InvocationOutcome = /* @__PURE__ */ function(InvocationOutcome2) {
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) {
236
648
  InvocationOutcome2["SUCCESS"] = "success";
237
649
  InvocationOutcome2["FAILURE"] = "failure";
238
650
  InvocationOutcome2["PENDING"] = "pending";
239
651
  return InvocationOutcome2;
240
- }({});
241
- var InvocationTraceEventType = /* @__PURE__ */ function(InvocationTraceEventType2) {
652
+ })({});
653
+ var InvocationTraceEventType = /* @__PURE__ */ (function(InvocationTraceEventType2) {
242
654
  InvocationTraceEventType2["START"] = "start";
243
655
  InvocationTraceEventType2["END"] = "end";
244
656
  return InvocationTraceEventType2;
245
- }({});
246
- var TraceEventException = Schema4.Struct({
247
- timestampMs: Schema4.Number,
248
- message: Schema4.String,
249
- name: Schema4.String,
250
- stack: Schema4.optional(Schema4.String)
657
+ })({});
658
+ var TraceEventException = Schema11.Struct({
659
+ timestamp: Schema11.Number,
660
+ message: Schema11.String,
661
+ name: Schema11.String,
662
+ stack: Schema11.optional(Schema11.String)
251
663
  });
252
- var InvocationTraceStartEvent = Schema4.Struct({
664
+ var InvocationTraceStartEvent = Schema11.Struct({
253
665
  /**
254
666
  * Queue message id.
255
667
  */
256
668
  id: ObjectId,
257
- type: Schema4.Literal("start"),
669
+ type: Schema11.Literal("start"),
258
670
  /**
259
671
  * Invocation id, the same for invocation start and end events.
260
672
  */
@@ -262,34 +674,34 @@ var InvocationTraceStartEvent = Schema4.Struct({
262
674
  /**
263
675
  * Event generation time.
264
676
  */
265
- timestampMs: Schema4.Number,
677
+ timestamp: Schema11.Number,
266
678
  /**
267
679
  * Data passed to function / workflow as an argument.
268
680
  */
269
681
  // TODO(burdon): Input schema?
270
- input: Schema4.Object,
682
+ input: Schema11.Object,
271
683
  /**
272
684
  * Queue for function/workflow invocation events.
273
685
  */
274
- invocationTraceQueue: Type2.Ref(Queue),
686
+ invocationTraceQueue: Schema11.optional(Type6.Ref(Queue)),
275
687
  /**
276
688
  * DXN of the invoked function/workflow.
277
689
  */
278
- invocationTarget: Type2.Ref(Type2.Expando),
690
+ invocationTarget: Schema11.optional(Type6.Ref(Type6.Expando)),
279
691
  /**
280
692
  * Present for automatic invocations.
281
693
  */
282
- trigger: Schema4.optional(Type2.Ref(FunctionTrigger))
283
- }).pipe(Type2.Obj({
694
+ trigger: Schema11.optional(Type6.Ref(Trigger_exports.Trigger))
695
+ }).pipe(Type6.Obj({
284
696
  typename: "dxos.org/type/InvocationTraceStart",
285
697
  version: "0.1.0"
286
698
  }));
287
- var InvocationTraceEndEvent = Schema4.Struct({
699
+ var InvocationTraceEndEvent = Schema11.Struct({
288
700
  /**
289
701
  * Trace event id.
290
702
  */
291
703
  id: ObjectId,
292
- type: Schema4.Literal("end"),
704
+ type: Schema11.Literal("end"),
293
705
  /**
294
706
  * Invocation id, will be the same for invocation start and end.
295
707
  */
@@ -298,31 +710,29 @@ var InvocationTraceEndEvent = Schema4.Struct({
298
710
  * Event generation time.
299
711
  */
300
712
  // TODO(burdon): Remove ms suffix.
301
- timestampMs: Schema4.Number,
302
- outcome: Schema4.Enums(InvocationOutcome),
303
- exception: Schema4.optional(TraceEventException)
304
- }).pipe(Type2.Obj({
713
+ timestamp: Schema11.Number,
714
+ outcome: Schema11.Enums(InvocationOutcome),
715
+ exception: Schema11.optional(TraceEventException)
716
+ }).pipe(Type6.Obj({
305
717
  typename: "dxos.org/type/InvocationTraceEnd",
306
718
  version: "0.1.0"
307
719
  }));
308
- var TraceEventLog = Schema4.Struct({
309
- timestampMs: Schema4.Number,
310
- level: Schema4.String,
311
- message: Schema4.String,
312
- 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)
313
725
  });
314
- var TraceEvent = Schema4.Struct({
726
+ var TraceEvent = Schema11.Struct({
315
727
  id: ObjectId,
316
728
  // TODO(burdon): Need enum/numeric result (not string).
317
- outcome: Schema4.String,
318
- truncated: Schema4.Boolean,
319
- /**
320
- * Time when the event was persisted.
321
- */
322
- ingestionTimestampMs: Schema4.Number,
323
- logs: Schema4.Array(TraceEventLog),
324
- exceptions: Schema4.Array(TraceEventException)
325
- }).pipe(Type2.Obj({
729
+ outcome: Schema11.String,
730
+ truncated: Schema11.Boolean,
731
+ /** Time when the event was persisted. */
732
+ ingestionTimestamp: Schema11.Number,
733
+ logs: Schema11.Array(TraceEventLog),
734
+ exceptions: Schema11.Array(TraceEventException)
735
+ }).pipe(Type6.Obj({
326
736
  typename: "dxos.org/type/TraceEvent",
327
737
  version: "0.1.0"
328
738
  }));
@@ -351,11 +761,11 @@ var createInvocationSpans = (items) => {
351
761
  const result = [];
352
762
  for (const [invocationId, { start, end }] of eventsByInvocationId.entries()) {
353
763
  if (!start) {
354
- log.warn("found end event without matching start", {
764
+ log3.warn("found end event without matching start", {
355
765
  invocationId
356
766
  }, {
357
- F: __dxlog_file,
358
- L: 160,
767
+ F: __dxlog_file2,
768
+ L: 158,
359
769
  S: void 0,
360
770
  C: (f, a) => f(...a)
361
771
  });
@@ -364,8 +774,8 @@ var createInvocationSpans = (items) => {
364
774
  const isInProgress = end === void 0;
365
775
  result.push({
366
776
  id: invocationId,
367
- timestampMs: start.timestampMs,
368
- durationMs: isInProgress ? now - start.timestampMs : end.timestampMs - start.timestampMs,
777
+ timestamp: start.timestamp,
778
+ duration: isInProgress ? now - start.timestamp : end.timestamp - start.timestamp,
369
779
  outcome: end?.outcome ?? "pending",
370
780
  exception: end?.exception,
371
781
  input: start.input,
@@ -377,117 +787,561 @@ var createInvocationSpans = (items) => {
377
787
  return result;
378
788
  };
379
789
 
380
- // src/url.ts
381
- var FUNCTIONS_META_KEY = "dxos.org/service/function";
382
- var FUNCTIONS_PRESET_META_KEY = "dxos.org/service/function-preset";
383
- var isSecure = (protocol) => {
384
- return protocol === "https:" || protocol === "wss:";
385
- };
386
- var getUserFunctionUrlInMetadata = (meta) => {
387
- return meta.keys.find((key) => key.source === FUNCTIONS_META_KEY)?.id;
790
+ // src/triggers/invocation-tracer.ts
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"
846
+ });
847
+ return _InvocationTracer.layerLive({
848
+ invocationTraceQueue: queue
849
+ });
850
+ }));
388
851
  };
389
- var setUserFunctionUrlInMetadata = (meta, functionUrl) => {
390
- const key = meta.keys.find((key2) => key2.source === FUNCTIONS_META_KEY);
391
- if (key) {
392
- if (key.id !== functionUrl) {
393
- throw new Error("Metadata mismatch");
852
+
853
+ // src/triggers/trigger-dispatcher.ts
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";
867
+ import { causeToError } from "@dxos/effect";
868
+ import { invariant } from "@dxos/invariant";
869
+ import { log as log4 } from "@dxos/log";
870
+ import { KEY_QUEUE_POSITION } from "@dxos/protocols";
871
+
872
+ // src/triggers/input-builder.ts
873
+ var createInvocationPayload = (trigger, event) => {
874
+ if (!trigger.input) {
875
+ return event;
876
+ }
877
+ const payload = {};
878
+ for (const [key, value] of Object.entries(trigger.input)) {
879
+ if (typeof value !== "string" || !(value.startsWith("{{") && value.endsWith("}}"))) {
880
+ payload[key] = value;
881
+ continue;
394
882
  }
395
- } else {
396
- meta.keys.push({
397
- source: FUNCTIONS_META_KEY,
398
- id: functionUrl
399
- });
883
+ const propertyPath = value.slice(2, -2);
884
+ let valueSubstitution = propertyPath.startsWith("trigger.") ? trigger : propertyPath.startsWith("event.") ? event : void 0;
885
+ for (const pathSegment of propertyPath.split(".").slice(1)) {
886
+ if (valueSubstitution && typeof valueSubstitution === "object") {
887
+ valueSubstitution = valueSubstitution[pathSegment];
888
+ }
889
+ }
890
+ payload[key] = valueSubstitution;
400
891
  }
892
+ return payload;
401
893
  };
402
- var makeFunctionUrl = (fn) => `/${fn.functionId}`;
403
- var getInvocationUrl = (functionUrl, edgeUrl, options = {}) => {
404
- const baseUrl = new URL("functions/", edgeUrl);
405
- const relativeUrl = functionUrl.replace(/^\//, "");
406
- const url = new URL(`./${relativeUrl}`, baseUrl.toString());
407
- options.spaceId && url.searchParams.set("spaceId", options.spaceId);
408
- options.subjectId && url.searchParams.set("subjectId", options.subjectId);
409
- url.protocol = isSecure(url.protocol) ? "https" : "http";
410
- return url.toString();
894
+
895
+ // src/triggers/trigger-state-store.ts
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";
902
+ import { ObjectId as ObjectId3 } from "@dxos/keys";
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({
908
+ key: ObjectId3,
909
+ value: Schema12.String
910
+ })
911
+ })))
912
+ });
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));
411
934
  };
412
935
 
413
- // src/executor/executor.ts
414
- import { Effect, Schema as Schema5 } from "effect";
415
- import { runAndForwardErrors } from "@dxos/effect";
416
- var FunctionExecutor = class {
417
- constructor(_services) {
418
- this._services = _services;
936
+ // src/triggers/trigger-dispatcher.ts
937
+ var __dxlog_file3 = "/__w/dxos/dxos/packages/core/functions/src/triggers/trigger-dispatcher.ts";
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
+ }));
942
+ };
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();
419
954
  }
420
- // TODO(dmaretskyi): Invocation context: queue, space, etc...
421
- async invoke(fnDef, input) {
422
- const assertInput = fnDef.inputSchema.pipe(Schema5.asserts);
423
- assertInput(input);
424
- const context = {
425
- getService: this._services.getService.bind(this._services),
426
- getSpace: async (_spaceId) => {
427
- throw new Error("Not available. Use the database service instead.");
428
- },
429
- space: void 0,
430
- get ai() {
431
- throw new Error("Not available. Use the ai service instead.");
955
+ get running() {
956
+ return this._running;
957
+ }
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
1028
+ }
1029
+ });
1030
+ const result = yield* Effect10.gen(this, function* () {
1031
+ if (!trigger.enabled) {
1032
+ return yield* Effect10.dieMessage("Attempting to invoke disabled trigger");
1033
+ }
1034
+ if (!trigger.function) {
1035
+ return yield* Effect10.dieMessage("Trigger has no function reference");
432
1036
  }
1037
+ const serialiedFunction = yield* DatabaseService.load(trigger.function).pipe(Effect10.orDie);
1038
+ invariant(Obj7.instanceOf(Function_exports.Function, serialiedFunction), void 0, {
1039
+ F: __dxlog_file3,
1040
+ L: 243,
1041
+ S: this,
1042
+ A: [
1043
+ "Obj.instanceOf(Function.Function, serialiedFunction)",
1044
+ ""
1045
+ ]
1046
+ });
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
433
1054
  };
434
- const result = fnDef.handler({
435
- context,
436
- data: input
1055
+ if (Exit.isSuccess(result)) {
1056
+ log4.info("trigger execution success", {
1057
+ triggerId: trigger.id
1058
+ }, {
1059
+ F: __dxlog_file3,
1060
+ L: 264,
1061
+ S: this,
1062
+ C: (f, a) => f(...a)
1063
+ });
1064
+ } else {
1065
+ log4.error("trigger execution failure", {
1066
+ error: causeToError(result.cause)
1067
+ }, {
1068
+ F: __dxlog_file3,
1069
+ L: 268,
1070
+ S: this,
1071
+ C: (f, a) => f(...a)
1072
+ });
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
437
1078
  });
438
- let data;
439
- if (Effect.isEffect(result)) {
440
- data = await result.pipe(Effect.provide(this._services.createLayer()), runAndForwardErrors);
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);
1098
+ }
1099
+ }
1100
+ invocations.push(...yield* Effect10.forEach(triggersToInvoke, (trigger) => this.invokeTrigger({
1101
+ trigger,
1102
+ event: {
1103
+ tick: now.getTime()
1104
+ }
1105
+ }), {
1106
+ concurrency: 1
1107
+ }));
1108
+ }
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)) {
1123
+ continue;
1124
+ }
1125
+ invocations.push(yield* this.invokeTrigger({
1126
+ trigger,
1127
+ event: {
1128
+ queue: spec.queue,
1129
+ item: object,
1130
+ cursor: objectPos
1131
+ }
1132
+ }));
1133
+ Obj7.deleteKeys(trigger, KEY_QUEUE_CURSOR);
1134
+ Obj7.getMeta(trigger).keys.push({
1135
+ source: KEY_QUEUE_CURSOR,
1136
+ id: objectPos
1137
+ });
1138
+ yield* DatabaseService.flush();
1139
+ break;
1140
+ }
1141
+ }
1142
+ break;
1143
+ }
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",
1154
+ triggerId: trigger.id,
1155
+ state: {
1156
+ _tag: "subscription",
1157
+ processedVersions: {}
1158
+ }
1159
+ })));
1160
+ invariant(state.state?._tag === "subscription", void 0, {
1161
+ F: __dxlog_file3,
1162
+ L: 381,
1163
+ S: this,
1164
+ A: [
1165
+ "state.state?._tag === 'subscription'",
1166
+ ""
1167
+ ]
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
+ }
1193
+ }
1194
+ break;
1195
+ }
1196
+ default: {
1197
+ return yield* Effect10.dieMessage(`Unknown trigger kind: ${kind}`);
1198
+ }
1199
+ }
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)
1217
+ });
1218
+ }).pipe(Effect10.orDie);
1219
+ getCurrentTime = () => {
1220
+ if (this.timeControl === "natural") {
1221
+ return /* @__PURE__ */ new Date();
441
1222
  } else {
442
- data = await result;
1223
+ return new Date(this._internalTime);
443
1224
  }
444
- const assertOutput = fnDef.outputSchema?.pipe(Schema5.asserts);
445
- assertOutput(data);
446
- return data;
447
- }
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
+ }
1233
+ }
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)
1280
+ });
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
+ };
448
1292
  };
1293
+ var KEY_QUEUE_CURSOR = "dxos.org/key/local-trigger-dispatcher/queue-cursor";
449
1294
  export {
450
- AiService,
1295
+ ComputeEvent,
1296
+ ComputeEventLogger,
1297
+ ComputeEventPayload,
451
1298
  ConfiguredCredentialsService,
1299
+ ContextQueueService,
452
1300
  CredentialsService,
453
1301
  DatabaseService,
454
- EmailTriggerOutput,
455
- EventLogger,
1302
+ Example,
1303
+ FUNCTIONS_META_KEY,
456
1304
  FUNCTIONS_PRESET_META_KEY,
457
- FUNCTION_TYPES,
458
- FunctionCallService,
1305
+ Function_exports as Function,
1306
+ FunctionDefinition,
1307
+ FunctionError,
459
1308
  FunctionExecutor,
460
- FunctionManifestSchema,
461
- FunctionTrigger,
462
- FunctionTriggerSchema,
463
- FunctionType,
1309
+ FunctionImplementationResolver,
1310
+ FunctionInvocationService,
1311
+ FunctionNotFoundError,
464
1312
  InvocationOutcome,
465
1313
  InvocationTraceEndEvent,
466
1314
  InvocationTraceEventType,
467
1315
  InvocationTraceStartEvent,
1316
+ InvocationTracer,
1317
+ LocalFunctionExecutionService,
1318
+ MESSAGE_PROPERTY_TOOL_CALL_ID,
468
1319
  QueueService,
469
- QueueTriggerOutput,
1320
+ RemoteFunctionExecutionService,
470
1321
  SERVICE_TAGS,
471
- ScriptType,
1322
+ Script_exports as Script,
472
1323
  ServiceContainer,
473
- SubscriptionTriggerOutput,
474
- TimerTriggerOutput,
475
- ToolResolverService,
1324
+ ServiceNotAvailableError,
476
1325
  TraceEvent,
477
1326
  TraceEventException,
478
1327
  TraceEventLog,
479
1328
  TracingService,
480
- TriggerKind,
481
- TriggerSchema,
482
- WebhookTriggerOutput,
1329
+ Trigger_exports as Trigger,
1330
+ TriggerDispatcher,
1331
+ TriggerEvent_exports as TriggerEvent,
1332
+ TriggerState,
1333
+ TriggerStateNotFoundError,
1334
+ TriggerStateStore,
483
1335
  createDefectLogger,
484
1336
  createEventLogger,
485
1337
  createInvocationSpans,
486
1338
  defineFunction,
1339
+ deserializeFunction,
487
1340
  getInvocationUrl,
488
- getUserFunctionUrlInMetadata,
1341
+ getUserFunctionIdInMetadata,
489
1342
  logCustomEvent,
490
- makeFunctionUrl,
491
- setUserFunctionUrlInMetadata
1343
+ serializeFunction,
1344
+ setUserFunctionIdInMetadata,
1345
+ withAuthorization
492
1346
  };
493
1347
  //# sourceMappingURL=index.mjs.map