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

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-ANP3DFCO.mjs +623 -0
  4. package/dist/lib/browser/chunk-ANP3DFCO.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 +892 -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 +77 -39
  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-MPKVY7ZR.mjs +625 -0
  19. package/dist/lib/node-esm/chunk-MPKVY7ZR.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 +892 -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 +77 -39
  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 +77 -8
  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 +75 -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 +6 -17
  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 +8 -0
  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 +118 -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 +10 -63
  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,65 @@
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-MPKVY7ZR.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") {
33
+ constructor(serviceName) {
34
+ super(`Service not available: ${serviceName}`);
23
35
  }
24
- if (typeof handler !== "function") {
25
- throw new Error("Handler must be a function");
36
+ };
37
+ var FunctionNotFoundError = class extends BaseError.extend("FUNCTION_NOT_FOUND") {
38
+ constructor(functionKey) {
39
+ super(`Function not found: ${functionKey}`);
26
40
  }
27
- return {
28
- name,
29
- description,
30
- inputSchema,
31
- outputSchema,
32
- handler
33
- };
41
+ };
42
+ var FunctionError = class extends BaseError.extend("FUNCTION_ERROR") {
43
+ };
44
+ var TriggerStateNotFoundError = class extends BaseError.extend("TRIGGER_STATE_NOT_FOUND") {
34
45
  };
35
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
+
36
52
  // src/schema.ts
37
- import { Schema as Schema2 } from "effect";
53
+ import { Schema } from "effect";
38
54
  import { Type } from "@dxos/echo";
39
55
  import { JsonSchemaType, LabelAnnotation, Ref } from "@dxos/echo-schema";
40
56
  import { DataType } from "@dxos/schema";
41
- var ScriptType = Schema2.Struct({
42
- name: Schema2.optional(Schema2.String),
43
- description: Schema2.optional(Schema2.String),
57
+ var ScriptType = Schema.Struct({
58
+ name: Schema.optional(Schema.String),
59
+ description: Schema.optional(Schema.String),
44
60
  // TODO(burdon): Change to hash of deployed content.
45
61
  // Whether source has changed since last deploy.
46
- changed: Schema2.optional(Schema2.Boolean),
62
+ changed: Schema.optional(Schema.Boolean),
47
63
  source: Ref(DataType.Text)
48
64
  }).pipe(Type.Obj({
49
65
  typename: "dxos.org/type/Script",
@@ -51,18 +67,28 @@ var ScriptType = Schema2.Struct({
51
67
  }), LabelAnnotation.set([
52
68
  "name"
53
69
  ]));
54
- var FunctionType = Schema2.Struct({
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
+ }),
55
81
  // TODO(burdon): Rename to id/uri?
56
- name: Schema2.NonEmptyString,
57
- version: Schema2.String,
58
- description: Schema2.optional(Schema2.String),
82
+ name: Schema.NonEmptyString,
83
+ version: Schema.String,
84
+ description: Schema.optional(Schema.String),
59
85
  // Reference to a source script if it exists within ECHO.
60
86
  // TODO(burdon): Don't ref ScriptType directly (core).
61
- source: Schema2.optional(Ref(ScriptType)),
62
- inputSchema: Schema2.optional(JsonSchemaType),
63
- outputSchema: Schema2.optional(JsonSchemaType),
87
+ source: Schema.optional(Ref(ScriptType)),
88
+ inputSchema: Schema.optional(JsonSchemaType),
89
+ outputSchema: Schema.optional(JsonSchemaType),
64
90
  // Local binding to a function name.
65
- binding: Schema2.optional(Schema2.String)
91
+ binding: Schema.optional(Schema.String)
66
92
  }).pipe(Type.Obj({
67
93
  typename: "dxos.org/type/Function",
68
94
  version: "0.1.0"
@@ -70,25 +96,106 @@ var FunctionType = Schema2.Struct({
70
96
  "name"
71
97
  ]));
72
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
+
73
180
  // src/trace.ts
74
181
  import { Schema as Schema4 } from "effect";
75
- import { Type as Type2 } from "@dxos/echo";
182
+ import { Type as Type4 } from "@dxos/echo";
76
183
  import { Queue } from "@dxos/echo-db";
77
184
  import { ObjectId } from "@dxos/echo-schema";
78
185
  import { log } from "@dxos/log";
79
186
 
80
187
  // src/types.ts
81
188
  import { Schema as Schema3, SchemaAST } from "effect";
82
- import { Expando, OptionsAnnotationId, TypedObject, Ref as Ref2, RawObject } from "@dxos/echo-schema";
189
+ import { QueryAST, Type as Type3 } from "@dxos/echo";
190
+ import { Expando, OptionsAnnotationId, RawObject, Ref as Ref2 } from "@dxos/echo-schema";
83
191
  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
- }({});
192
+ var TriggerKinds = [
193
+ "timer",
194
+ "webhook",
195
+ "subscription",
196
+ "email",
197
+ "queue"
198
+ ];
92
199
  var kindLiteralAnnotations = {
93
200
  title: "Kind"
94
201
  };
@@ -106,6 +213,7 @@ var EmailTriggerSchema = Schema3.Struct({
106
213
  }).pipe(Schema3.mutable);
107
214
  var QueueTriggerSchema = Schema3.Struct({
108
215
  kind: Schema3.Literal("queue").annotations(kindLiteralAnnotations),
216
+ // TODO(dmaretskyi): Change to a reference.
109
217
  queue: DXN.Schema
110
218
  }).pipe(Schema3.mutable);
111
219
  var WebhookTriggerSchema = Schema3.Struct({
@@ -121,21 +229,11 @@ var WebhookTriggerSchema = Schema3.Struct({
121
229
  title: "Port"
122
230
  }))
123
231
  }).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
232
  var SubscriptionTriggerSchema = Schema3.Struct({
136
233
  kind: Schema3.Literal("subscription").annotations(kindLiteralAnnotations),
137
- // TODO(burdon): Define query DSL (from ECHO). Reconcile with Table.Query.
138
- filter: QuerySchema,
234
+ query: QueryAST.Query.annotations({
235
+ title: "Query"
236
+ }),
139
237
  options: Schema3.optional(Schema3.Struct({
140
238
  // Watch changes to object (not just creation).
141
239
  deep: Schema3.optional(Schema3.Boolean.annotations({
@@ -180,7 +278,7 @@ var SubscriptionTriggerOutput = Schema3.mutable(Schema3.Struct({
180
278
  var TimerTriggerOutput = Schema3.mutable(Schema3.Struct({
181
279
  tick: Schema3.Number
182
280
  }));
183
- var FunctionTriggerSchema = Schema3.Struct({
281
+ var FunctionTrigger_ = Schema3.Struct({
184
282
  /**
185
283
  * Function or workflow to invoke.
186
284
  */
@@ -215,12 +313,11 @@ var FunctionTriggerSchema = Schema3.Struct({
215
313
  key: Schema3.String,
216
314
  value: Schema3.Any
217
315
  })))
218
- });
219
- var FunctionTrigger = class extends TypedObject({
316
+ }).pipe(Type3.Obj({
220
317
  typename: "dxos.org/type/FunctionTrigger",
221
318
  version: "0.2.0"
222
- })(FunctionTriggerSchema.fields) {
223
- };
319
+ }));
320
+ var FunctionTrigger = FunctionTrigger_;
224
321
  var FunctionManifestSchema = Schema3.Struct({
225
322
  functions: Schema3.optional(Schema3.mutable(Schema3.Array(RawObject(FunctionType)))),
226
323
  triggers: Schema3.optional(Schema3.mutable(Schema3.Array(RawObject(FunctionTrigger))))
@@ -244,7 +341,7 @@ var InvocationTraceEventType = /* @__PURE__ */ function(InvocationTraceEventType
244
341
  return InvocationTraceEventType2;
245
342
  }({});
246
343
  var TraceEventException = Schema4.Struct({
247
- timestampMs: Schema4.Number,
344
+ timestamp: Schema4.Number,
248
345
  message: Schema4.String,
249
346
  name: Schema4.String,
250
347
  stack: Schema4.optional(Schema4.String)
@@ -262,7 +359,7 @@ var InvocationTraceStartEvent = Schema4.Struct({
262
359
  /**
263
360
  * Event generation time.
264
361
  */
265
- timestampMs: Schema4.Number,
362
+ timestamp: Schema4.Number,
266
363
  /**
267
364
  * Data passed to function / workflow as an argument.
268
365
  */
@@ -271,16 +368,16 @@ var InvocationTraceStartEvent = Schema4.Struct({
271
368
  /**
272
369
  * Queue for function/workflow invocation events.
273
370
  */
274
- invocationTraceQueue: Type2.Ref(Queue),
371
+ invocationTraceQueue: Schema4.optional(Type4.Ref(Queue)),
275
372
  /**
276
373
  * DXN of the invoked function/workflow.
277
374
  */
278
- invocationTarget: Type2.Ref(Type2.Expando),
375
+ invocationTarget: Schema4.optional(Type4.Ref(Type4.Expando)),
279
376
  /**
280
377
  * Present for automatic invocations.
281
378
  */
282
- trigger: Schema4.optional(Type2.Ref(FunctionTrigger))
283
- }).pipe(Type2.Obj({
379
+ trigger: Schema4.optional(Type4.Ref(FunctionTrigger))
380
+ }).pipe(Type4.Obj({
284
381
  typename: "dxos.org/type/InvocationTraceStart",
285
382
  version: "0.1.0"
286
383
  }));
@@ -298,15 +395,15 @@ var InvocationTraceEndEvent = Schema4.Struct({
298
395
  * Event generation time.
299
396
  */
300
397
  // TODO(burdon): Remove ms suffix.
301
- timestampMs: Schema4.Number,
398
+ timestamp: Schema4.Number,
302
399
  outcome: Schema4.Enums(InvocationOutcome),
303
400
  exception: Schema4.optional(TraceEventException)
304
- }).pipe(Type2.Obj({
401
+ }).pipe(Type4.Obj({
305
402
  typename: "dxos.org/type/InvocationTraceEnd",
306
403
  version: "0.1.0"
307
404
  }));
308
405
  var TraceEventLog = Schema4.Struct({
309
- timestampMs: Schema4.Number,
406
+ timestamp: Schema4.Number,
310
407
  level: Schema4.String,
311
408
  message: Schema4.String,
312
409
  context: Schema4.optional(Schema4.Object)
@@ -316,13 +413,11 @@ var TraceEvent = Schema4.Struct({
316
413
  // TODO(burdon): Need enum/numeric result (not string).
317
414
  outcome: Schema4.String,
318
415
  truncated: Schema4.Boolean,
319
- /**
320
- * Time when the event was persisted.
321
- */
322
- ingestionTimestampMs: Schema4.Number,
416
+ /** Time when the event was persisted. */
417
+ ingestionTimestamp: Schema4.Number,
323
418
  logs: Schema4.Array(TraceEventLog),
324
419
  exceptions: Schema4.Array(TraceEventException)
325
- }).pipe(Type2.Obj({
420
+ }).pipe(Type4.Obj({
326
421
  typename: "dxos.org/type/TraceEvent",
327
422
  version: "0.1.0"
328
423
  }));
@@ -355,7 +450,7 @@ var createInvocationSpans = (items) => {
355
450
  invocationId
356
451
  }, {
357
452
  F: __dxlog_file,
358
- L: 160,
453
+ L: 158,
359
454
  S: void 0,
360
455
  C: (f, a) => f(...a)
361
456
  });
@@ -364,8 +459,8 @@ var createInvocationSpans = (items) => {
364
459
  const isInProgress = end === void 0;
365
460
  result.push({
366
461
  id: invocationId,
367
- timestampMs: start.timestampMs,
368
- durationMs: isInProgress ? now - start.timestampMs : end.timestampMs - start.timestampMs,
462
+ timestamp: start.timestamp,
463
+ duration: isInProgress ? now - start.timestamp : end.timestamp - start.timestamp,
369
464
  outcome: end?.outcome ?? "pending",
370
465
  exception: end?.exception,
371
466
  input: start.input,
@@ -377,107 +472,767 @@ var createInvocationSpans = (items) => {
377
472
  return result;
378
473
  };
379
474
 
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:";
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")()) {
385
498
  };
386
- var getUserFunctionUrlInMetadata = (meta) => {
387
- return meta.keys.find((key) => key.source === FUNCTIONS_META_KEY)?.id;
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")()) {
388
550
  };
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");
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));
394
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
+ });
395
570
  } else {
396
- meta.keys.push({
397
- source: FUNCTIONS_META_KEY,
398
- id: functionUrl
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
399
726
  });
727
+ } else {
728
+ obj[key] = value;
400
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")()) {
401
735
  };
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();
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
+ }
411
1086
  };
1087
+ var KEY_QUEUE_CURSOR = "dxos.org/key/local-trigger-dispatcher/queue-cursor";
412
1088
 
413
1089
  // src/executor/executor.ts
414
- import { Effect, Schema as Schema5 } from "effect";
1090
+ import { Effect as Effect6, Schema as Schema7 } from "effect";
415
1091
  import { runAndForwardErrors } from "@dxos/effect";
416
- var FunctionExecutor = class {
417
- constructor(_services) {
418
- this._services = _services;
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;
419
1102
  }
1103
+ return obj;
1104
+ }
1105
+ var FunctionExecutor = class {
1106
+ /**
1107
+ * Invoke function.
1108
+ */
420
1109
  // TODO(dmaretskyi): Invocation context: queue, space, etc...
421
- async invoke(fnDef, input) {
422
- const assertInput = fnDef.inputSchema.pipe(Schema5.asserts);
1110
+ async invoke(functionDef, input) {
1111
+ const assertInput = functionDef.inputSchema.pipe(Schema7.asserts);
423
1112
  assertInput(input);
424
1113
  const context = {
1114
+ space: void 0,
425
1115
  getService: this._services.getService.bind(this._services),
426
1116
  getSpace: async (_spaceId) => {
427
1117
  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
1118
  }
433
1119
  };
434
- const result = fnDef.handler({
1120
+ const result = functionDef.handler({
435
1121
  context,
436
1122
  data: input
437
1123
  });
438
1124
  let data;
439
- if (Effect.isEffect(result)) {
440
- data = await result.pipe(Effect.provide(this._services.createLayer()), runAndForwardErrors);
1125
+ if (Effect6.isEffect(result)) {
1126
+ data = await result.pipe(Effect6.provide(this._services.createLayer()), runAndForwardErrors);
441
1127
  } else {
442
1128
  data = await result;
443
1129
  }
444
- const assertOutput = fnDef.outputSchema?.pipe(Schema5.asserts);
1130
+ const assertOutput = functionDef.outputSchema?.pipe(Schema7.asserts);
445
1131
  assertOutput(data);
446
1132
  return data;
447
1133
  }
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}`);
1134
+ constructor(_services) {
1135
+ _define_property5(this, "_services", void 0);
1136
+ this._services = _services;
455
1137
  }
456
1138
  };
457
- var FunctionError = class extends BaseError.extend("FUNCTION_ERROR") {
458
- };
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
+ });
459
1206
  export {
1207
+ ComputeEvent,
1208
+ ComputeEventLogger,
1209
+ ComputeEventPayload,
460
1210
  ConfiguredCredentialsService,
461
1211
  ContextQueueService,
462
1212
  CredentialsService,
463
1213
  DatabaseService,
464
1214
  EmailTriggerOutput,
465
- EventLogger,
1215
+ FUNCTIONS_META_KEY,
466
1216
  FUNCTIONS_PRESET_META_KEY,
467
1217
  FUNCTION_TYPES,
468
- FunctionCallService,
1218
+ FunctionDefinition,
469
1219
  FunctionError,
470
1220
  FunctionExecutor,
1221
+ FunctionImplementationResolver,
471
1222
  FunctionManifestSchema,
1223
+ FunctionNotFoundError,
472
1224
  FunctionTrigger,
473
- FunctionTriggerSchema,
474
1225
  FunctionType,
475
1226
  InvocationOutcome,
476
1227
  InvocationTraceEndEvent,
477
1228
  InvocationTraceEventType,
478
1229
  InvocationTraceStartEvent,
1230
+ InvocationTracer,
1231
+ LocalFunctionExecutionService,
1232
+ MESSAGE_PROPERTY_TOOL_CALL_ID,
479
1233
  QueueService,
480
1234
  QueueTriggerOutput,
1235
+ RemoteFunctionExecutionService,
481
1236
  SERVICE_TAGS,
482
1237
  ScriptType,
483
1238
  ServiceContainer,
@@ -488,17 +1243,24 @@ export {
488
1243
  TraceEventException,
489
1244
  TraceEventLog,
490
1245
  TracingService,
491
- TriggerKind,
1246
+ TriggerDispatcher,
1247
+ TriggerKinds,
492
1248
  TriggerSchema,
1249
+ TriggerState,
1250
+ TriggerStateNotFoundError,
1251
+ TriggerStateStore,
493
1252
  WebhookTriggerOutput,
494
1253
  createDefectLogger,
495
1254
  createEventLogger,
496
1255
  createInvocationSpans,
497
1256
  defineFunction,
1257
+ deserializeFunction,
1258
+ examples_exports as exampleFunctions,
498
1259
  getInvocationUrl,
499
- getUserFunctionUrlInMetadata,
1260
+ getUserFunctionIdInMetadata,
500
1261
  logCustomEvent,
501
- makeFunctionUrl,
502
- setUserFunctionUrlInMetadata
1262
+ serializeFunction,
1263
+ setUserFunctionIdInMetadata,
1264
+ withAuthorization
503
1265
  };
504
1266
  //# sourceMappingURL=index.mjs.map