Skip to content

aws-cdk: Duration.parse() does not handle units larger then days  #29572

@mattaschmann

Description

@mattaschmann

Describe the bug

While trying to use cdk.Duration.parse() with the strings P1Y and P1M it threw errors. Looking at the source (

public static parse(duration: string): Duration {
const matches = duration.match(/^P(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?$/);
if (!matches) {
throw new Error(`Not a valid ISO duration: ${duration}`);
}
const [, days, hours, minutes, seconds] = matches;
if (!days && !hours && !minutes && !seconds) {
throw new Error(`Not a valid ISO duration: ${duration}`);
}
return Duration.millis(
_toInt(seconds) * TimeUnit.Seconds.inMillis
+ (_toInt(minutes) * TimeUnit.Minutes.inMillis)
+ (_toInt(hours) * TimeUnit.Hours.inMillis)
+ (_toInt(days) * TimeUnit.Days.inMillis),
);
function _toInt(str: string): number {
if (!str) { return 0; }
return Number(str);
}
}
) it's obvious that any unit larger then days are not handled.

Expected Behavior

As the documentation for this message states:

    /**
     * Parse a period formatted according to the ISO 8601 standard
     *
     * @see https://www.iso.org/standard/70907.html
     * @param duration an ISO-formatted duration to be parsed.
     * @returns the parsed `Duration`.
     */

It should correctly handle all valid ISO 8601 strings. Either that, or the documentation needs to indicate it doesn't handled anything larger then days.

Current Behavior

Throws an error on any unit larger then a day.

Reproduction Steps

import * as cdk from 'aws-cdk-lib'

cdk.Duration.parse('P1Y')
cdk.Duration.parse('P1M')

Possible Solution

Add larger units to the regular expression and handle them, or change the documentation to indicate that they are not handled.

Additional Information/Context

No response

CDK CLI Version

2.115.0 (build 58027ee)

Framework Version

No response

Node.js Version

v18.15.0

OS

macOS: 14.3.1 (23D60)

Language

TypeScript

Language Version

No response

Other information

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugThis issue is a bug.effort/mediumMedium work item – several days of effortp2package/toolsRelated to AWS CDK Tools or CLI

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions