Skip to content

Commit 2c98018

Browse files
committed
add duration wait threshold
1 parent 58567bf commit 2c98018

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed

packages/trigger-sdk/src/v3/wait.ts

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -369,6 +369,12 @@ export class WaitpointTimeoutError extends Error {
369369
}
370370
}
371371

372+
const DURATION_WAIT_CHARGE_THRESHOLD_MS = 5000;
373+
374+
function printWaitBelowThreshold() {
375+
console.warn(`Waits of ${DURATION_WAIT_CHARGE_THRESHOLD_MS / 1000}s or less are charged.`);
376+
}
377+
372378
export const wait = {
373379
for: async (options: WaitForOptions) => {
374380
const ctx = taskContext.ctx;
@@ -380,6 +386,36 @@ export const wait = {
380386

381387
const start = Date.now();
382388
const durationInMs = calculateDurationInMs(options);
389+
390+
if (durationInMs <= DURATION_WAIT_CHARGE_THRESHOLD_MS) {
391+
return tracer.startActiveSpan(
392+
`wait.for()`,
393+
async (span) => {
394+
if (durationInMs <= 0) {
395+
return;
396+
}
397+
398+
printWaitBelowThreshold();
399+
400+
await new Promise((resolve) => setTimeout(resolve, durationInMs));
401+
},
402+
{
403+
attributes: {
404+
[SemanticInternalAttributes.STYLE_ICON]: "wait",
405+
...accessoryAttributes({
406+
items: [
407+
{
408+
text: nameForWaitOptions(options),
409+
variant: "normal",
410+
},
411+
],
412+
style: "codepath",
413+
}),
414+
},
415+
}
416+
);
417+
}
418+
383419
const date = new Date(start + durationInMs);
384420
const result = await apiClient.waitForDuration(ctx.run.id, {
385421
date: date,
@@ -417,6 +453,46 @@ export const wait = {
417453
throw new Error("wait.forToken can only be used from inside a task.run()");
418454
}
419455

456+
// Calculate duration in ms
457+
const durationInMs = options.date.getTime() - Date.now();
458+
459+
if (durationInMs <= DURATION_WAIT_CHARGE_THRESHOLD_MS) {
460+
return tracer.startActiveSpan(
461+
`wait.for()`,
462+
async (span) => {
463+
if (durationInMs === 0) {
464+
return;
465+
}
466+
467+
if (durationInMs < 0) {
468+
if (options.throwIfInThePast) {
469+
throw new Error("Date is in the past");
470+
}
471+
472+
return;
473+
}
474+
475+
printWaitBelowThreshold();
476+
477+
await new Promise((resolve) => setTimeout(resolve, durationInMs));
478+
},
479+
{
480+
attributes: {
481+
[SemanticInternalAttributes.STYLE_ICON]: "wait",
482+
...accessoryAttributes({
483+
items: [
484+
{
485+
text: options.date.toISOString(),
486+
variant: "normal",
487+
},
488+
],
489+
style: "codepath",
490+
}),
491+
},
492+
}
493+
);
494+
}
495+
420496
const apiClient = apiClientManager.clientOrThrow();
421497

422498
const result = await apiClient.waitForDuration(ctx.run.id, {

0 commit comments

Comments
 (0)