Skip to content

Instantly share code, notes, and snippets.

@maxpert
Last active October 16, 2022 22:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maxpert/d50a49dfb2f307b30b7cae841c9607e1 to your computer and use it in GitHub Desktop.
Save maxpert/d50a49dfb2f307b30b7cae841c9607e1 to your computer and use it in GitHub Desktop.
Marmot Scripts

A very simple log stream watcher for Marmot (supports ZSTD, CBOR, and basic auth for NATS)

Usage

deno run --allow-net https://gist.githubusercontent.com/maxpert/d50a49dfb2f307b30b7cae841c9607e1/raw/6d30803c140b0ba602545c1c0878d3394be548c3/watch-marmot-change-logs.ts -u <nats_username> -p <nats_password> -s <comma_seperated_server_list>

MIT License

Copyright (c) 2022 Zohaib Sibte Hassan

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

import * as cbor from "https://deno.land/x/cbor@v1.4.1/index.js";
import * as nats from "https://deno.land/x/nats@v1.8.0/src/mod.ts";
import * as zstd from "https://deno.land/x/zstd_wasm@0.0.16/deno/zstd.ts";
import * as cli from "https://deno.land/x/args@2.1.1/index.ts";
import { crayon } from "https://deno.land/x/crayon@3.3.2/mod.ts";
const argsParser = cli.
args.
describe('Marmot watcher').
with(
cli.EarlyExitFlag('help', {
describe: 'Show help',
exit() {
console.log(argsParser.help());
return Deno.exit();
},
}),
).
with(
cli.PartialOption('compressed', {
describe: "Stream messages are zstd compressed",
alias: ["c"],
default: "true",
type: cli.values.Text
})
).
with(
cli.PartialOption('username', {
describe: "Username for NATS stream",
alias: ["u"],
default: undefined,
type: cli.values.Text
})
).
with(
cli.PartialOption('password', {
describe: "Password for NATS stream",
alias: ["p"],
default: undefined,
type: cli.values.Text
})
).
with(
cli.PartialOption('servers', {
describe: "NATS server URL",
alias: ["s"],
default: "localhost:4222",
type: cli.values.Text
})
).
with(
cli.PartialOption('prefix', {
describe: "Prefix for marmot subjects",
default: "marmot-change-log-",
type: cli.values.Text
})
);
interface MarmotPublishedRow {
FromNodeId: number;
Payload: {
Id: number;
Type: "insert" | "update" | "delete";
TableName: string;
// deno-lint-ignore no-explicit-any
Row: {[ColumnName: string]: any}
};
}
export class MarmotStreamListener {
#nc: nats.NatsConnection | null = null;
#jsm: nats.JetStreamManager | null = null;
async connect(serverConfig: nats.ConnectionOptions) {
this.#nc = await nats.connect(serverConfig);
this.#jsm = await this.#nc.jetstreamManager();
}
async subjects(prefix: string): Promise<string[]> {
const streams = await this.#jsm?.streams.list().next();
if (!streams) {
return [];
}
return streams.map(c => c.config.subjects).
filter(s => s.length == 1 && s[0].startsWith(prefix)).
flatMap(s => s);
}
async streams(): Promise<nats.StreamInfo[] | undefined> {
return await this.#jsm?.streams.list().next();
}
async subscribe(subj: string): Promise<nats.Subscription | undefined> {
return await this.#nc?.subscribe(subj);
}
}
function onStreamMessage(m: nats.Msg) {
try {
let data: Uint8Array|ArrayBuffer = m.data;
if (cliArgs.value?.compressed === "true") {
data = zstd.decompress(data);
}
const payload = cbor.decode(data) as MarmotPublishedRow;
const tupleString = Object.entries(payload.Payload.Row).sort((a, b) => {
if (a[0] < b[0]) return -1;
if (a[0] > b[0]) return 1;
return 0;
}).map(([k, v]) => {
if (typeof v === 'bigint') {
v = v.toString();
}
return `${k}=${JSON.stringify(v)}`;
}).join(" ");
console.log(
crayon.cyan("🖥️ ", payload.FromNodeId),
crayon.lightBlue("📨", m.subject),
crayon.lightGreen("⚡", payload.Payload.TableName),
crayon.lightRed("🔹", payload.Payload.Type),
crayon.lightWhite("▶️ ", tupleString),
);
} catch(e) {
console.error(e);
}
}
const cliArgs = argsParser.parse(Deno.args);
async function main() {
const natsConfig = {
user: cliArgs.value?.username,
pass: cliArgs.value?.password,
servers: cliArgs.value?.servers.split(",").map(s => s.trim()) || "localhost:4222",
};
console.log(" 🚀 Connecting to server ", natsConfig);
const mst = new MarmotStreamListener();
await mst.connect(natsConfig);
const subs = await mst.subjects(cliArgs.value?.prefix || "marmot-change-log");
console.log(crayon.lightYellow(" 🤙 Starting subscription"), subs);
const promises = subs.map(sub => mst.subscribe(sub)).map(async sub => {
const strm = await sub;
if (!strm) {
return () => Promise.reject();
}
return (async () => {
for await (const m of strm) {
onStreamMessage(m);
}
})();
});
Promise.any(promises);
}
// Learn more at https://deno.land/manual/examples/module_metadata#concepts
if (import.meta.main) {
if (cliArgs.error) {
console.error('Failed to parse CLI arguments');
console.error(cliArgs.error.toString());
Deno.exit(1);
}
await zstd.init();
await main();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment