@fintekkers/ledger-models 1.1.51 → 1.1.53

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 (36) hide show
  1. package/README.md +37 -0
  2. package/index.js +19 -0
  3. package/index.js.map +1 -1
  4. package/index.ts +27 -1
  5. package/node/wrappers/models/security/security.d.ts +29 -0
  6. package/node/wrappers/models/security/security.js +59 -0
  7. package/node/wrappers/models/security/security.js.map +1 -1
  8. package/node/wrappers/models/security/security.ts +63 -0
  9. package/node/wrappers/models/security/security_metric.d.ts +163 -0
  10. package/node/wrappers/models/security/security_metric.js +431 -0
  11. package/node/wrappers/models/security/security_metric.js.map +1 -0
  12. package/node/wrappers/models/security/security_metric.test.d.ts +1 -0
  13. package/node/wrappers/models/security/security_metric.test.js +215 -0
  14. package/node/wrappers/models/security/security_metric.test.js.map +1 -0
  15. package/node/wrappers/models/security/security_metric.test.ts +223 -0
  16. package/node/wrappers/models/security/security_metric.ts +514 -0
  17. package/node/wrappers/services/security-metric-service/SecurityMetricService.d.ts +94 -0
  18. package/node/wrappers/services/security-metric-service/SecurityMetricService.js +257 -0
  19. package/node/wrappers/services/security-metric-service/SecurityMetricService.js.map +1 -0
  20. package/node/wrappers/services/security-metric-service/SecurityMetricService.ts +298 -0
  21. package/node/wrappers/services/security_metric_fake_server.d.ts +35 -0
  22. package/node/wrappers/services/security_metric_fake_server.js +203 -0
  23. package/node/wrappers/services/security_metric_fake_server.js.map +1 -0
  24. package/node/wrappers/services/security_metric_fake_server.ts +194 -0
  25. package/node/wrappers/services/security_metric_readme.test.d.ts +1 -0
  26. package/node/wrappers/services/security_metric_readme.test.js +132 -0
  27. package/node/wrappers/services/security_metric_readme.test.js.map +1 -0
  28. package/node/wrappers/services/security_metric_readme.test.ts +115 -0
  29. package/node/wrappers/services/security_metric_service.test.d.ts +1 -0
  30. package/node/wrappers/services/security_metric_service.test.js +307 -0
  31. package/node/wrappers/services/security_metric_service.test.js.map +1 -0
  32. package/node/wrappers/services/security_metric_service.test.ts +321 -0
  33. package/node/wrappers/util/object-types.test.js +34 -1
  34. package/node/wrappers/util/object-types.test.js.map +1 -1
  35. package/node/wrappers/util/object-types.test.ts +43 -0
  36. package/package.json +1 -1
@@ -0,0 +1,514 @@
1
+ /**
2
+ * Security metrics (LM-485): the pure rules behind `SecurityMetricService`
3
+ * and `Security.getMetric`. No I/O here: request builders, response mapping,
4
+ * record validation and chunking, checked in every language against
5
+ * test-fixtures/security-metric/cases.json.
6
+ *
7
+ * A metric is a dated series per security (shares outstanding, NAV per share,
8
+ * total net assets). Absent is never 0: a security with no point on or before
9
+ * the date asked for has no result (`undefined`), while a stored 0 is a real 0.
10
+ */
11
+ import { Decimal } from 'decimal.js';
12
+ import { SecurityMetricPointProto, SecurityMetricSeriesProto } from '../../../fintekkers/models/security/security_metric_pb';
13
+ import { SecurityMetricTypeProto } from '../../../fintekkers/models/security/security_metric_type_pb';
14
+ import { LocalDateProto } from '../../../fintekkers/models/util/local_date_pb';
15
+ import { CreateSecurityMetricRequestProto } from '../../../fintekkers/requests/security_metric/create_security_metric_request_pb';
16
+ import {
17
+ GetLatestSecurityMetricRequestProto,
18
+ type GetLatestSecurityMetricResponseProto,
19
+ } from '../../../fintekkers/requests/security_metric/get_latest_security_metric_request_pb';
20
+ import {
21
+ SearchSecurityMetricRequestProto,
22
+ type SearchSecurityMetricResponseProto,
23
+ } from '../../../fintekkers/requests/security_metric/search_security_metric_request_pb';
24
+ import { RequestOperationTypeProto } from '../../../fintekkers/requests/util/operation_pb';
25
+ import { stampOwn } from '../../util/object-types';
26
+ import { ModelValidationError } from '../errors';
27
+ import { LocalDate, daysBetween } from '../utils/date';
28
+ import { ZonedDateTime } from '../utils/datetime';
29
+ import { decodeDecimal, encodeDecimal, fromDecimalJs, parseDecimalString, toDecimalJs, withField } from '../utils/decimal';
30
+ import { UUID } from '../utils/uuid';
31
+
32
+ /** Most points sent in one CreateOrUpdate request; `record` splits larger inputs. */
33
+ export const RECORD_CHUNK_SIZE = 5000;
34
+
35
+ /** A metric: the generated enum value, or its name such as `'SHARES_OUTSTANDING'`. */
36
+ export type SecurityMetricInput = SecurityMetricTypeProto | string;
37
+
38
+ /** A calendar date: a `LocalDate`, a `Date` (its local date parts) or an ISO `yyyy-mm-dd` string. */
39
+ export type DateInput = LocalDate | Date | string;
40
+
41
+ /** A security id: a `UUID` or its string form. */
42
+ export type SecurityIdInput = UUID | string;
43
+
44
+ /** A value to record: a decimal.js `Decimal`, a decimal string, or a number (read via its string form). */
45
+ export type MetricValueInput = Decimal | string | number;
46
+
47
+ /**
48
+ * Points to record: an object keyed by ISO date, or a list of (date, value)
49
+ * pairs. A list may repeat a date, which is rejected as `duplicate date`.
50
+ */
51
+ export type RecordPointsInput =
52
+ | Record<string, MetricValueInput | null | undefined>
53
+ | ReadonlyArray<readonly [DateInput, MetricValueInput | null | undefined]>;
54
+
55
+ /** One rejected point: its ISO date (null for the whole input) and the reason. */
56
+ export interface MetricPointViolation {
57
+ date: string | null;
58
+ reason: string;
59
+ }
60
+
61
+ // ---------------------------------------------------------------- errors
62
+
63
+ /** Typed input error: the caller asked for something that cannot be sent. */
64
+ export class SecurityMetricInputError extends Error {
65
+ constructor(message: string) {
66
+ super(message);
67
+ this.name = 'SecurityMetricInputError';
68
+ }
69
+ }
70
+
71
+ /** The security has no UUID, so its metrics cannot be looked up. */
72
+ export class MissingSecurityId extends SecurityMetricInputError {
73
+ constructor() {
74
+ super('security has no UUID: cannot fetch its metrics');
75
+ this.name = 'MissingSecurityId';
76
+ }
77
+ }
78
+
79
+ /** The metric is UNKNOWN_SECURITY_METRIC, or not a SecurityMetricTypeProto value or name. */
80
+ export class UnknownMetric extends SecurityMetricInputError {
81
+ /** The metric as given, as a string. */
82
+ readonly metric: string;
83
+
84
+ constructor(metric: string) {
85
+ super(`unknown security metric: ${metric}`);
86
+ this.name = 'UnknownMetric';
87
+ this.metric = metric;
88
+ }
89
+ }
90
+
91
+ /** Points rejected by `validateRecord`; `violations` lists every bad point in input order. */
92
+ export class InvalidMetricPoints extends SecurityMetricInputError {
93
+ readonly metric: string;
94
+ readonly violations: ReadonlyArray<MetricPointViolation>;
95
+
96
+ /** @param details per violation, extra text for the message (e.g. the bad value), or '' */
97
+ constructor(metric: string, violations: MetricPointViolation[], details: string[] = []) {
98
+ const parts = violations.map((v, i) => {
99
+ const detail = details[i] ? ` (${details[i]})` : '';
100
+ return v.date === null ? `${v.reason}${detail}` : `${v.date}: ${v.reason}${detail}`;
101
+ });
102
+ super(`invalid ${metric} points: ${parts.join('; ')}`);
103
+ this.name = 'InvalidMetricPoints';
104
+ this.metric = metric;
105
+ this.violations = Object.freeze(violations.map(v => Object.freeze({ ...v })));
106
+ }
107
+ }
108
+
109
+ /** Where a service error came from: the `host:port` called and the gRPC status. */
110
+ export interface ServiceErrorDetails {
111
+ /** `host:port` of the service, when known. */
112
+ address?: string;
113
+ /** gRPC status code number, when the error came from a call. */
114
+ code?: number;
115
+ /** gRPC status code name, e.g. `NOT_FOUND`. */
116
+ codeName?: string;
117
+ }
118
+
119
+ /** The SecurityMetric service failed or returned something unusable. */
120
+ export class SecurityMetricServiceError extends Error {
121
+ readonly address?: string;
122
+ readonly code?: number;
123
+ readonly codeName?: string;
124
+
125
+ constructor(message: string, details: ServiceErrorDetails = {}) {
126
+ super(message);
127
+ this.name = 'SecurityMetricServiceError';
128
+ this.address = details.address;
129
+ this.code = details.code;
130
+ this.codeName = details.codeName;
131
+ }
132
+ }
133
+
134
+ /** The SecurityMetric service could not be reached (gRPC UNAVAILABLE). */
135
+ export class ServiceUnavailable extends SecurityMetricServiceError {
136
+ constructor(message: string, details: ServiceErrorDetails = {}) {
137
+ super(message, details);
138
+ this.name = 'ServiceUnavailable';
139
+ }
140
+ }
141
+
142
+ // ---------------------------------------------------------------- dates
143
+
144
+ /** ISO `yyyy-mm-dd` of `d`. (`LocalDate.toString` does not zero-pad.) */
145
+ export function isoDate(d: LocalDate): string {
146
+ const p = d.toProto();
147
+ return `${String(p.getYear()).padStart(4, '0')}-${String(p.getMonth()).padStart(2, '0')}-${String(p.getDay()).padStart(2, '0')}`;
148
+ }
149
+
150
+ /**
151
+ * `d` as a `LocalDate`. A string must be an ISO calendar date `yyyy-mm-dd`;
152
+ * anything else is a SecurityMetricInputError naming it.
153
+ */
154
+ export function toLocalDate(d: DateInput): LocalDate {
155
+ if (d instanceof LocalDate) return d;
156
+ if (d instanceof Date) {
157
+ if (isNaN(d.getTime())) throw new SecurityMetricInputError('date is an invalid Date');
158
+ return LocalDate.from(d);
159
+ }
160
+ if (typeof d === 'string') {
161
+ const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(d);
162
+ if (m) {
163
+ const [year, month, day] = [m[1], m[2], m[3]].map(s => parseInt(s, 10));
164
+ const check = new Date(Date.UTC(year, month - 1, day));
165
+ if (check.getUTCFullYear() === year && check.getUTCMonth() === month - 1 && check.getUTCDate() === day) {
166
+ return new LocalDate(new LocalDateProto().setYear(year).setMonth(month).setDay(day));
167
+ }
168
+ }
169
+ throw new SecurityMetricInputError(`not an ISO date (yyyy-mm-dd): '${d}'`);
170
+ }
171
+ throw new SecurityMetricInputError(`not a date: ${String(d)}`);
172
+ }
173
+
174
+ function dateFromProto(proto: LocalDateProto): LocalDate {
175
+ return new LocalDate(new LocalDateProto().setYear(proto.getYear()).setMonth(proto.getMonth()).setDay(proto.getDay()));
176
+ }
177
+
178
+ /** Calendar days from `from` to `to` (negative when `to` is earlier). */
179
+ function daysFrom(from: LocalDate, to: LocalDate): number {
180
+ const a = from.toProto();
181
+ const b = to.toProto();
182
+ return daysBetween(new Date(a.getYear(), a.getMonth() - 1, a.getDay()), new Date(b.getYear(), b.getMonth() - 1, b.getDay()));
183
+ }
184
+
185
+ // ---------------------------------------------------------------- results
186
+
187
+ /** One observation: the date it is for and its value. */
188
+ export class MetricPoint {
189
+ readonly date: LocalDate;
190
+ readonly value: Decimal;
191
+
192
+ constructor(date: LocalDate, value: Decimal) {
193
+ this.date = date;
194
+ this.value = value;
195
+ }
196
+ }
197
+
198
+ /** The latest point on or before a date: its value, its date, the date asked for and the age in days. */
199
+ export class MetricResult {
200
+ readonly value: Decimal;
201
+ /** The observation date of the point. */
202
+ readonly date: LocalDate;
203
+ /** The date asked for. */
204
+ readonly on: LocalDate;
205
+ /** Calendar days from `date` to `on`: a Friday point asked for on Monday is 3. */
206
+ readonly ageDays: number;
207
+
208
+ constructor(value: Decimal, date: LocalDate, on: LocalDate) {
209
+ this.value = value;
210
+ this.date = date;
211
+ this.on = on;
212
+ this.ageDays = daysFrom(date, on);
213
+ }
214
+ }
215
+
216
+ /** A metric's history for one security: points in ascending date order, gaps kept. */
217
+ export class MetricSeries {
218
+ readonly securityId: UUID;
219
+ readonly metric: SecurityMetricTypeProto;
220
+ /** The as_of the service stamped on the first message, or undefined when unset. */
221
+ readonly asOf: ZonedDateTime | undefined;
222
+ readonly points: ReadonlyArray<MetricPoint>;
223
+
224
+ constructor(securityId: UUID, metric: SecurityMetricTypeProto, asOf: ZonedDateTime | undefined, points: MetricPoint[]) {
225
+ this.securityId = securityId;
226
+ this.metric = metric;
227
+ this.asOf = asOf;
228
+ this.points = Object.freeze([...points]);
229
+ }
230
+
231
+ /** The last point, or undefined for an empty series. */
232
+ get latest(): MetricPoint | undefined {
233
+ return this.points.length === 0 ? undefined : this.points[this.points.length - 1];
234
+ }
235
+
236
+ /** Values keyed by ISO date, in ascending date order. */
237
+ asDict(): Map<string, Decimal> {
238
+ return new Map(this.points.map(p => [isoDate(p.date), p.value] as [string, Decimal]));
239
+ }
240
+ }
241
+
242
+ // ---------------------------------------------------------------- metric
243
+
244
+ const KNOWN_METRICS: ReadonlyArray<SecurityMetricTypeProto> = [
245
+ SecurityMetricTypeProto.SHARES_OUTSTANDING,
246
+ SecurityMetricTypeProto.NAV_PER_SHARE,
247
+ SecurityMetricTypeProto.TOTAL_NET_ASSETS,
248
+ ];
249
+
250
+ /** The enum name of `metric`, e.g. `SHARES_OUTSTANDING`, or its number when it has none. */
251
+ export function metricName(metric: SecurityMetricTypeProto): string {
252
+ const name = (Object.keys(SecurityMetricTypeProto) as Array<keyof typeof SecurityMetricTypeProto>)
253
+ .find(k => SecurityMetricTypeProto[k] === metric);
254
+ return name ?? String(metric);
255
+ }
256
+
257
+ /**
258
+ * The metric as an enum value. UNKNOWN_SECURITY_METRIC, a number that is not
259
+ * a metric, or a string that is not a metric's name is an `UnknownMetric`
260
+ * naming it.
261
+ */
262
+ export function checkMetric(metric: SecurityMetricInput): SecurityMetricTypeProto {
263
+ if (typeof metric === 'string') {
264
+ const found = KNOWN_METRICS.find(m => metricName(m) === metric);
265
+ if (found === undefined) throw new UnknownMetric(metric);
266
+ return found;
267
+ }
268
+ if (!KNOWN_METRICS.includes(metric)) throw new UnknownMetric(metricName(metric));
269
+ return metric;
270
+ }
271
+
272
+ /** The UUID of `id`; a string that is not a UUID is a SecurityMetricInputError. */
273
+ export function toSecurityId(id: SecurityIdInput): UUID {
274
+ if (id instanceof UUID) return id;
275
+ if (typeof id === 'string' && /^[0-9a-fA-F]{8}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{12}$/.test(id)) {
276
+ return new UUID(UUID.fromString(id));
277
+ }
278
+ throw new SecurityMetricInputError(`not a security UUID: '${String(id)}'`);
279
+ }
280
+
281
+ function dedupe(uuids: ReadonlyArray<SecurityIdInput>): UUID[] {
282
+ const seen = new Set<string>();
283
+ const out: UUID[] = [];
284
+ for (const id of uuids) {
285
+ const uuid = toSecurityId(id);
286
+ const key = uuid.toString();
287
+ if (!seen.has(key)) {
288
+ seen.add(key);
289
+ out.push(uuid);
290
+ }
291
+ }
292
+ return out;
293
+ }
294
+
295
+ // ---------------------------------------------------------------- latest
296
+
297
+ /** GetLatest request for `metric` of each security (duplicates dropped, order kept) on `on`. */
298
+ export function buildGetLatest(
299
+ metric: SecurityMetricInput,
300
+ uuids: ReadonlyArray<SecurityIdInput>,
301
+ on: DateInput,
302
+ ): GetLatestSecurityMetricRequestProto {
303
+ const m = checkMetric(metric);
304
+ return stampOwn(new GetLatestSecurityMetricRequestProto())
305
+ .setSecurityIdsList(dedupe(uuids).map(u => u.toUUIDProto()))
306
+ .setMetricsList([m])
307
+ .setDate(toLocalDate(on).toProto());
308
+ }
309
+
310
+ function pointFromProto(p: SecurityMetricPointProto): MetricPoint {
311
+ const date = p.getObservationDate();
312
+ if (!date) throw new SecurityMetricServiceError('SecurityMetric returned a point with no observation_date');
313
+ const value = p.getValue();
314
+ if (!value) {
315
+ throw new SecurityMetricServiceError(`SecurityMetric returned a point with no value on ${isoDate(dateFromProto(date))}`);
316
+ }
317
+ return new MetricPoint(dateFromProto(date), toDecimalJs(withField('value', () => decodeDecimal(value))));
318
+ }
319
+
320
+ /**
321
+ * Maps a GetLatest response to every requested security (key: UUID string):
322
+ * the last point of its series for `metric`, or undefined when the response
323
+ * has no series for it or the series has no points. Series are matched by
324
+ * security_id, never by position; series for another metric or a security
325
+ * that was not asked for are ignored.
326
+ */
327
+ export function mapLatest(
328
+ response: GetLatestSecurityMetricResponseProto,
329
+ metric: SecurityMetricInput,
330
+ uuids: ReadonlyArray<SecurityIdInput>,
331
+ on: DateInput,
332
+ ): Map<string, MetricResult | undefined> {
333
+ const m = checkMetric(metric);
334
+ const onDate = toLocalDate(on);
335
+ const result = new Map<string, MetricResult | undefined>();
336
+ for (const uuid of dedupe(uuids)) result.set(uuid.toString(), undefined);
337
+ for (const series of response.getSeriesList()) {
338
+ if (series.getMetric() !== m) continue;
339
+ const key = UUID.fromUUIDProto(series.getSecurityId())?.toString();
340
+ if (key === undefined || !result.has(key) || result.get(key) !== undefined) continue;
341
+ const points = series.getPointsList();
342
+ if (points.length === 0) continue;
343
+ const last = pointFromProto(points[points.length - 1]);
344
+ result.set(key, new MetricResult(last.value, last.date, onDate));
345
+ }
346
+ return result;
347
+ }
348
+
349
+ // ---------------------------------------------------------------- history
350
+
351
+ /** Search request for `metric` of one security from `from` to `to`, both inclusive. */
352
+ export function buildSearch(
353
+ metric: SecurityMetricInput,
354
+ uuid: SecurityIdInput,
355
+ from: DateInput,
356
+ to: DateInput,
357
+ ): SearchSecurityMetricRequestProto {
358
+ const m = checkMetric(metric);
359
+ const securityId = toSecurityId(uuid);
360
+ const fromDate = toLocalDate(from);
361
+ const toDate = toLocalDate(to);
362
+ if (isoDate(fromDate) > isoDate(toDate)) {
363
+ throw new SecurityMetricInputError(`from date ${isoDate(fromDate)} is after to date ${isoDate(toDate)}`);
364
+ }
365
+ return stampOwn(new SearchSecurityMetricRequestProto())
366
+ .setSecurityId(securityId.toUUIDProto())
367
+ .setMetricsList([m])
368
+ .setStartDate(fromDate.toProto())
369
+ .setEndDate(toDate.toProto());
370
+ }
371
+
372
+ /**
373
+ * Joins the points of consecutive Search messages. Dates must be strictly
374
+ * ascending across the whole stream, else a SecurityMetricServiceError naming
375
+ * the date. No messages, or messages without points, give an empty series.
376
+ * `asOf` comes from the first message whose series has one.
377
+ */
378
+ export function mergeChunks(
379
+ chunks: ReadonlyArray<SearchSecurityMetricResponseProto>,
380
+ securityId: SecurityIdInput,
381
+ metric: SecurityMetricInput,
382
+ ): MetricSeries {
383
+ const m = checkMetric(metric);
384
+ const points: MetricPoint[] = [];
385
+ let asOf: ZonedDateTime | undefined;
386
+ let previous: string | undefined;
387
+ for (const chunk of chunks) {
388
+ const series = chunk.getSeries();
389
+ if (!series) continue;
390
+ if (asOf === undefined && series.hasAsOf()) asOf = new ZonedDateTime(series.getAsOf()!);
391
+ for (const p of series.getPointsList()) {
392
+ const point = pointFromProto(p);
393
+ const date = isoDate(point.date);
394
+ if (previous !== undefined && date <= previous) {
395
+ throw new SecurityMetricServiceError(
396
+ `Search returned ${date} after ${previous}: dates must be strictly ascending`);
397
+ }
398
+ previous = date;
399
+ points.push(point);
400
+ }
401
+ }
402
+ return new MetricSeries(toSecurityId(securityId), m, asOf, points);
403
+ }
404
+
405
+ // ---------------------------------------------------------------- record
406
+
407
+ function isDecimal(v: unknown): v is Decimal {
408
+ return v instanceof Decimal || Decimal.isDecimal(v);
409
+ }
410
+
411
+ /** The value as a Decimal, or undefined when it is not a finite decimal. */
412
+ function toDecimalValue(v: MetricValueInput): Decimal | undefined {
413
+ if (isDecimal(v)) return v.isFinite() ? v : undefined;
414
+ if (typeof v === 'number') {
415
+ return Number.isFinite(v) ? new Decimal(String(v)) : undefined;
416
+ }
417
+ if (typeof v === 'string') {
418
+ try {
419
+ return toDecimalJs(parseDecimalString(v));
420
+ } catch (e) {
421
+ if (e instanceof ModelValidationError) return undefined;
422
+ throw e;
423
+ }
424
+ }
425
+ return undefined;
426
+ }
427
+
428
+ function pairsOf(points: RecordPointsInput): Array<readonly [DateInput, MetricValueInput | null | undefined]> {
429
+ if (Array.isArray(points)) return points as Array<readonly [DateInput, MetricValueInput | null | undefined]>;
430
+ return Object.keys(points).map(k => [k, (points as Record<string, MetricValueInput | null | undefined>)[k]] as const);
431
+ }
432
+
433
+ /**
434
+ * Checks points before anything is sent. Every bad point is listed, in input
435
+ * order, in one `InvalidMetricPoints`: `no points` (empty input), `missing
436
+ * value`, `not a decimal`, `fractional share count` (SHARES_OUTSTANDING
437
+ * values must be whole; `100.00` is accepted as 100) and `duplicate date`
438
+ * (each repeat of a date). Returns the points sorted by date.
439
+ */
440
+ export function validateRecord(metric: SecurityMetricInput, points: RecordPointsInput): MetricPoint[] {
441
+ const m = checkMetric(metric);
442
+ const name = metricName(m);
443
+ const pairs = pairsOf(points);
444
+ const violations: MetricPointViolation[] = [];
445
+ const details: string[] = [];
446
+ const reject = (date: string | null, reason: string, detail = '') => {
447
+ violations.push({ date, reason });
448
+ details.push(detail);
449
+ };
450
+ if (pairs.length === 0) reject(null, 'no points');
451
+
452
+ const seen = new Set<string>();
453
+ const valid: MetricPoint[] = [];
454
+ for (const [rawDate, rawValue] of pairs) {
455
+ const date = toLocalDate(rawDate);
456
+ const iso = isoDate(date);
457
+ let value: Decimal | undefined;
458
+ if (rawValue === null || rawValue === undefined) {
459
+ reject(iso, 'missing value');
460
+ } else {
461
+ value = toDecimalValue(rawValue);
462
+ if (value === undefined) {
463
+ reject(iso, 'not a decimal', String(rawValue));
464
+ } else if (m === SecurityMetricTypeProto.SHARES_OUTSTANDING && !value.isInteger()) {
465
+ reject(iso, 'fractional share count', value.toFixed());
466
+ value = undefined;
467
+ }
468
+ }
469
+ if (seen.has(iso)) {
470
+ reject(iso, 'duplicate date');
471
+ } else {
472
+ seen.add(iso);
473
+ if (value !== undefined) valid.push(new MetricPoint(date, value));
474
+ }
475
+ }
476
+ if (violations.length > 0) throw new InvalidMetricPoints(name, violations, details);
477
+ return valid.sort((a, b) => (isoDate(a.date) < isoDate(b.date) ? -1 : 1));
478
+ }
479
+
480
+ /** `points` split into consecutive lists of at most `chunkSize`. */
481
+ export function chunkRecord<T>(points: ReadonlyArray<T>, chunkSize: number = RECORD_CHUNK_SIZE): T[][] {
482
+ if (!Number.isInteger(chunkSize) || chunkSize < 1) {
483
+ throw new SecurityMetricInputError(`chunk size must be a whole number of at least 1: ${chunkSize}`);
484
+ }
485
+ const chunks: T[][] = [];
486
+ for (let i = 0; i < points.length; i += chunkSize) chunks.push(points.slice(i, i + chunkSize));
487
+ return chunks;
488
+ }
489
+
490
+ /**
491
+ * The wire form of a point. Values are exact; a whole value (every
492
+ * SHARES_OUTSTANDING value after `validateRecord`) has scale 0.
493
+ */
494
+ export function pointToProto(point: MetricPoint): SecurityMetricPointProto {
495
+ return new SecurityMetricPointProto()
496
+ .setObservationDate(point.date.toProto())
497
+ .setValue(encodeDecimal(fromDecimalJs(point.value)));
498
+ }
499
+
500
+ /** CreateOrUpdate request (operation CREATE) carrying one chunk of points for one security. */
501
+ export function buildCreate(
502
+ metric: SecurityMetricInput,
503
+ uuid: SecurityIdInput,
504
+ chunk: ReadonlyArray<MetricPoint>,
505
+ ): CreateSecurityMetricRequestProto {
506
+ const m = checkMetric(metric);
507
+ const series = stampOwn(new SecurityMetricSeriesProto())
508
+ .setSecurityId(toSecurityId(uuid).toUUIDProto())
509
+ .setMetric(m)
510
+ .setPointsList(chunk.map(pointToProto));
511
+ return stampOwn(new CreateSecurityMetricRequestProto())
512
+ .setOperationType(RequestOperationTypeProto.CREATE)
513
+ .setSeries(series);
514
+ }
@@ -0,0 +1,94 @@
1
+ import type { CreateSecurityMetricRequestProto, CreateSecurityMetricResponseProto } from '../../../fintekkers/requests/security_metric/create_security_metric_request_pb';
2
+ import type { GetLatestSecurityMetricRequestProto, GetLatestSecurityMetricResponseProto } from '../../../fintekkers/requests/security_metric/get_latest_security_metric_request_pb';
3
+ import type { SearchSecurityMetricRequestProto, SearchSecurityMetricResponseProto } from '../../../fintekkers/requests/security_metric/search_security_metric_request_pb';
4
+ import { ZonedDateTime } from '../../models/utils/datetime';
5
+ import { SecurityMetricServiceError, type DateInput, type MetricResult, type MetricSeries, type RecordPointsInput, type SecurityIdInput, type SecurityMetricInput } from '../../models/security/security_metric';
6
+ import { type Endpoint, type Env } from '../../util/serviceaddress';
7
+ /** Default per-call deadline of the gRPC fetcher. */
8
+ export declare const DEFAULT_DEADLINE_MS = 30000;
9
+ /** The three SecurityMetric RPCs. `search` returns every streamed message, in order. */
10
+ export interface SecurityMetricFetcher {
11
+ getLatest(request: GetLatestSecurityMetricRequestProto): Promise<GetLatestSecurityMetricResponseProto>;
12
+ search(request: SearchSecurityMetricRequestProto): Promise<SearchSecurityMetricResponseProto[]>;
13
+ createOrUpdate(request: CreateSecurityMetricRequestProto): Promise<CreateSecurityMetricResponseProto>;
14
+ }
15
+ export interface GrpcFetcherOptions {
16
+ /** Per-call deadline in milliseconds (default 30000). */
17
+ deadlineMs?: number;
18
+ }
19
+ /**
20
+ * The default fetcher: a gRPC client for one endpoint. Errors become
21
+ * `ServiceUnavailable` (gRPC UNAVAILABLE) or `SecurityMetricServiceError`,
22
+ * both naming `host:port` and the status.
23
+ */
24
+ export declare class GrpcSecurityMetricFetcher implements SecurityMetricFetcher {
25
+ readonly address: string;
26
+ readonly deadlineMs: number;
27
+ private readonly client;
28
+ constructor(endpoint: Endpoint, options?: GrpcFetcherOptions);
29
+ close(): void;
30
+ private callOptions;
31
+ /** The service error for a failed call to `rpc`. */
32
+ toServiceError(rpc: string, err: unknown): SecurityMetricServiceError;
33
+ getLatest(request: GetLatestSecurityMetricRequestProto): Promise<GetLatestSecurityMetricResponseProto>;
34
+ search(request: SearchSecurityMetricRequestProto): Promise<SearchSecurityMetricResponseProto[]>;
35
+ createOrUpdate(request: CreateSecurityMetricRequestProto): Promise<CreateSecurityMetricResponseProto>;
36
+ }
37
+ export interface SecurityMetricServiceOptions {
38
+ /** Fetcher for this instance only. Default: gRPC to `resolve(Service.PRICE, env)`. */
39
+ fetcher?: SecurityMetricFetcher;
40
+ /** Environment the default address is resolved from (default `process.env`). */
41
+ env?: Env;
42
+ /** Per-call deadline of the default gRPC fetcher in milliseconds (default 30000). */
43
+ deadlineMs?: number;
44
+ }
45
+ declare class SecurityMetricService {
46
+ private readonly ownFetcher?;
47
+ private readonly env?;
48
+ private readonly deadlineMs?;
49
+ private grpcFetcher?;
50
+ constructor(options?: SecurityMetricServiceOptions);
51
+ /**
52
+ * A service whose default gRPC fetcher resolves the PRICE address from
53
+ * `env` instead of `process.env`.
54
+ */
55
+ static fromEnv(env: Env, options?: {
56
+ deadlineMs?: number;
57
+ }): SecurityMetricService;
58
+ /** This instance's fetcher, else the installed one, else the default gRPC fetcher (built on first use). */
59
+ private fetcher;
60
+ /** Closes the default gRPC client, if one was built. */
61
+ close(): void;
62
+ /**
63
+ * The latest value of `metric` on or before `on` (default today) for each
64
+ * security, in one GetLatest call. Every requested UUID string is a key;
65
+ * its value is undefined when the security has no point on or before `on`.
66
+ * No call for an empty list.
67
+ */
68
+ get(metric: SecurityMetricInput, uuids: ReadonlyArray<SecurityIdInput>, on?: DateInput): Promise<Map<string, MetricResult | undefined>>;
69
+ /** Every point of `metric` for one security from `from` to `to` (default today), both inclusive. */
70
+ getHistory(metric: SecurityMetricInput, uuid: SecurityIdInput, from: DateInput, to?: DateInput): Promise<MetricSeries>;
71
+ /**
72
+ * Stores points of `metric` for one security. Points are checked first
73
+ * (`InvalidMetricPoints`, nothing sent), then sent in chunks of
74
+ * `RECORD_CHUNK_SIZE`, one CreateOrUpdate each. Returns the as_of the
75
+ * service stamped on the last chunk. If a later chunk fails, the error
76
+ * says how many points were already stored.
77
+ */
78
+ record(metric: SecurityMetricInput, uuid: SecurityIdInput, points: RecordPointsInput): Promise<ZonedDateTime>;
79
+ }
80
+ /**
81
+ * Installs `fetcher` for every SecurityMetricService in the process (except
82
+ * instances built with their own fetcher). `null` restores the default.
83
+ */
84
+ declare function setSecurityMetricFetcher(fetcher: SecurityMetricFetcher | null): void;
85
+ /** The process-wide service that `Security.getMetric` and friends use, built on first use. */
86
+ declare function getSecurityMetricService(): SecurityMetricService;
87
+ /**
88
+ * Replaces the process-wide service, e.g. with `SecurityMetricService.fromEnv(env)`
89
+ * in a test. `null` clears it (the next `getSecurityMetricService()` builds a new one).
90
+ */
91
+ declare function setSecurityMetricService(service: SecurityMetricService | null): void;
92
+ /** Test teardown: removes the installed fetcher and closes and clears the process-wide service. */
93
+ declare function resetSecurityMetricServiceForTests(): void;
94
+ export { SecurityMetricService, setSecurityMetricFetcher, getSecurityMetricService, setSecurityMetricService, resetSecurityMetricServiceForTests, };