@dxos/functions 0.8.4-main.dedc0f3 → 0.8.4-main.dfabb4ec29

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