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