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