@dxos/functions 0.8.4-main.c4373fc → 0.8.4-main.c85a9c8dae

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