-
Notifications
You must be signed in to change notification settings - Fork 39
Implement dogstatsd, add timestamp support, fix flushing #648
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 16 commits
Commits
Show all changes
22 commits
Select commit
Hold shift + click to select a range
630019a
create dogstatsd class and constructor
nhulston 567b508
create `report` method to build dogstatsd payload
nhulston 2dde47a
implement `send` UDP datagram
nhulston 7bb3998
replace `hot-shots` with custom `dogstatsd` implementation
nhulston 9dccc5d
implement flushing strategy
nhulston e1a206b
remove `hot-shots`
nhulston ed3f52f
lint
nhulston 20da437
fix metric timestamp
nhulston 7d484ba
set max flush timeout to prevent infinite blocking
nhulston 85c2c18
fix metric log using fractional timestamps
nhulston 6258126
fix unit tests; test that we use dogstatsd with timestamp+extension
nhulston 79bdb43
update license
nhulston 1a2a38a
add debug log on error
nhulston f1f3615
unit tests
nhulston e0fa27c
fix debug logs
nhulston 48eb47d
log when socket times out
nhulston 5ea40f6
nits
nhulston 11fe06e
round in dogstatsd; unit test
nhulston b77211a
bind to local port before setting min send buffer size; add debug
nhulston fc08ed8
lint
nhulston fdb0bee
fix
nhulston b7967e6
remove `setSendBufferSize`, since it sets MAX send size, not MIN send…
nhulston File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -15,7 +15,6 @@ ts-jest,dev,MIT,Copyright (c) 2016-2018 Kulshekhar Kabra | |
| tslint,dev,Apache-2.0,"Copyright 2013-2019 Palantir Technologies, Inc." | ||
| typescript,dev,Apache-2.0,Copyright (c) Microsoft Corporation. | ||
| dc-polyfill,import,MIT,"Copyright (c) 2023 Datadog, Inc." | ||
| hot-shots,import,MIT,Copyright 2011 Steve Ivy. All rights reserved. | ||
| promise-retry,import,MIT,Copyright (c) 2014 IndigoUnited | ||
| serialize-error,import,MIT,Copyright (c) Sindre Sorhus <[email protected]> (https://sindresorhus.com) | ||
| shimmer,import,BSD-2-Clause,"Copyright (c) 2013-2019, Forrest L Norvell" | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,72 @@ | ||
| import * as dgram from "node:dgram"; | ||
| import { LambdaDogStatsD } from "./dogstatsd"; | ||
|
|
||
| jest.mock("node:dgram", () => ({ | ||
| createSocket: jest.fn(), | ||
| })); | ||
|
|
||
| describe("LambdaDogStatsD", () => { | ||
| let mockSend: jest.Mock; | ||
|
|
||
| beforeEach(() => { | ||
| // A send() that immediately calls its callback | ||
| mockSend = jest.fn((msg, port, host, cb) => cb()); | ||
| (dgram.createSocket as jest.Mock).mockReturnValue({ | ||
| send: mockSend, | ||
| getSendBufferSize: jest.fn().mockReturnValue(64 * 1024), | ||
| setSendBufferSize: jest.fn(), | ||
| }); | ||
| }); | ||
|
|
||
| afterEach(() => { | ||
| jest.clearAllMocks(); | ||
| }); | ||
|
|
||
| it("sends a distribution metric without tags or timestamp", async () => { | ||
| const client = new LambdaDogStatsD(); | ||
| client.distribution("metric", 1); | ||
| await client.flush(); | ||
|
|
||
| expect(mockSend).toHaveBeenCalledWith(Buffer.from("metric:1|d", "utf8"), 8125, "localhost", expect.any(Function)); | ||
| }); | ||
|
|
||
| it("sends with tags (sanitized) and timestamp", async () => { | ||
| const client = new LambdaDogStatsD(); | ||
| client.distribution("metric2", 2, 12345, ["tag1", "bad?tag"]); | ||
| await client.flush(); | ||
|
|
||
| // "bad?tag" becomes "bad_tag" | ||
| expect(mockSend).toHaveBeenCalledWith( | ||
| Buffer.from("metric2:2|d|#tag1,bad_tag|T12345", "utf8"), | ||
| 8125, | ||
| "localhost", | ||
| expect.any(Function), | ||
| ); | ||
| }); | ||
|
|
||
| it("flush() resolves immediately when there are no sends", async () => { | ||
| const client = new LambdaDogStatsD(); | ||
| await expect(client.flush()).resolves.toBeUndefined(); | ||
| }); | ||
|
|
||
| it("flush() times out if a send never invokes its callback", async () => { | ||
| // replace socket.send with a never‐calling callback | ||
| (dgram.createSocket as jest.Mock).mockReturnValue({ | ||
| send: jest.fn(), // never calls callback | ||
| getSendBufferSize: jest.fn(), | ||
| setSendBufferSize: jest.fn(), | ||
| }); | ||
|
|
||
| const client = new LambdaDogStatsD(); | ||
| client.distribution("will", 9); | ||
|
|
||
| jest.useFakeTimers(); | ||
| const p = client.flush(); | ||
| // advance past the 1000ms MAX_FLUSH_TIMEOUT | ||
| jest.advanceTimersByTime(1100); | ||
|
|
||
| // expect the Promise returned by flush() to resolve successfully | ||
| await expect(p).resolves.toBeUndefined(); | ||
| jest.useRealTimers(); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
| @@ -0,0 +1,92 @@ | ||||||
| import * as dgram from "node:dgram"; | ||||||
| import { SocketType } from "node:dgram"; | ||||||
| import { logDebug } from "../utils"; | ||||||
|
|
||||||
| export class LambdaDogStatsD { | ||||||
| private static readonly HOST = "localhost"; | ||||||
| private static readonly PORT = 8125; | ||||||
| private static readonly MIN_SEND_BUFFER_SIZE = 32 * 1024; | ||||||
| private static readonly ENCODING: BufferEncoding = "utf8"; | ||||||
| private static readonly SOCKET_TYPE: SocketType = "udp4"; | ||||||
| private static readonly TAG_RE = /[^\w\d_\-:\/\.]/gu; | ||||||
| private static readonly TAG_SUB = "_"; | ||||||
| // The maximum amount to wait while flushing pending sends, so we don't block forever. | ||||||
| private static readonly MAX_FLUSH_TIMEOUT = 1000; | ||||||
|
|
||||||
| private readonly socket: dgram.Socket; | ||||||
| private readonly pendingSends = new Set<Promise<void>>(); | ||||||
|
|
||||||
| constructor() { | ||||||
| this.socket = dgram.createSocket(LambdaDogStatsD.SOCKET_TYPE); | ||||||
| LambdaDogStatsD.ensureMinSendBufferSize(this.socket); | ||||||
| } | ||||||
|
|
||||||
| private static ensureMinSendBufferSize(sock: dgram.Socket): void { | ||||||
| if (process.platform === "win32") { | ||||||
| return; | ||||||
| } | ||||||
|
|
||||||
| try { | ||||||
| const currentSize = sock.getSendBufferSize(); | ||||||
| if (currentSize <= LambdaDogStatsD.MIN_SEND_BUFFER_SIZE) { | ||||||
| sock.setSendBufferSize(LambdaDogStatsD.MIN_SEND_BUFFER_SIZE); | ||||||
| logDebug(`Socket send buffer increased to ${LambdaDogStatsD.MIN_SEND_BUFFER_SIZE / 1024}kb`); | ||||||
| } | ||||||
| } catch { | ||||||
| // ignore | ||||||
|
||||||
| } | ||||||
| } | ||||||
|
|
||||||
| /** | ||||||
| * Send a distribution value, optionally setting tags and timestamp. | ||||||
| * Timestamp is seconds since epoch. | ||||||
| */ | ||||||
| public distribution(metric: string, value: number, timestamp?: number, tags?: string[]): void { | ||||||
| this.report(metric, "d", value, tags, timestamp); | ||||||
| } | ||||||
|
|
||||||
| private normalizeTags(tags: string[]): string[] { | ||||||
| return tags.map((t) => t.replace(LambdaDogStatsD.TAG_RE, LambdaDogStatsD.TAG_SUB)); | ||||||
| } | ||||||
|
|
||||||
| private report(metric: string, metricType: string, value: number | null, tags?: string[], timestamp?: number): void { | ||||||
| if (value == null) { | ||||||
| return; | ||||||
| } | ||||||
| const serializedTags = tags && tags.length ? `|#${this.normalizeTags(tags).join(",")}` : ""; | ||||||
| const timeStampPart = timestamp != null ? `|T${timestamp}` : ""; | ||||||
|
||||||
| const timeStampPart = timestamp != null ? `|T${timestamp}` : ""; | |
| const timestampPart = timestamp != null ? `|T${timestamp}` : ""; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Maybe we set this to
127.0.0.1instead oflocalhost, for safety