@dxos/functions 0.8.4-main.c1de068 → 0.8.4-main.e098934

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