blib/lib/Langertha/Moment.pm

filter: Statementstmt 100% 44 / 44 Branchbran 90.9% 20 / 22 Conditioncond 66.6% 2 / 3 MC/DCmcdc 50.0% 1 / 2 Subroutinesub 100% 12 / 12 Podpod 100% 2 / 2 totaltotal 95.2% 81 / 85 CC 13 SCAR 15.2
CC
13
Cov
96%
from_wire
9.0
_compare_numeric
4.0
_compare_string
2.0
CRAP 4.6
« blib/lib/Langertha/Engine/Groq.pm ↑ Summary blib/lib/Langertha.pm »
1 package Langertha::Moment;
2 # ABSTRACT: Instant on the wire — a Time::Moment that numifies to its Unix epoch
3 182 our $VERSION = '0.503';
4 182 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 182 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 182 ▶use parent 'Time::Moment';
Subroutine BEGIN: called CC=1 SCAR=0.0
7 182 ▶use Scalar::Util qw( blessed );
Subroutine BEGIN: called CC=1 SCAR=0.0
8  
9 # NOT a Moose class, and deliberately so — the one place in this distribution
10 # that departs from the "Moose exclusively / always make_immutable" house rule.
11 #
12 # Time::Moment is XS. Its instances are blessed SCALARs holding an opaque
13 # struct, and every constructor (from_string, from_epoch, now, ...) as well as
14 # every derivation (plus_days, with_offset_same_instant, ...) blesses into the
15 # invocant's class from inside XS, never through Moose::Object::new. A Moose
16 # metaclass laid over that would describe an object system nothing here uses:
17 # make_immutable would inline a constructor that no Time::Moment code path
18 # calls, and Moose's default hash-based meta-instance does not fit a blessed
19 # SCALAR at all.
20 #
21 # MooseX::NonMoose (already a dependency, used by Langertha::Request::HTTP)
22 # was considered and rejected for the same reason. It exists to give a Moose
23 # class Moose *attributes* on top of a foreign parent, by routing
24 # Moose::Object::new through FOREIGNBUILDARGS into the parent's new. This
25 # class adds no attributes, and the constructors that actually matter here
26 # (from_string / from_epoch / from_wire) bypass new entirely — so NonMoose
27 # would add a metaclass, a wrapped new nobody calls, and a hash-instance
28 # assumption that is false, in exchange for nothing.
29 #
30 # What this class *is* is the overload set: subclassing is the only way to
31 # attach one to Time::Moment without polluting every other consumer of it in
32 # the process.
33 use overload
34 # The back-compat contract. Langertha::Response->created was a Unix
35 # timestamp Int for its whole life; numeric context must keep yielding
36 # exactly that number. Note this is not inherited: Time::Moment overloads
37 # '""' but not '0+', so a plain Time::Moment numifies through its string
38 # form and evaluates to its *year*.
39 54 ▶ '0+' => sub { $_[0]->epoch },
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine __ANON__: called CC=1 SCAR=0.0
40 # Same as the inherited '""', declared explicitly: the pair of "'0+' is the
41 # epoch, '""' is the full ISO-8601 stamp" is the contract of this class, and
42 # it should not silently follow a change in the parent.
43 14 ▶ '""' => sub { $_[0]->to_string },
Subroutine __ANON__: called CC=1 SCAR=0.0
44 '<=>' => \&_compare_numeric,
45 'cmp' => \&_compare_string,
46 # An instant that exists is true, the same call Langertha::Response makes for
47 # itself (karr #100). Declared rather than left to autogeneration: perl
48 # derives bool from '0+' here, which makes the epoch-0 moment -- a perfectly
49 # real instant -- false, and which overload it picks is not something to
50 # depend on across perl versions.
51 6 ▶ 'bool' => sub { 1 },
Subroutine __ANON__: called CC=1 SCAR=0.0
52 182 fallback => 1;
53  
54  
55 4 ▶sub TO_JSON { return 0 + $_[0]->epoch }
Subroutine TO_JSON: called CC=1 SCAR=0.0
Pod documented
56  
57  
58 7 ▶sub _compare_numeric {
Subroutine _compare_numeric: called CC=4 SCAR=13.9
59 7 my ( $self, $other, $swapped ) = @_;
60 7 ▶ my $result = ( blessed($other) && $other->isa('Time::Moment') )
Branch: 1 branch
BranchTrueFalseTotal
builtin::blessed($other) && $other->isa('Time::Moment') ? : 3 4 7
Condition66%2/3
builtin::blessed($other) and $other->isa("Time::Moment")
!ll&&!rl&&r
403
MC/DC50%1/2
builtin::blessed($other) and $other->isa("Time::Moment")
builtin::blessed($other) $other->isa("Time::Moment")
Truth table66%2/3
A and B
A= builtin::blessed($other)B= $other->isa("Time::Moment")
ABresult
0X0
100
111
61 ? $self->compare($other)
62 : ( $self->epoch <=> $other );
63 7 ▶ return $swapped ? -$result : $result;
Branch: 1 branch
BranchTrueFalseTotal
$swapped ? : 1 6 7
64 }
65  
66 2 ▶sub _compare_string {
Subroutine _compare_string: called CC=2 SCAR=7.1
67 2 my ( $self, $other, $swapped ) = @_;
68 2 my $result = $self->to_string cmp "$other";
69 2 ▶ return $swapped ? -$result : $result;
Branch: 1 branch
BranchTrueFalseTotal
$swapped ? : 0 2 2
70 }
71  
72 182 ▶sub from_wire {
Subroutine from_wire: called CC=9 SCAR=22.0
Pod documented
73 182 my ( $class, $value ) = @_;
74 182 ▶ return undef unless defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 1 181 182
75  
76 181 my $moment;
77 181 ▶ if ( blessed($value) ) {
Branch: 2 branches
BranchTrueFalseTotal
if (builtin::blessed($value)) { } 15 166 181
elsif ($value =~ /\A [-+]? [0-9]+ (?: \. [0-9]+ )? \z/x) { } 116 50 166
78 15 ▶ return undef unless $value->isa('Time::Moment');
Branch: 1 branch
BranchTrueFalseTotal
unless $value->isa("Time::Moment") 0 15 15
79 15 ▶ return $value if $value->isa($class);
Branch: 1 branch
BranchTrueFalseTotal
if $value->isa($class) 14 1 15
80 # A plain Time::Moment (or a foreign subclass): re-parse its own canonical
81 # string. That carries nanoseconds and offset across without assuming
82 # anything about how the other class was built.
83 1 $moment = eval { $class->from_string( $value->to_string ) };
84 }
85 elsif ( $value =~ /\A [-+]? [0-9]+ (?: \. [0-9]+ )? \z/x ) {
86 # The OpenAI-compatible wire sends an epoch integer, and Ollama-compatible
87 # shims sometimes send epoch seconds where Ollama itself sends RFC3339.
88 #
89 # Seconds and milliseconds are told apart by magnitude, not by any wire
90 # flag: Time::Moment's whole representable range (through year 9999) tops
91 # out at epoch 253402300799 -- 12 digits -- so a genuine seconds epoch is
92 # always below 1e12. A 13-digit value is out of range as seconds but is a
93 # sane milliseconds epoch (1e12 ms is year 2001), so scale it down instead
94 # of letting from_epoch reject it and silently drop the field. The division
95 # keeps the sub-second part. A normal ~10-digit seconds epoch is untouched
96 # (karr #171).
97 116 my $epoch = 0 + $value;
98 116 ▶ $epoch /= 1000 if abs($epoch) >= 1e12;
Branch: 1 branch
BranchTrueFalseTotal
if abs $epoch >= "1000000000000" 3 113 116
99 116 $moment = eval { $class->from_epoch( $epoch ) };
100 }
101 else {
102 # lenient => 1 is chosen, not a default: it is what makes this accept the
103 # same set the hand-rolled RFC3339 regex it replaced accepted — a space
104 # instead of the T, an offset written without its colon, lowercase t/z.
105 # It does not widen the door to non-timestamps: bare '2026' and
106 # '2026-02-22' are still rejected, with or without it.
107 50 $moment = eval { $class->from_string( "$value", lenient => 1 ) };
108 }
109  
110 167 ▶ return undef unless defined $moment;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $moment 12 155 167
111 # Ollama emits "0001-01-01T00:00:00Z" — Go's zero time.Time — as its "no
112 # timestamp" sentinel, and it is a perfectly valid RFC3339 string that
113 # Time::Moment parses without complaint. Treat the whole pre-1000 band as
114 # absent rather than as a real instant; nothing an LLM provider reports
115 # belongs there (karr #92).
116 155 ▶ return undef if $moment->year < 1000;
Branch: 1 branch
BranchTrueFalseTotal
if $moment->year < 1000 4 151 155
117 151 return $moment;
118 }
119  
120  
121  
122 182 1;
123  
124 __END__
125  
126 =pod
127  
128 =encoding UTF-8
129  
130 =head1 NAME
131  
132 Langertha::Moment - Instant on the wire — a Time::Moment that numifies to its Unix epoch
133  
134 =head1 VERSION
135  
136 version 0.503
137  
138 =head1 SYNOPSIS
139  
140 my $m = Langertha::Moment->from_wire('2026-05-05T02:53:03.138043625Z');
141  
142 print 0 + $m; # 1777949583 — the Unix epoch
143 print "$m"; # 2026-05-05T02:53:03.138043625Z
144 print $m->nanosecond;# 138043625
145 print $m->year; # 2026 — every Time::Moment method is available
146  
147 my $o = Langertha::Moment->from_wire(1777949583); # OpenAI-shaped epoch
148 my $x = Langertha::Moment->from_wire('garbage'); # undef, never dies
149  
150 =head1 DESCRIPTION
151  
152 Canonical value object for an instant reported by a provider — currently
153 L<Langertha::Response/created>.
154  
155 C<Langertha::Moment> is a subclass of L<Time::Moment> and inherits its whole
156 API: nanosecond resolution, UTC offsets, comparison, arithmetic. What it adds
157 is an overload set that makes the object drop into the places a plain Unix
158 timestamp used to sit:
159  
160 =over
161  
162 =item * C<0+> yields L<Time::Moment/epoch> — whole seconds since the epoch.
163 This is the compatibility contract. Every provider on the OpenAI-compatible
164 wire reports C<created> as an epoch integer, and that is the number
165 L<Langertha::Response/to_hash> keeps emitting.
166  
167 =item * C<""> yields L<Time::Moment/to_string> — the full ISO-8601 stamp,
168 sub-seconds included. Nothing is rounded away on the way in, so an Ollama
169 stamp round-trips byte for byte.
170  
171 =item * C<< <=> >> compares instants. Against another L<Time::Moment> it
172 delegates to L<Time::Moment/compare> and is nanosecond-exact; against a plain
173 number it compares whole epoch seconds. The inherited overload would
174 C<die> on the second case ("can only be compared to another Time::Moment
175 object"), which is precisely what code written against the old C<Int> does.
176  
177 =item * C<cmp> compares the ISO-8601 strings.
178  
179 =item * C<bool> is a constant true — an instant that exists is true, including
180 the epoch-0 one. Note this differs from the plain C<Int> the attribute used to
181 hold, where C<0> was false; L<Langertha::Response/has_created> is the predicate
182 for "did the provider report a stamp at all", and it is unaffected.
183  
184 =back
185  
186 =head2 Why a subclass rather than an attribute pair
187  
188 The alternative — keep an C<Int> and hang a second "and here are the
189 nanoseconds" field beside it — is the shape ADR 0011 already rejected once for
190 timing. One value, one object, and the provider's native form stays reachable
191 under L<Langertha::Response/raw>.
192  
193 =head2 JSON
194  
195 C<TO_JSON> returns the epoch B<number>, so an encoder with C<convert_blessed>
196 enabled serializes a moment exactly where an C<Int> used to sit — inside
197 L<Langertha::Response/to_hash> and anywhere else a caller drops the value into
198 a structure of their own.
199  
200 This overrides L<Time::Moment>'s own C<TO_JSON>, which returns the ISO-8601
201 string. Inheriting it would have been the quieter bug of the two: no error,
202 just a field that silently changed from number to string in every trace and
203 log that carries a response. The number is the compatibility surface; the
204 string is one C<"$moment"> away.
205  
206 An encoder B<without> C<convert_blessed> still dies on the object, as it does
207 on every other value object a L<Langertha::Response> carries
208 (L<Langertha::Usage>, L<Langertha::ToolCall>, L<Langertha::RateLimit>). That
209 is a real break against the old plain C<Int> — see
210 L<Langertha::Response/"Comparing and printing created">.
211  
212 =head2 TO_JSON
213  
214 Returns the Unix epoch as a number, so a moment encodes as the plain integer
215 the field held before this class existed. Overrides L<Time::Moment>'s
216 C<TO_JSON>, which returns the ISO-8601 string.
217  
218 =head2 from_wire
219  
220 my $m = Langertha::Moment->from_wire( $value ); # or undef
221  
222 The lenient inbound constructor: the one entry point that turns whatever a
223 provider put in a timestamp field into a C<Langertha::Moment>, and returns
224 C<undef> — never dies — when it cannot.
225  
226 Accepts, in this order:
227  
228 =over
229  
230 =item * an existing C<Langertha::Moment> (returned unchanged), or any other
231 L<Time::Moment>, re-parsed from its canonical string;
232  
233 =item * an epoch number, integer or fractional, as a number or as a
234 digit string — the OpenAI-compatible wire form; a 13-digit value is read as a
235 millisecond epoch and scaled to seconds, keeping its sub-second precision,
236 since no representable seconds epoch reaches that magnitude;
237  
238 =item * an ISO-8601 / RFC3339 string, parsed with L<Time::Moment/from_string>
239 in C<lenient> mode, keeping sub-seconds at full precision.
240  
241 =back
242  
243 Returns C<undef> for anything else, for a value outside L<Time::Moment>'s
244 representable range, and for a stamp in year 1..999 — the band Go-based
245 servers use for their "no timestamp" zero value.
246  
247 B<Leniency is the point.> A timestamp is metadata; it must never be able to
248 take a whole provider response down with it, which is exactly what happened
249 when L<Langertha::Response/created> was a C<Maybe[Int]> and Ollama sent a
250 string (GitHub issue #3, karr #92 / #117). Callers that want a parse failure
251 to be loud should use the inherited L<Time::Moment/from_string> or
252 L<Time::Moment/from_epoch> directly — those still die.
253  
254 =head1 SEE ALSO
255  
256 =over
257  
258 =item * L<Time::Moment> - The parent class; its whole API is available here
259  
260 =item * L<Langertha::Response> - Carries a C<Langertha::Moment> as C<created>
261  
262 =back
263  
264 =head1 SUPPORT
265  
266 =head2 Issues
267  
268 Please report bugs and feature requests on GitHub at
269 L<https://github.com/Getty/langertha/issues>.
270  
271 =head2 IRC
272  
273 Join C<#langertha> on C<irc.perl.org> or message Getty directly.
274  
275 =head1 CONTRIBUTING
276  
277 Contributions are welcome! Please fork the repository and submit a pull request.
278  
279 =head1 AUTHOR
280  
281 Torsten Raudssus <getty@cpan.org>
282  
283 =head1 COPYRIGHT AND LICENSE
284  
285 This software is copyright (c) 2026 by Torsten Raudssus L<https://raudssus.de/>.
286  
287 This is free software; you can redistribute it and/or modify it under
288 the same terms as the Perl 5 programming language system itself.
289  
290 =cut
« blib/lib/Langertha/Engine/Groq.pm ↑ Summary blib/lib/Langertha.pm »