<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[WatchIreshStruggle]]></title><description><![CDATA[I build things because reading the docs seemed harder. Technical deep-dives on AI agents, streaming servers, and other rabbit holes I fell into and refused to c]]></description><link>https://blog.iresharma.com</link><generator>RSS for Node</generator><lastBuildDate>Sun, 15 Nov 2026 20:59:58 GMT</lastBuildDate><atom:link href="https://blog.iresharma.com/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Don’t make the model pay 200 lines to find a function]]></title><description><![CDATA[Coding agents still read like find | cat: dump the tree, grep wide, page 200-line windows until context is landfill. Codeloom’s engine makes reading a cost…]]></description><link>https://blog.iresharma.com/system-one-assiting-llms</link><guid isPermaLink="true">https://blog.iresharma.com/system-one-assiting-llms</guid><category><![CDATA[jev]]></category><category><![CDATA[typesafe api]]></category><category><![CDATA[Harness]]></category><dc:creator><![CDATA[Iresh Sharma]]></dc:creator><pubDate>Mon, 21 Sep 2026 18:30:38 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/5f4676819b597625e2dec1dc/91ccf891-11bc-432d-a934-b225a3840497.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Coding agents still read like <code>find | cat</code>: dump the tree, grep wide, page 200-line windows until context is landfill. Codeloom’s engine makes reading a <strong>cost hierarchy</strong>, then puts TypeSafe System One (<code>jev-latest</code>) on a few choke points.</p>
<p><strong>The LLM generates. TypeSafe (JEV) judges. Code decides.</strong></p>
<p>JEV never writes a query, invents a path, or authors an edit.</p>
<h3>Who reads</h3>
<p>The user talks to the <strong>orchestrator</strong>. It has no <code>list_files</code> / <code>search</code> / <code>read_file</code>. <code>ask</code> is the reader. <code>coder</code> <code>read_file</code>s before an edit — that is a write-funnel stamp, not discovery.</p>
<img src="https://cdn.hashnode.com/uploads/covers/5f4676819b597625e2dec1dc/6e127cc9-b064-41b2-9ffa-5ca471926abd.png" alt="" style="display:block;margin:0 auto" />

<hr />
<h2>Cheaper-first ladder</h2>
<p>Prompt policy, not a hard state machine. Tool descriptions push the same order.</p>
<img src="https://cdn.hashnode.com/uploads/covers/5f4676819b597625e2dec1dc/235c5873-5832-49ce-9c47-ffc9e4f872e4.png" alt="" style="display:block;margin:0 auto" />

<table>
<thead>
<tr>
<th>Step</th>
<th>Tool</th>
<th>Cost</th>
<th>Why it exists</th>
</tr>
</thead>
<tbody><tr>
<td>Locate</td>
<td><code>search</code></td>
<td>rg, 10s cap, skip-dirs</td>
<td>Prefer this over listing</td>
</tr>
<tr>
<td>Locate (last)</td>
<td><code>list_files</code></td>
<td>flatten whole tree</td>
<td>Model tends to dump; prompt says don’t</td>
</tr>
<tr>
<td>Outline</td>
<td><code>list_symbols</code></td>
<td>one parse, no LSP</td>
<td>See a file without reading it</td>
</tr>
<tr>
<td>One def</td>
<td><code>find_symbol</code></td>
<td>same parse</td>
<td>Body + coordinate handoff</td>
</tr>
<tr>
<td>Local CST</td>
<td><code>query_tree</code> / <code>get_node_at</code> / <code>parse_file</code></td>
<td>instant</td>
<td>Imports, calls, nesting</td>
</tr>
<tr>
<td>Types</td>
<td>LSP</td>
<td>server wait</td>
<td>Cross-file truth; fall back to sitter</td>
</tr>
<tr>
<td>Context</td>
<td><code>read_file</code></td>
<td>200–400 numbered lines</td>
<td>Surrounding source + write stamp</td>
</tr>
</tbody></table>
<p><code>coder</code>: skip search. Read the briefing’s paths. Search once only if a path is missing.</p>
<hr />
<h2>JEV in one table</h2>
<p>~100ms calibrated classifier. One <code>state</code> + N parallel questions. Missing key / timeout / 5xx → <code>None</code> → pre-judge path. Engine works without it.</p>
<table>
<thead>
<tr>
<th>Primitive</th>
<th>Returns</th>
<th>Read-path use</th>
</tr>
</thead>
<tbody><tr>
<td><code>Noul</code></td>
<td>P(yes) 0–1</td>
<td>injection? answers the question?</td>
</tr>
<tr>
<td><code>Choice</code></td>
<td>option + per-option P</td>
<td>which rg hit? what intent?</td>
</tr>
<tr>
<td><code>Score</code></td>
<td>ordinal</td>
<td>mostly exec blast radius, not reads</td>
</tr>
</tbody></table>
<p><strong>Judgments only add restriction or information.</strong> They never override <code>guard_write_path</code>, the syntax gate, staleness, or the write denylist.</p>
<p>Modes: <code>off</code> / <code>advisory</code> (events only) / <code>enforcing</code>. Per-site overrides (<code>ENGINE_JUDGE_SEARCH</code>, <code>_SCREEN</code>, <code>_INTENT</code>, …). Write gate does <strong>not</strong> inherit a blanket <code>enforcing</code>.</p>
<h2>Judged read path</h2>
<img src="https://cdn.hashnode.com/uploads/covers/5f4676819b597625e2dec1dc/5c56a825-fdc5-4897-9102-5cf6b22fe9d7.png" alt="" style="display:block;margin:0 auto" />

<p>Child reports (<code>[agent ask … finished]</code>) skip this. Injecting <code>search</code> into orch history — orch has no FS tools — stalled the model.</p>
<h3>Four call sites on reads</h3>
<img src="https://cdn.hashnode.com/uploads/covers/5f4676819b597625e2dec1dc/03ce753e-a0b6-4ea9-8e5d-5fced2fb6de4.png" alt="" style="display:block;margin:0 auto" />

<table>
<thead>
<tr>
<th>Tag</th>
<th>When</th>
<th>Question</th>
<th>Enforcing effect</th>
</tr>
</thead>
<tbody><tr>
<td><code>intent_route</code></td>
<td>before the loop</td>
<td>meta / locate / edit / execute</td>
<td>skip loop, or bump turns</td>
</tr>
<tr>
<td><code>search_rerank</code></td>
<td>rg hits &gt; 10</td>
<td>which line answers the query?</td>
<td>return top 15, not 80</td>
</tr>
<tr>
<td><code>intent_route</code> (gate)</td>
<td>after 2 windows</td>
<td>does gathered context answer it?</td>
<td>seed history or fall through</td>
</tr>
<tr>
<td><code>call_verify</code></td>
<td>LSP / edits, not search/read</td>
<td>coords from <code>find_symbol</code>? path was read?</td>
<td>error string, don’t run</td>
</tr>
<tr>
<td><code>result_screen</code></td>
<td>large tool results</td>
<td>instruction / override / secrets / ordinary code?</td>
<td>flag wrap, or redact secrets</td>
</tr>
</tbody></table>
<p><code>list_files</code> is never verified or screened. Cheap to get wrong, cheap to retry.</p>
<h3>Search re-rank</h3>
<img src="https://cdn.hashnode.com/uploads/covers/5f4676819b597625e2dec1dc/73f128b3-6a14-4b3b-baaf-2d22f52b1338.png" alt="" style="display:block;margin:0 auto" />

<p>One Choice scores every candidate. A lexical miss that the model then <code>read_file</code>s is 200 lines and a round trip.</p>
<h3>Result screen</h3>
<table>
<thead>
<tr>
<th>Signal</th>
<th>Role</th>
</tr>
</thead>
<tbody><tr>
<td><code>contains_instruction_to_agent</code></td>
<td>hazard</td>
</tr>
<tr>
<td><code>attempts_override</code></td>
<td>hazard</td>
</tr>
<tr>
<td><code>requests_secret_disclosure</code></td>
<td>redact if high</td>
</tr>
<tr>
<td><code>is_ordinary_source_code</code></td>
<td>false-positive brake</td>
</tr>
</tbody></table>
<p>This repo is full of prompt strings. Hazard high <strong>and</strong> ordinary low → wrap, don’t strip. Only the first 4k chars are judged.</p>
<hr />
<h2><code>read_file</code> itself</h2>
<img src="https://cdn.hashnode.com/uploads/covers/5f4676819b597625e2dec1dc/71628802-990f-4b4f-9203-6cd2cd365d8e.png" alt="" style="display:block;margin:0 auto" />

<p>Edit without that stamp: <code>error: read X before editing it</code>. Sha drift: read again.</p>
<hr />
<h2>Other personalities</h2>
<table>
<thead>
<tr>
<th>Profile</th>
<th>First read</th>
</tr>
</thead>
<tbody><tr>
<td><strong>ask</strong></td>
<td>Full ladder</td>
</tr>
<tr>
<td><strong>coder</strong></td>
<td><code>read_file</code> named paths</td>
</tr>
<tr>
<td><strong>debugger</strong></td>
<td>Same NAV + shell/git/browser. Don’t stop at the first filename.</td>
</tr>
<tr>
<td><strong>reviewer</strong></td>
<td><code>git_diff</code> in the writer’s worktree, then sitter/LSP on <strong>changed</strong> files</td>
</tr>
<tr>
<td><strong>researcher</strong></td>
<td>Remote first. Workspace search only after external facts</td>
</tr>
<tr>
<td><strong>tester</strong></td>
<td>Read code under test, then write tests</td>
</tr>
</tbody></table>
<hr />
<h2>Pros</h2>
<table>
<thead>
<tr>
<th></th>
<th></th>
</tr>
</thead>
<tbody><tr>
<td>Right model for a choke point</td>
<td>Classifier over closed sets. Cannot hallucinate a path.</td>
</tr>
<tr>
<td>Restriction-only</td>
<td>Cannot punch through deterministic write/exec guards.</td>
</tr>
<tr>
<td>Optional</td>
<td>No key / <code>None</code> verdict = old behaviour. Tests assert that.</td>
</tr>
<tr>
<td>Search re-rank is asymmetric</td>
<td>~100ms vs N wasted <code>read_file</code>s. Biggest quality-per-turn lever.</td>
</tr>
<tr>
<td>Screening closes a real hole</td>
<td>File contents and stdout used to enter context unscreened (80k cap).</td>
</tr>
<tr>
<td>Locate can delete 5–6 tool rounds</td>
<td>Model still writes the answer; it skips exploration.</td>
</tr>
<tr>
<td>Decisions are code</td>
<td>Thresholds in <code>judge_decisions.py</code>. Pure functions. Tunable.</td>
</tr>
<tr>
<td>Observable</td>
<td><code>JudgementMade</code>: tag, signals, enforced?, latency.</td>
</tr>
</tbody></table>
<hr />
<h2>Cons</h2>
<table>
<thead>
<tr>
<th></th>
<th></th>
</tr>
</thead>
<tbody><tr>
<td>Not ground truth</td>
<td>Parser/LSP beat a probability on syntax and types.</td>
</tr>
<tr>
<td>Cannot generate queries</td>
<td>Locate pattern = stopword-stripped identifiers. “How does auth work?” may miss <code>authenticate</code>.</td>
</tr>
<tr>
<td>Confidence compounds</td>
<td>0.9⁴ ≈ 0.66. Resolver stopped before <code>list_symbols</code> → <code>find_symbol</code>. Fall through often, be right when you don’t.</td>
</tr>
<tr>
<td>Latency vs the brochure</td>
<td>Timeout 800ms. Screen fires on every large result. Fall-through pays classify <strong>and</strong> still runs <code>ask</code>. Advisory pays for nothing.</td>
</tr>
<tr>
<td>False positives already happened</td>
<td><code>git status</code> scored as huge blast radius (it <em>observes</em> the repo). Prompt files need the ordinary-code brake. Thresholds are first guesses.</td>
</tr>
<tr>
<td>Orch / resolver clash</td>
<td>Orch has no FS tools. Seeding <code>search</code> into orch already stalled a turn. Inbox handoffs had to be excluded.</td>
</tr>
<tr>
<td>Knob sprawl</td>
<td>Global mode + ~10 site overrides. Write gate refuses to inherit <code>enforcing</code>. Correct, and not “turn the judge on.”</td>
</tr>
<tr>
<td>Extra vendor on the hot path</td>
<td>Key, cost, 800ms tail of no-ops. Cache (512) helps re-reads, not first reads.</td>
</tr>
<tr>
<td>Gaps on the read path</td>
<td>No <code>list_symbols</code> re-rank. Verify does not run on <code>search</code>/<code>read_file</code>. JEV will not stop <code>list_files</code> first — that’s still a prompt.</td>
</tr>
<tr>
<td>Screen is windowed</td>
<td>Injection after char 4000 is out of scope.</td>
</tr>
</tbody></table>
<hr />
<h2>The split worth keeping</h2>
<table>
<thead>
<tr>
<th>Enumerable (JEV can pick)</th>
<th>Not enumerable (LLM must generate)</th>
</tr>
</thead>
<tbody><tr>
<td><code>read_file</code> given a known path</td>
<td><code>search</code> query</td>
</tr>
<tr>
<td><code>find_symbol</code> given a name from the outline</td>
<td><code>str_replace</code> / patch body</td>
</tr>
<tr>
<td><code>goto_definition</code> given <code>find_symbol</code> coords</td>
<td><code>run_command</code></td>
</tr>
</tbody></table>
<p><strong>Navigation can stop being an agent. Editing cannot.</strong></p>
<p>Ship each site <code>advisory</code> until the false-positive rate is a number. Let JEV reorder rg and flag hostile bytes. Do not let it invent the next path.</p>
]]></content:encoded></item><item><title><![CDATA[Trimming the Fat, Not the Signal]]></title><description><![CDATA[Context Engineering in codeloom.engine]]></description><link>https://blog.iresharma.com/context-engineering</link><guid isPermaLink="true">https://blog.iresharma.com/context-engineering</guid><category><![CDATA[context engineering]]></category><category><![CDATA[codex]]></category><category><![CDATA[claude]]></category><category><![CDATA[openrouter]]></category><category><![CDATA[harnessengineering]]></category><dc:creator><![CDATA[Iresh Sharma]]></dc:creator><pubDate>Thu, 10 Sep 2026 02:08:55 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/5f4676819b597625e2dec1dc/000d0897-04c1-4343-b00d-e21bcbfd9fb5.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Most writing about coding agents focuses on the loop: call the model, run its tools, feed results back, repeat. <a href="https://engine.codeloom.iresharma.com">codeloom.engine</a>'s loop is deliberately unremarkable — an OpenAI-style tool-calling loop with a turn cap. The real engineering is in what enters the model's context, what's kept out, and how tool results are shaped.</p>
<p>The engine itself is a headless backend: a long-lived Python process bound to a single workspace, speaking newline-delimited JSON over a Unix socket, exposing 24 tools backed by tree-sitter (syntax) and LSP (types). Clients never touch agent internals — just commands and events. The core idea: context window is a budget, and every byte spent on stale, oversized, or unactionable content is wasted.</p>
<p>The three ways context rots</p>
<p>It fills with output no longer needed — an old search result, a file window read once for a function name, a diff for an edit since undone. It accumulates claims that are no longer true — the model read auth.py at turn 3, a rename touched it at turn 9, but the model still "remembers" the old version. It receives results it can't act on — a full traceback where one line would do, or a hallucinated-argument TypeError.</p>
<p>Every decision below targets one or more of these. Together they form a funnel: disk → tool-level caps → registry cap (80k chars) → history → compactor (120k token budget) → model.</p>
<ol>
<li>Caps at the source, a fuse at the registry Tool ceilings are tuned per tool:</li>
</ol>
<p>Tool / surface Limit read_file window 200 lines default, 400 max search (ripgrep) 80 matches default, 200 max find_references / goto_definition / document_symbols 50 / 20 / 200 query_tree captures 80 parse_file 200 nodes, depth 8 Diff in a tool result 4,000 characters run_command output 30k per stream, 60k total Any tool result reaching the model 80,000 characters (registry)</p>
<p>Tool-level caps shape the result (e.g., read_file returns a numbered, page-able window; hitting search's cap signals "narrow the query"). The registry cap is a backstop that should rarely fire — it exists so a misbehaving tool can't flood context alone.</p>
<p>Two smaller but easy-to-miss decisions: the read window and edit window share one coordinate system — read_file gives 1-based numbered lines, and replace_lines/insert_at_line take matching 1-based ranges, eliminating an off-by-one bug class. And the model gets a truncated diff (≤4,000 chars, enough to confirm the edit landed) while the client gets the full diff via a FileEdited event — different audiences, different payloads.</p>
<ol>
<li>A cost hierarchy written into the system prompt The prompt tells the model the order to spend its budget: search/list_files to locate a file → list_symbols to see what's in it → find_symbol for a definition's source (which also returns its 1-based line/character position) → that position feeds goto_definition, find_references, or hover → get_diagnostics for errors → read_file windows only when surrounding context is truly needed.</li>
</ol>
<p>This is a cost gradient: tree-sitter tools are instant, need no server, and work on broken files; LSP tools are authoritative but costlier; read_file is most expensive per unit of information since most of a window is usually irrelevant. The hinge is find_symbol returning a coordinate directly — in many harnesses, getting from "the function is called X" to querying the LSP requires reading the file first to find the line number. Here that step is skipped entirely: one fewer read, one fewer turn, hundreds fewer lines in context.</p>
<p>The prompt also states an editing contract the runtime enforces anyway (read before editing, use str_replace with unique surrounding text, use rename_symbol not search-and-replace, use undo_edit on mistakes) — stating rules the runtime enforces means the model learns them once, not through repeated refusals.</p>
<ol>
<li>Failures are messages, not exceptions An aborted turn is the costliest thing that can happen to context. If any turn raises, history rolls back to a pre-message marker, leaving no partial state — but the bigger point is how rarely that's needed, since almost every failure becomes a readable string instead:</li>
</ol>
<p>A throwing tool returns error: {message} instead of propagating. Hallucinated arguments that don't match a tool's signature are dropped, not raised as TypeError. A None return becomes an empty string. str_replace refuses on zero or multiple matches rather than guessing. apply_patch tolerates up to five lines of line-number drift per hunk, but any failing hunk rejects the whole patch — a clean failure, never a half-applied one. Editing an unread file yields "read {path} before editing it." Editing a file changed on disk since it was read yields "{path} changed on disk since you read it." The syntax gate rejects edits that introduce new tree-sitter ERROR/MISSING nodes (but not edits to already-broken files — otherwise the agent could never fix one). undo_edit refuses if the file's current hash no longer matches the journaled post-edit hash.</p>
<p>Every case is a one-line instruction telling the model what to do next (re-read, narrow, fix syntax, back off). The turn continues — the 16-turn budget goes to recovery, not to re-establishing context from scratch.</p>
<ol>
<li><p>Feedback arrives inside the same tool result After a committed write, the engine resyncs the language server (pushing a didChange when the on-disk SHA moved), waits briefly for fresh diagnostics, and appends any new diagnostics to that same tool result — so the model learns about a type error it just introduced without spending a turn on get_diagnostics. This is filtered to a short delta, not the full diagnostic list. Same principle for run_command: a non-zero exit is reported as information, not failure; stdout/stderr stream live to clients while the model gets capped, complete output at the end.</p>
</li>
<li><p>History is curated, not appended</p>
</li>
</ol>
<p>Tool messages aren't rehydrated on resume. hydrate() replays only user/assistant messages; tool results are dropped since they're stale workspace snapshots. Cost: the model re-reads files it already saw. The engine judges correctness worth the tokens. The FileTracker resets on every session bind. A resumed session starts with no assumptions about disk state, reinforcing the read-before-edit rule — two independent mechanisms both rebuild the model's picture of the workspace from disk, not memory. Model and client see different representations. Tool messages go to clients as 400-character previews plus structured ToolCallStarted/ToolCallFinished events for UI traces; the model gets the full capped result. Durable memory lives outside the window. {workspace}/.engine/context.md is long-term memory appended across sessions — a home for things summarization would otherwise lose. Only necessary state is persisted. Sessions save to SQLite after each message/edit, but file tree, git state, and detected language are stripped before writing since they're recomputed from disk on load — stale derived state never gets trusted.</p>
<ol>
<li>Compaction as an explicit, observable state At a 120,000-token budget (ENGINE_CONTEXT_BUDGET), history goes to agents/compactor.py, which handles tool-result trimming, summarization, and overflow detection — a tiered strategy: trim old tool results first (cheapest, least valuable post-use), summarize when trimming isn't enough, and mark overflow explicitly rather than silently dropping content. A history-invariant test suggests the compactor must keep tool calls and results paired in a format the API will accept.</li>
</ol>
<p>Two things matter more than the algorithm itself:</p>
<p>Compaction is a state, not a side effect — AgentStateChanged includes compacting alongside thinking, calling_tool, waiting_for_user, aborting, so a client can show the user the agent is compressing memory. Compaction is reported — a ContextCompacted event carries the strategy, counts, and summary that replaced trimmed history. The difference between an agent that mysteriously forgets and one that says what it forgot; also makes compaction debuggable externally.</p>
<p>StatsUpdated streams token counts, cost, and elapsed time after each exchange — the budget is visible on the wire, not hidden.</p>
<ol>
<li>The response path is budgeted too Output gets the same discipline as input:</li>
</ol>
<p>Streaming with canonical fallback — ChatMessageStarted opens a message, ChatMessageDelta streams incremental text, ChatMessageAdded follows as the complete canonical version. Clients that miss deltas still land on the right message. Deltas are droppable; canonical messages aren't — each client has a bounded event queue (4,096 items / 1 MiB) with a delta-drop policy; a slow client loses smoothness, never correctness. Oversized events are replaced, not truncated — a 512 KiB per-event soft limit and 8 MiB stream fuse mean an oversized event becomes an ErrorOccurred rather than corrupting the NDJSON stream. Snapshots stream their history — SnapshotReady ships with messages emptied and a message_count for instant UI sizing; history replays as individual ChatHistoryAdded events from a background task, with a generation counter to cancel stale replays.</p>
<p>Trade-offs worth naming</p>
<p>Static caps push work into the prompt — if the 51st reference mattered, the model must notice and re-query narrower. Dropping tool messages on resume costs tokens — the right default for a coding agent, but not free. Summarization is lossy — context.md mitigates this, but nothing prevents it from growing into its own context problem over many sessions. The 16-turn cap is tight for large refactors — rename_symbol's server-computed, batched rename across files is the main lever for staying inside it. The 120k-token budget is a heuristic, assuming headroom above it and a token estimate close enough to the provider's actual tokenizer.</p>
<p>What to take from it</p>
<p>Cap at the tool, then again at the registry — the first shapes, the second protects. Give the model a cost gradient with coordinate handoffs from cheap structural tools to expensive semantic ones. Convert every failure into a one-line instruction — an error string keeps the turn alive; an exception resets it. Put the consequences of an action inside its own result (new diagnostics after a write, a capped diff, exit code as information). Treat history as a curated document — roll back failed turns, drop stale results on resume, keep durable memory outside the window. Make compaction a state with a report, so forgetting is visible, not mysterious. Budget the output path with the same rigor as the input path.</p>
<p>The engine's README frames its architecture as a hard boundary: clients speak JSON, nothing else crosses the line. These context decisions form a second, less visible boundary — between what the workspace actually contains and what the model is allowed to believe about it.</p>
]]></content:encoded></item><item><title><![CDATA[Why a Coding Agent Needs Three Different Ways to "Read" Code]]></title><description><![CDATA[Tree-sitter vs LSP: why AI coding agents need both fast local symbol lookup and deep project-wide intelligence to understand real codebases.]]></description><link>https://blog.iresharma.com/why-a-coding-agent-needs-three-different-ways-to-read-code</link><guid isPermaLink="true">https://blog.iresharma.com/why-a-coding-agent-needs-three-different-ways-to-read-code</guid><category><![CDATA[llm]]></category><category><![CDATA[claude]]></category><category><![CDATA[claude-code]]></category><category><![CDATA[codex]]></category><category><![CDATA[tools]]></category><dc:creator><![CDATA[Iresh Sharma]]></dc:creator><pubDate>Tue, 18 Aug 2026 11:41:21 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/5f4676819b597625e2dec1dc/3ccb0ff9-4e86-4cac-9723-0828f0c3d1c8.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>If you're building something like Devin, an agent that goes end-to-end from a task description to a working code change. The very first problem you hit isn't code generation. It's <em>comprehension</em>. Before an agent can safely touch a codebase, it has to be able to answer basic questions: Where is this function defined? What calls it? What does it return? Is this file even valid right now?</p>
<p>The instinct is to just hand the model <code>read_file</code> and let it grep around. That works for a five-file toy project. It falls over immediately on anything real the model burns its context window reading whole files to find one function, and it has no way to know that the <code>parse_config</code> it just read is a <em>different</em> <code>parse_config</code> than the one being called three directories away.</p>
<p>This experiment tackles that problem with two tools that sound similar but do fundamentally different jobs: <strong>tree-sitter</strong> and the <strong>Language Server Protocol (LSP)</strong>. Here's the reasoning behind using both, not just one.</p>
<h2>Tree-sitter: fast, local, and doesn't need to know your project</h2>
<p>Tree-sitter's job in this script is narrow: given a file and a symbol name, parse just that file into a syntax tree and find the node whose name matches. That's <code>find_symbol</code>. Under the hood it's simple parse the file's bytes into an AST with the right grammar (<code>tree_sitter_python</code>, <code>_go</code>, <code>_javascript</code>, <code>_typescript</code>), walk the tree looking for definition-shaped nodes (<code>function_definition</code>, <code>class_declaration</code>, <code>method_definition</code>, etc.), and compare each candidate's name field against the string the agent asked for.</p>
<p>The reason this tool exists at all, alongside a full language server, comes down to <strong>cost and availability</strong>:</p>
<ul>
<li><p><strong>It's instant.</strong> No subprocess, no protocol handshake, no project-wide indexing. Parsing one file with tree-sitter takes milliseconds. Spinning up <code>gopls</code> or <code>pyright</code> and waiting for it to build a full workspace model does not.</p>
</li>
<li><p><strong>It doesn't need the rest of the project to be coherent.</strong> A tree-sitter parse only needs valid-ish syntax in <em>this file</em>. It works before dependencies are installed, before <code>gopls</code> has finished indexing, even inside a codebase with broken imports elsewhere.</p>
</li>
<li><p><strong>It gives the agent a foothold for everything else.</strong> This is the more interesting design choice: <code>find_symbol</code> doesn't just return source code. It returns the <strong>1-based line/character position of the symbol's name</strong>, specifically so that position can be fed straight into <code>goto_definition</code>, <code>find_references</code>, or <code>hover</code> without a separate lookup step. That's a small detail, but it matters LSP calls are positional (a line/column in a file), and models are bad at counting characters by eye from a text dump. Tree-sitter becomes the thing that hands the model <em>correct coordinates</em> to hand back to the LSP.</p>
</li>
</ul>
<p>Notice also what tree-sitter deliberately <em>doesn't</em> try to do: cross-file resolution. It can't tell you that the <code>Client</code> class used in <code>handlers.py</code> is actually imported from <code>client/base.py</code>. That's not a limitation to work around — it's the boundary that defines why the LSP is there too.</p>
<h2>LSP: slow to start, but it actually understands the project</h2>
<p>The four LSP-backed tools — <code>goto_definition</code>, <code>find_references</code>, <code>hover</code>, <code>get_diagnostics</code> — exist for exactly the question tree-sitter can't answer: <em>how does this symbol relate to the rest of the codebase?</em></p>
<p>This is where most of the script's complexity lives, and it's worth explaining why, because "just call the language server" hides a lot of real engineering:</p>
<p><strong>LSP servers are long-running, stateful processes, not stateless functions.</strong> <code>LSPClient</code> spawns something like <code>pyright-langserver --stdio</code> or <code>gopls serve</code> and talks to it over JSON-RPC framed with <code>Content-Length</code> headers on stdin/stdout the same protocol VS Code uses. That process has to be initialized once (<code>initialize</code> → <code>initialized</code> handshake), told about the workspace root, and then kept alive for the life of the session because it's continuously building an in-memory model of the project (symbol tables, import graphs, type inference). Treating it like a one-shot subprocess call would mean re-indexing the whole project on every single query, which is untenable.</p>
<p><strong>Servers talk back, not just respond.</strong> This is why there's a background reader thread and a notification queue instead of a simple request/response wrapper. Diagnostics (<code>textDocument/publishDiagnostics</code>) arrive <em>unprompted</em>, whenever the server feels like re-analyzing a file — not as a reply to a specific request. Some servers (pyright, notably) also make <em>requests back to the client</em>, like <code>workspace/configuration</code>, and will stall indefinitely if nobody answers. The <code>_notification_listener</code> thread and <code>_handle_server_request</code> method exist specifically to keep that conversation alive in both directions while the main thread is free to do other things.</p>
<p><strong>Warm starting is a deliberate latency hedge.</strong> As soon as the sandbox detects a project's primary language (via manifest files like <code>pyproject.toml</code>/<code>go.mod</code>, falling back to extension counts), it kicks off <code>warm_start</code> in a background thread because spawning the server and <code>didOpen</code>-ing up to 500 source files <em>before the agent has asked a single question</em>. The comment in the code makes the reasoning explicit: <code>gopls</code> and <code>pyright</code> both do most of their expensive work (project graph loading, type inference) as a side effect of being told what's open, so the win isn't a special "index everything now" API — there isn't one for <code>typescript-language-server</code> — it's just front-loading that same cost so it overlaps with the agent's early exploration turns instead of blocking the first real query.</p>
<p><strong>Every server is configured slightly differently, and the code doesn't pretend otherwise.</strong> <code>pyright</code> needs an explicit <code>workspace/didChangeConfiguration</code> push to turn on whole-workspace diagnostics instead of open-files-only. <code>gopls</code> doesn't need that because it indexes the whole module by design. <code>typescript-language-server</code> doesn't have a workspace diagnostic mode at all, warm-starting it only buys you a pre-loaded <code>tsserver</code> process. The <code>ServerConfig</code> dataclass and per-language <code>settings</code> dict exist to hold these differences explicitly rather than hard-coding one server's assumptions everywhere.</p>
<p><strong>Coordinates need translating both ways.</strong> Tools are exposed to the model as 1-based line/character, because that's what a human (and apparently a model) naturally reasons about from reading numbered source. LSP itself is 0-based. So every LSP-backed method in <code>Sandbox</code> does the <code>-1</code> on the way in and <code>+1</code> on the way back out — a small but easy-to-get-wrong detail that's worth calling out because it's exactly the kind of bug that would silently point the agent at the wrong line.</p>
<h2>Why not just use one of them?</h2>
<p>Because they answer different questions at different costs, and an agent loop is sensitive to both:</p>
<table>
<thead>
<tr>
<th></th>
<th>Tree-sitter (<code>find_symbol</code>)</th>
<th>LSP (<code>goto_definition</code>, <code>find_references</code>, <code>hover</code>, <code>get_diagnostics</code>)</th>
</tr>
</thead>
<tbody><tr>
<td>Scope</td>
<td>Single file</td>
<td>Whole indexed workspace</td>
</tr>
<tr>
<td>Startup cost</td>
<td>~0</td>
<td>Seconds to tens of seconds (process spawn + indexing)</td>
</tr>
<tr>
<td>Understands imports/types</td>
<td>No</td>
<td>Yes</td>
</tr>
<tr>
<td>Needs project to be "healthy"</td>
<td>No</td>
<td>Mostly no, but benefits from it</td>
</tr>
<tr>
<td>Best for</td>
<td>"I know the name, give me its code and a position"</td>
<td>"Where does this actually come from / who uses this / is this broken"</td>
</tr>
</tbody></table>
<p>The system prompt actually encodes this tradeoff directly for the model: <em>prefer the cheapest tool that answers your question</em>, and reach for LSP specifically when the question is relational rather than local. That's the real design insight here — it's not "LSP is better than tree-sitter" or vice versa, it's that a code-understanding agent needs a cheap <em>local</em> lookup and an expensive <em>global</em> one, and conflating them either wastes tokens re-reading whole files or wastes time and process overhead asking a language server questions a regex could've answered.</p>
<h2>The shape this sets up for the bigger project</h2>
<p>For an end-to-end coding agent, this comprehension layer is the foundation everything else stacks on. You can't safely rename a function, fix a call site, or reason about blast radius without <code>find_references</code>. You can't verify a generated edit didn't break type-checking without <code>get_diagnostics</code>. And you can't afford to have the model read entire files every time it needs one function's body — that's context budget you'll want later for the actual editing and reasoning steps.</p>
<p>Worth flagging as open questions for where this goes next: the diagnostics cache and <code>_opened_files</code> set live in memory for the session, so nothing currently invalidates or re-fetches a file's diagnostics after the agent (eventually) edits it — that'll matter as soon as writing code enters the loop. There's also no <code>textDocument/didChange</code> handling yet, only <code>didOpen</code>, which is fine for a read-only exploration tool but will need to change the moment the agent starts making edits and wants fresh diagnostics without a full re-open.</p>
]]></content:encoded></item><item><title><![CDATA[I never finished Venture Deals, so I built a pipeline to read it for me]]></title><description><![CDATA[I've started Venture Deals three times. I've never finished it. That's not really a discipline problem, it's a format problem. I care about maybe 15% of a…]]></description><link>https://blog.iresharma.com/i-never-finished-venture-deals-so-i-built-a-pipeline-to-read-it-for-me</link><guid isPermaLink="true">https://blog.iresharma.com/i-never-finished-venture-deals-so-i-built-a-pipeline-to-read-it-for-me</guid><category><![CDATA[llm]]></category><category><![CDATA[workflow]]></category><category><![CDATA[claude]]></category><dc:creator><![CDATA[Iresh Sharma]]></dc:creator><pubDate>Fri, 07 Aug 2026 02:16:41 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/5f4676819b597625e2dec1dc/0fc383c1-a30e-4534-b155-f1cdcba7c28c.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>I've started <em>Venture Deals</em> three times. I've never finished it.</p>
<p>That's not really a discipline problem, it's a format problem. I care about maybe 15% of a book like that: the definitions, the mechanics, the market norms, the "here's where founders get burned" warnings. That 15% is smeared across 300 pages of anecdote and connective tissue. I read the way I grep. Books don't grep.</p>
<p>So I did the thing engineers do instead of solving the actual problem. I built a tool.</p>
<p><strong>Lens Distill</strong> takes a PDF plus a free text "topic lens" and turns it into three things:</p>
<ol>
<li><p><strong>Atomic claims.</strong> Self contained paraphrased statements, each citing the exact paragraphs it came from.</p>
</li>
<li><p><strong>A canonical concept vocabulary.</strong> The book's real nouns, normalized and deduplicated.</p>
</li>
<li><p><strong>A sparse concept graph.</strong> Prerequisite, related, and confusable edges between those concepts.</p>
</li>
</ol>
<p>There's a Next.js app wrapped around it so other people can watch it run, but that's just a window. The work is the pipeline, and this post is about the pipeline, mostly about the places it broke. Almost all of them broke <em>quietly</em>.</p>
<h2>Seven stages, one line</h2>
<p>The whole system is a linear job queue. No DAG, no fan out, no orchestration framework, no cron.</p>
<img src="https://cdn.hashnode.com/uploads/covers/5f4676819b597625e2dec1dc/abf33215-d93c-4e31-bd75-db0a184d3f5a.svg" alt="" style="display:block;margin:0 auto" />

<table>
<thead>
<tr>
<th>#</th>
<th>Stage</th>
<th>LLM?</th>
<th>Turns</th>
<th>Into</th>
</tr>
</thead>
<tbody><tr>
<td>0</td>
<td><em>(parse)</em></td>
<td>no</td>
<td>PDF bytes</td>
<td><code>paragraphs</code> with global indices</td>
</tr>
<tr>
<td>1</td>
<td><code>chunk</code></td>
<td>no</td>
<td>paragraphs</td>
<td>~1200 token windows</td>
</tr>
<tr>
<td>2</td>
<td><code>embed</code></td>
<td>embedding model</td>
<td>chunks</td>
<td>1536-d vectors</td>
</tr>
<tr>
<td>3</td>
<td><code>extract</code></td>
<td>Haiku</td>
<td>chunks + persona</td>
<td>cited claims</td>
</tr>
<tr>
<td>4</td>
<td><code>dedupe</code></td>
<td>embeddings + Sonnet</td>
<td>claims</td>
<td>claim clusters, survivors</td>
</tr>
<tr>
<td>5</td>
<td><code>canonicalize</code></td>
<td>embeddings (fallback only)</td>
<td>raw tags</td>
<td><code>raw_tag → canonical_tag</code> map</td>
</tr>
<tr>
<td>6</td>
<td><code>concepts</code></td>
<td>no</td>
<td>canonical tags</td>
<td>graph nodes</td>
</tr>
<tr>
<td>7</td>
<td><code>concept_graph</code></td>
<td>Opus</td>
<td>nodes</td>
<td>typed edges, then <code>ready</code></td>
</tr>
</tbody></table>
<p>Each stage writes its rows and enqueues exactly one next job, or returns <code>null</code> and the book is done. That linearity is a deliberate call. A boring pipeline is a debuggable pipeline: when a book fails there's exactly one place it failed, and that stage's metrics tell you which numbers looked wrong going in.</p>
<p>Everything lives in Neon Postgres with pgvector (1536 dimensions, HNSW cosine indexes on chunk and claim embeddings), Drizzle for the ORM, <code>pdfjs-dist</code> for parsing, <code>js-tiktoken</code> for token counting, the Anthropic SDK direct for the three generative stages, and <code>text-embedding-3-small</code> through OpenRouter.</p>
<h2>Stage 0: PDF structure is the boss fight</h2>
<p>I assumed parsing would be the boring part. It's the riskiest stage in the system and the only one where corruption is completely silent. Everything downstream succeeds. The output is just garbage.</p>
<p>Here's the canonical failure from an earlier version: a book whose headings wrapped across two lines produced <strong>157 detected chapters</strong> instead of 21. Nothing threw. Chunks hard break on chapter boundaries, so chunking produced hundreds of fragments. Extraction ran on fragments and emitted thousands of context free claims. The concept stage built a cloud of junk tags. Ten dollars of tokens later I had a beautiful graph of nothing.</p>
<p>The detection rules that came out of that:</p>
<table>
<thead>
<tr>
<th>Rule</th>
<th>Detail</th>
</tr>
</thead>
<tbody><tr>
<td>Body size</td>
<td>Estimated from line heights across the document</td>
</tr>
<tr>
<td>Chapter candidate</td>
<td>Line height ≥ <strong>1.35x</strong> body, usually first content on a page, followed by body text</td>
</tr>
<tr>
<td>Section candidate</td>
<td>Line height ≥ <strong>1.15x</strong> body</td>
</tr>
<tr>
<td>Wrapped headings</td>
<td>Merged <em>before</em> classification. This is the 157 chapter fix</td>
</tr>
<tr>
<td>Demotion</td>
<td>Any "chapter" with <strong>&lt; 15 paragraphs</strong> becomes a section of the previous chapter</td>
</tr>
<tr>
<td>Headers/footers</td>
<td>Dropped if a normalized key appears on <strong>&gt; 30%</strong> of pages</td>
</tr>
<tr>
<td>Two column</td>
<td>Detected when left/right x-modes are split by a mid page gap</td>
</tr>
</tbody></table>
<p>Then a gate: after demotion, chapter count must land in <strong>[5, 40]</strong> or the upload throws before a cent is spent. A book with 3 chapters or 157 chapters is a book I parsed wrong.</p>
<p><strong>On page numbers, I fail closed.</strong> Printed page numbers and PDF indices disagree constantly. Calibration samples pages and looks for a consistent offset, and I only ship a number when agreement is above <strong>0.8</strong>. In the mid confidence band I store <code>page = null</code>. Not a guess, not best effort, null. The UI never renders an empty page chip either, and citations show chapter instead. A wrong page number is worse than a missing one, because a missing one tells you to go look.</p>
<p>Last thing, and it's the one I'd tattoo somewhere: every paragraph gets a <code>para_index</code> that's <strong>global and monotonic across the whole book</strong>, not per chapter. Primary key is <code>(book_id, para_index)</code>. I did per chapter first. Those indices collide the moment you join across chapters, and the join <em>succeeds</em>. It just hands you the wrong paragraph. Everything looks fine and nothing is fine.</p>
<h2>Stage 1: <code>chunk</code></h2>
<p>No LLM here, just windowing and gates.</p>
<table>
<thead>
<tr>
<th>Constant</th>
<th>Value</th>
</tr>
</thead>
<tbody><tr>
<td><code>TARGET</code></td>
<td>1200 tokens</td>
</tr>
<tr>
<td><code>MIN_TOKENS</code></td>
<td>600</td>
</tr>
<tr>
<td><code>OVERLAP</code></td>
<td>150 tokens</td>
</tr>
<tr>
<td><code>SECTION_SOFT_WINDOW</code></td>
<td>300</td>
</tr>
<tr>
<td><code>MAX_CHUNKS</code></td>
<td>550</td>
</tr>
</tbody></table>
<p>Grow a window by tokens until near target. <strong>Hard break on chapter change.</strong> Prefer a soft cut at a section boundary if the trailing segment would otherwise be stubby. Overlap ~150 tokens when advancing. Merge undersized adjacent same chapter slices if the combined size still fits under target.</p>
<p>Three loud gates:</p>
<ul>
<li><p>Zero chunks throws.</p>
</li>
<li><p>More than 550 chunks throws ("book too large for the demo").</p>
</li>
<li><p><strong>Average tokens below half the target throws.</strong></p>
</li>
</ul>
<p>That last one is the 157 chapter canary. If chapter detection exploded, chunks come out tiny, and I'd rather kill the book here than at the graph stage an hour and several dollars later.</p>
<h2>Stage 2: <code>embed</code></h2>
<table>
<thead>
<tr>
<th></th>
<th></th>
</tr>
</thead>
<tbody><tr>
<td>Batch size</td>
<td>100 chunks per call</td>
</tr>
<tr>
<td>Dimensions</td>
<td>1536</td>
</tr>
<tr>
<td>Input</td>
<td><code>sectionTitle + "\n\n" + text</code> when a section title exists</td>
</tr>
<tr>
<td>Billing</td>
<td>Input tokens only, output always 0</td>
</tr>
</tbody></table>
<p>The thing I got wrong here was conceptual rather than mechanical. There's <strong>one vector per chunk, not per token</strong>. The API tokenizes the string internally and returns a single 1536 dimension vector for the whole thing. Obvious in retrospect, but my usage accounting was recording one "call" per chunk instead of per batch, which inflated the call count 100x and made the cost dashboard nonsense.</p>
<p>The stage processes chunks with null embeddings ordered by index and re-enqueues itself with a cursor if work or time runs out.</p>
<h2>Stage 3: <code>extract</code></h2>
<p>First generative stage, and where the good idea lives.</p>
<table>
<thead>
<tr>
<th></th>
<th></th>
</tr>
</thead>
<tbody><tr>
<td>Model</td>
<td>Haiku</td>
</tr>
<tr>
<td>Chunks per invocation</td>
<td>40</td>
</tr>
<tr>
<td>Worker concurrency</td>
<td>4 over a shared in memory queue</td>
</tr>
<tr>
<td><code>max_tokens</code></td>
<td>4096</td>
</tr>
<tr>
<td>Output</td>
<td>Forced tool <code>emit_claims</code> via <code>tool_choice</code></td>
</tr>
<tr>
<td>Claims per chunk</td>
<td>≤ ~12, statements ≤ 300 chars</td>
</tr>
</tbody></table>
<p>The system prompt is hardcoded in the app and the uploader can't touch it. The user's persona goes in the <em>user</em> message, inside a <code>&lt;persona&gt;</code> fence, framed as a topic preference rather than instructions.</p>
<p>The chunk text carries <strong>inline paragraph markers</strong>:</p>
<pre><code class="language-plaintext">[p412] Investors typically negotiate for a 1x non-participating preference...
[p413] The participating preferred, by contrast...
</code></pre>
<p>Because every paragraph is labeled with its global index, the model cites by marker and I can verify the citation <strong>deterministically, with no LLM judge</strong>:</p>
<pre><code class="language-plaintext">support_paras must be non-empty
every index must fall inside [paraStart, paraEnd] of the source chunk
otherwise drop the claim
</code></pre>
<p>A model that hallucinates <code>[p9001]</code> gets that claim discarded and the drop rate lands in the stage metrics. No second model call, no similarity check, no vibes. Just a range check on integers.</p>
<p>I also cap <code>anchor_quote</code> at <strong>15 whitespace separated words</strong> and null anything longer. Partly a copyright posture, partly because paraphrase is the entire point. If I wanted the original sentences I'd have read the book.</p>
<p>Each claim carries:</p>
<table>
<thead>
<tr>
<th>Field</th>
<th>Notes</th>
</tr>
</thead>
<tbody><tr>
<td><code>statement</code></td>
<td>Self contained paraphrase</td>
</tr>
<tr>
<td><code>claim_type</code></td>
<td><code>definition, mechanic, heuristic, warning, negotiation_move, anecdote, market_norm</code></td>
</tr>
<tr>
<td><code>favors</code></td>
<td><code>investor, founder, neutral, not_applicable</code></td>
</tr>
<tr>
<td><code>anchor_quote</code></td>
<td>Optional, ≤ 15 words</td>
</tr>
<tr>
<td><code>support_paras[]</code></td>
<td>Validated paragraph indices</td>
</tr>
<tr>
<td><code>concepts[]</code></td>
<td>Raw tags, canonicalized later</td>
</tr>
</tbody></table>
<p>Restarting extract at cursor 0 deletes the book's prior claims, so the stage is idempotent.</p>
<h2>Stage 4: <code>dedupe</code></h2>
<p>Roughly two thirds of the wall clock, and the most interesting algorithm in the pipeline.</p>
<table>
<thead>
<tr>
<th>Constant</th>
<th>Value</th>
<th>Meaning</th>
</tr>
</thead>
<tbody><tr>
<td><code>SIM_THRESHOLD</code></td>
<td>0.86</td>
<td>Cosine at or above this is a cluster candidate</td>
</tr>
<tr>
<td><code>AUTO_MERGE_THRESHOLD</code></td>
<td>0.92</td>
<td>Merge deterministically, skip the LLM entirely</td>
</tr>
<tr>
<td>Projection window <code>W</code></td>
<td>min(48, n−1)</td>
<td>How many neighbors each claim compares against</td>
</tr>
<tr>
<td><code>LLM_MERGE_BATCH</code></td>
<td>24</td>
<td>Sonnet merges per drain invocation</td>
</tr>
<tr>
<td><code>LLM_CONCURRENCY</code></td>
<td>6</td>
<td>Parallel merge calls</td>
</tr>
</tbody></table>
<p>The phases:</p>
<ol>
<li><p><strong>Embed</strong> every live claim's statement text, batches of 100.</p>
</li>
<li><p><strong>Cluster cheaply.</strong> Not O(n²). Project all embeddings onto a deterministic 1D axis (LCG, seed 42), sort claims along it, and only compare each claim to its next 48 neighbors. Cosine above 0.86 unions them. Locality sensitive enough for near duplicates, and linear instead of quadratic.</p>
</li>
<li><p><strong>Auto merge</strong> any cluster whose tightness (min cosine to centroid) clears 0.92, with no LLM at all. Canonical wording picked by type rank (<code>definition</code> beats <code>mechanic</code> beats the rest) then longer statement.</p>
</li>
<li><p><strong>LLM merge</strong> only the 0.86 to 0.92 band, with Sonnet and an <code>emit_merge</code> tool, re-enqueueing until drained.</p>
</li>
<li><p>Assign a durable <code>cluster_id</code> and compute a 2D PCA projection for the embedding scatter UI.</p>
</li>
</ol>
<p>That 0.92 auto merge is what makes the whole thing affordable. Without it Sonnet sees every cluster and the bill roughly triples for merges that are obviously the same sentence written twice.</p>
<p>Losers get <code>superseded = winner_claim_id</code>, and <strong>every downstream read filters</strong> <code>superseded IS NULL</code>. Forgetting that filter exactly once is how you get duplicate claims in your concept counts.</p>
<p>Two metrics lessons. I was overwriting cumulative merge counts with per invocation values, so a stage that ran eight times reported the eighth run's numbers. Fixed by computing before/after counts from the database at finish instead of accumulating in memory. And on the <em>Venture Deals</em> run most clusters came out size 1, which made the rainbow cluster colors in the scatter plot pure noise. I'd built a color legend for a variable with ~900 distinct values. Check cardinality before you reach for a color scale.</p>
<h2>Stage 5: <code>canonicalize</code></h2>
<p>Raw tags are a mess: <code>liquidation_preference</code>, <code>liquidation preference</code>, <code>the liquidation preference clause</code>. This stage builds the <code>raw_tag → canonical_tag</code> map, and the philosophy is load bearing.</p>
<p><strong>String first, embeddings last. Lowering the cosine threshold is specifically the wrong move.</strong></p>
<table>
<thead>
<tr>
<th>Rule</th>
<th>Detail</th>
</tr>
</thead>
<tbody><tr>
<td>Normalize</td>
<td>Lowercase, unify punctuation</td>
</tr>
<tr>
<td>Strip</td>
<td>Container nouns only: <code>agreement, clause, provision, covenant, language, section, terms</code></td>
</tr>
<tr>
<td>Never strip</td>
<td>Meaning bearing words: <code>right, cap, multiple, period, threshold</code></td>
</tr>
<tr>
<td>Negation</td>
<td>Hard block on <code>non, un, anti, de, dis, no</code> prefixes. Never merge at any similarity</td>
</tr>
<tr>
<td>Embed fallback</td>
<td>Only for near singletons with ≥ 2 claims, cosine ≥ 0.93</td>
</tr>
</tbody></table>
<p>The negation rule isn't hypothetical. <code>nonparticipating_preferred</code> and <code>participating_preferred</code> embed at very high cosine similarity and mean opposite things. Merging them corrupts the single most important distinction in the book. There's an <code>assertNoNegationCrossMerge</code> gate that throws if one slips through.</p>
<p>Semantic similarity is exactly the wrong tool for antonyms. The fix is a regex, not a better model.</p>
<h2>Stage 6: <code>concepts</code></h2>
<p>A canonical tag becomes a graph node only at <strong>8 or more claims</strong>. Fewer than <strong>5</strong> nodes total throws, because a book that produces 3 concepts wasn't distilled, it was mangled.</p>
<p>Descriptions get picked heuristically by claim type, with a rule that definitions outrank modal obligation claims when both exist. Otherwise <em>information rights</em> gets described as "the company must deliver audited financials within 90 days," which is a fact about the concept, not the concept.</p>
<p>Each node also gets a <code>primary_chapter</code>, computed as the <strong>modal chapter across its claims, not</strong> <code>MIN()</code>. I used <code>MIN()</code> first. Almost every important concept gets name dropped once in the intro, so <code>MIN()</code> assigned half the graph to chapter 1. Modal assignment puts each concept where the book actually teaches it.</p>
<h2>Stage 7: <code>concept_graph</code>, and the bug that shipped</h2>
<p>Terminal stage. Opus, <code>max_tokens: 16000</code>, tool <code>emit_concept_graph</code>, emitting three edge kinds with per concept caps (prereq ≤ 3, related ≤ 5, confusable ≤ 3) to keep the graph sparse on purpose.</p>
<p>An earlier version asked the model for <code>claim_ids</code> alongside every edge, for the whole book, in one call. On a large book the response hit the ceiling. So:</p>
<ol>
<li><p><code>stop_reason</code> came back <code>max_tokens</code>.</p>
</li>
<li><p>The JSON was truncated mid object.</p>
</li>
<li><p>The parser caught the error and returned <code>[]</code>.</p>
</li>
<li><p>The code saw an empty edge list and fell back to a tag only graph with zero edges.</p>
</li>
<li><p>The book was marked <code>ready</code>.</p>
</li>
<li><p>The UI rendered a perfectly nice force graph of disconnected dots.</p>
</li>
</ol>
<p>Nothing logged an error. Nothing failed. The product quietly became worthless, and I found it days later only because the graph looked suspiciously <em>clean</em>.</p>
<p>The fixes are all about refusing to be helpful:</p>
<ul>
<li><p>A shared <code>requireToolUse</code> helper that <strong>throws</strong> on <code>stop_reason === "max_tokens"</code> or a missing <code>tool_use</code> block. No parsing, no salvage.</p>
</li>
<li><p>The tool schema no longer asks for per edge claim ids across the entire book. Don't build a call whose success depends on the response being small.</p>
</li>
<li><p>A <strong>coverage gate</strong>: if fewer than 80% of concepts have at least one edge, throw the stage.</p>
</li>
</ul>
<p>Post processing normalizes concept references to real ids, then breaks cycles in the prerequisite subgraph with a recursive CTE, preferring to delete edges that run backward in chapter order. <code>cyclesBroken</code> is a metric, because a book generating lots of prerequisite cycles is telling you something about your concept extraction.</p>
<p>Then the book goes <code>ready</code>, the handler returns <code>null</code>, and the queue is empty.</p>
<p><strong>Silent fallbacks are how demos lie.</strong> A fallback that produces a structurally different result (empty edges, fake pages, a tag only graph) is worse than a crash, because a crash gets fixed and a fallback gets shipped.</p>
<h2>Holding it together: the queue</h2>
<p>A full book takes about an hour, so none of this fits in one request. The orchestration is deliberately minimal:</p>
<ul>
<li><p>Jobs are claimed with <code>SELECT ... FOR UPDATE SKIP LOCKED LIMIT 1</code>, which means the worker needs a real transaction. Reads go over Neon's HTTP driver, the worker needs a WebSocket <code>Pool</code>, and every worker path ends in <code>pool.end()</code> inside a <code>finally</code> or you leak connections.</p>
</li>
<li><p>Long stages don't finish in one job. They <strong>re-enqueue themselves with a cursor</strong> in <code>jobs.payload</code>.</p>
</li>
<li><p>The drain claims, runs, and inserts the next job until 45 seconds before its budget expires, then <code>setTimeout</code>s itself in process if pending jobs remain. Self chaining instead of cron.</p>
</li>
<li><p>Failures back off <code>2^attempts * 30</code> seconds, three attempts max. Jobs stuck <code>running</code> for over 15 minutes get recovered to <code>pending</code>.</p>
</li>
<li><p>A module level mutex means one book, one stage at a time, site wide.</p>
</li>
</ul>
<h2>Untrusted personas</h2>
<p>The persona field is free text from strangers that ends up in a prompt I pay for. Defense in depth, ordered by how much I actually trust each layer:</p>
<ol>
<li><p><strong>Forced tool output.</strong> There's no free text channel to hijack.</p>
</li>
<li><p><strong>Deterministic citation validation.</strong> Even a successful injection has to emit claims citing in range paragraphs.</p>
</li>
<li><p><strong>A global spend cap.</strong> Three books per rolling 7 days, site wide, enforced with an advisory lock and a quota row written in the same transaction as the book insert.</p>
</li>
<li><p>A fixed system prompt that frames the persona as a topic preference.</p>
</li>
<li><p>A soft deny list at upload.</p>
</li>
</ol>
<p>That order is deliberate. The deny list is the layer everyone reaches for first and it's the weakest, because deny lists are always incomplete. The real backstops are the tool schema, the range check, and a bounded worst case.</p>
<p>Also worth saying: <strong>the PDF bytes are never stored.</strong> Parse to paragraphs, discard the binary. Privacy choice, cost choice, and a "this doesn't become a pirate library" choice.</p>
<h2>What the run actually looked like</h2>
<table>
<thead>
<tr>
<th>Metric</th>
<th>Value</th>
</tr>
</thead>
<tbody><tr>
<td>Paragraphs / chapters / chunks</td>
<td>3,001 / 21 / 109</td>
</tr>
<tr>
<td>Claims extracted</td>
<td>~1,054</td>
</tr>
<tr>
<td>Claims live after dedupe</td>
<td>~978 (76 superseded)</td>
</tr>
<tr>
<td>Concepts / edges</td>
<td>~54 / ~318</td>
</tr>
<tr>
<td>Wall clock</td>
<td>~45 to 60 min</td>
</tr>
<tr>
<td>Modeled cost</td>
<td>~$1 to $2</td>
</tr>
</tbody></table>
<p>Per stage: embed ~1 min, extract ~6 min, <strong>dedupe ~40 min</strong>, canonicalize ~5 min, graph ~2 min. Dedupe is 70% of the runtime. Embeddings cost cents. Opus on the graph is a real fraction of the dollars once the concept set gets large.</p>
<p>Did it work? I now know what a participating preferred with a cap does, why full ratchet anti dilution is a founder's problem, and what a drag along actually drags. I can click any of those claims and expand it to the paragraph it came from. I did not read the book.</p>
<p>I did read about 900 sentences from it, individually, sorted by concept. I'd argue that's reading the book with the connective tissue removed. Reasonable people will disagree.</p>
<h2>The cheat sheet</h2>
<table>
<thead>
<tr>
<th>Area</th>
<th>Numbers</th>
</tr>
</thead>
<tbody><tr>
<td>Parse</td>
<td>25 MB cap, chapters 5 to 40, demote under 15 paragraphs, page offset only above 0.8 agreement</td>
</tr>
<tr>
<td>Chunk</td>
<td>1200 target, 600 min, 150 overlap, 550 max</td>
</tr>
<tr>
<td>Embed</td>
<td>batch 100, 1536-d, input only billing</td>
</tr>
<tr>
<td>Extract</td>
<td>40 chunks per job, concurrency 4, <code>max_tokens</code> 4096, quote ≤ 15 words</td>
</tr>
<tr>
<td>Dedupe</td>
<td>sim 0.86, auto merge 0.92, window ≤ 48, LLM batch 24 at concurrency 6</td>
</tr>
<tr>
<td>Canonicalize</td>
<td>embed fallback ≥ 0.93, negation hard block</td>
</tr>
<tr>
<td>Concepts</td>
<td>≥ 8 claims per node, ≥ 5 nodes total</td>
</tr>
<tr>
<td>Graph</td>
<td><code>max_tokens</code> 16000, ≥ 80% edge coverage, cycles broken</td>
</tr>
<tr>
<td>Queue</td>
<td>12 min budget, 45s claim cutoff, 15 min stale recovery, 3 attempts</td>
</tr>
</tbody></table>
<h2>What I'd tell past me</h2>
<ol>
<li><p><strong>Inline markers turn citation into a range check.</strong> Labeling paragraphs <code>[p412]</code> costs a few tokens and buys deterministic verification. Never let a model invent identifiers you plan to join on.</p>
</li>
<li><p><strong>Fail loudly or your pipeline will lie.</strong> Every silent fallback here produced output that looked correct.</p>
</li>
<li><p><strong>String first, embeddings last.</strong> Embeddings can't do antonyms.</p>
</li>
<li><p><strong>Global identifiers, always.</strong> Per chapter indices are a join bug waiting for a quiet afternoon.</p>
</li>
<li><p><strong>Gate before you spend.</strong> Chapter count, chunk count, average chunk size. Each one caught a book that would have failed slowly and expensively.</p>
</li>
<li><p><strong>Modal, not minimum.</strong> Think about which statistic actually encodes what you mean.</p>
</li>
</ol>
<p>The pipeline stops at the graph on purpose. Claims and prerequisite edges are obviously the substrate for something that schedules retrieval practice, and I've been building that separately for myself. Different product, different failure modes. This one's job was just to make the nodes trustworthy enough to rank.</p>
]]></content:encoded></item><item><title><![CDATA[Building an AI-Powered YouTube Shorts Generator: A Complete Technical Deep Dive]]></title><description><![CDATA[In the era of short-form content dominance, creating engaging YouTube Shorts consistently can be a time-consuming challenge. Today, I'm excited to share a…]]></description><link>https://blog.iresharma.com/building-an-ai-powered-youtube-shorts-generator-a-complete-technical-deep-dive</link><guid isPermaLink="true">https://blog.iresharma.com/building-an-ai-powered-youtube-shorts-generator-a-complete-technical-deep-dive</guid><category><![CDATA[video]]></category><category><![CDATA[Tiktok]]></category><category><![CDATA[youtube]]></category><dc:creator><![CDATA[Iresh Sharma]]></dc:creator><pubDate>Tue, 10 Jun 2025 15:43:31 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1749570158661/6b1f985b-0e38-4e4f-9d1d-20446d17d2ff.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In the era of short-form content dominance, creating engaging YouTube Shorts consistently can be a time-consuming challenge. Today, I'm excited to share a comprehensive technical breakdown of an open-source YouTube Shorts generator that automates the entire video creation pipeline—from text-to-speech generation to final video composition.</p>
<h2 id="heading-project-overview">Project Overview</h2>
<p>The <strong>YouTube Shorts Generator</strong> is a Python-based automation tool designed to create professional-quality short videos with zero manual intervention. What makes this project unique is its "local-first" approach, prioritizing CPU processing and minimal API dependencies while maintaining high output quality.</p>
<h3 id="heading-key-features">Key Features</h3>
<ul>
<li><p>🚀 <strong>Fast &amp; Efficient</strong>: Optimized for batch processing multiple videos</p>
</li>
<li><p>🏠 <strong>Local-First</strong>: Primary processing happens on your machine</p>
</li>
<li><p>💰 <strong>Cost-Effective</strong>: Only requires Pexels API (free tier available)</p>
</li>
<li><p>🎤 <strong>Human-Sounding</strong>: Multiple TTS engines with neural voice synthesis</p>
</li>
<li><p>📱 <strong>YouTube Shorts Optimized</strong>: 9:16 aspect ratio, perfect timing</p>
</li>
</ul>
<h2 id="heading-architecture-overview">Architecture Overview</h2>
<p>The system follows a modular, component-based architecture that ensures maintainability and extensibility:</p>
<pre><code class="lang-plaintext">videoOrchestrator.py (Main Controller)
├── config/config_manager.py (Configuration)
├── components/
│   ├── topic_manager.py (Content Management)
│   ├── tts_generator.py (Audio Generation)
│   ├── pexels_fetcher.py (Image Fetching)
│   └── video_composer.py (Video Assembly)
</code></pre>
<h2 id="heading-technical-deep-dive">Technical Deep Dive</h2>
<h3 id="heading-1-configuration-management-configmanagerpyhttpmanagerpy">1. Configuration Management (<code>config_</code><a target="_blank" href="http://manager.py"><code>manager.py</code></a>)</h3>
<p>The configuration system uses environment variables and <code>.env</code> files for flexible deployment:</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ConfigManager</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, env_file: str = <span class="hljs-string">".env"</span>, pexels_api_key: str = None</span>):</span>
        self._load_environment()
        self._setup_directories()
        self._setup_logging()
</code></pre>
<p><strong>Key Configuration Areas:</strong></p>
<ul>
<li><p><strong>TTS Settings</strong>: Rate, volume, voice selection</p>
</li>
<li><p><strong>Video Parameters</strong>: Resolution (1080x1920), FPS, duration</p>
</li>
<li><p><strong>Pexels Integration</strong>: API key, image quality, search terms</p>
</li>
<li><p><strong>File Paths</strong>: Output directories, temp storage, topic files</p>
</li>
</ul>
<h3 id="heading-2-intelligent-text-to-speech-ttsgeneratorpyhttpgeneratorpy">2. Intelligent Text-to-Speech (<code>tts_</code><a target="_blank" href="http://generator.py"><code>generator.py</code></a>)</h3>
<p>One of the project's standout features is its sophisticated TTS engine fallback system:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">_initialize_engine</span>(<span class="hljs-params">self</span>):</span>
    tts_methods = [
        (<span class="hljs-string">"coqui_tts"</span>, self._init_coqui_tts),      <span class="hljs-comment"># Neural, local</span>
        (<span class="hljs-string">"elevenlabs"</span>, self._init_elevenlabs),     <span class="hljs-comment"># Premium, cloud</span>
        (<span class="hljs-string">"pyttsx3"</span>, self._init_pyttsx3),          <span class="hljs-comment"># Cross-platform</span>
        (<span class="hljs-string">"system_say"</span>, self._init_system_say),     <span class="hljs-comment"># macOS native</span>
        (<span class="hljs-string">"espeak"</span>, self._init_espeak)             <span class="hljs-comment"># Linux fallback</span>
    ]
</code></pre>
<p><strong>TTS Engine Hierarchy:</strong></p>
<ol>
<li><p><strong>Coqui TTS</strong> (Preferred): Neural synthesis, completely local</p>
</li>
<li><p><strong>ElevenLabs</strong>: Premium cloud-based, requires API key</p>
</li>
<li><p><strong>pyttsx3</strong>: System TTS, cross-platform compatibility</p>
</li>
<li><p><strong>macOS Say</strong>: Native macOS voice synthesis</p>
</li>
<li><p><strong>espeak</strong>: Linux/Unix fallback option</p>
</li>
</ol>
<h3 id="heading-3-smart-image-management-pexelsfetcherpyhttpfetcherpy">3. Smart Image Management (<code>pexels_</code><a target="_blank" href="http://fetcher.py"><code>fetcher.py</code></a>)</h3>
<p>The image fetching system includes intelligent caching and search query generation:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">_generate_search_queries</span>(<span class="hljs-params">self, topic_title: str</span>) -&gt; List[str]:</span>
    <span class="hljs-comment"># Default tech/coding related queries</span>
    tech_queries = [
        <span class="hljs-string">"technology abstract"</span>,
        <span class="hljs-string">"computer programming"</span>, 
        <span class="hljs-string">"digital technology"</span>,
        <span class="hljs-string">"coding screen"</span>,
        <span class="hljs-string">"dark technology"</span>
    ]
    <span class="hljs-comment"># Combine and randomize for variety</span>
    <span class="hljs-keyword">return</span> self._combine_and_shuffle_queries(tech_queries)
</code></pre>
<p><strong>Image Processing Features:</strong></p>
<ul>
<li><p><strong>Intelligent Caching</strong>: 1-hour cache for API responses</p>
</li>
<li><p><strong>Rate Limiting</strong>: Respects Pexels API constraints</p>
</li>
<li><p><strong>Auto-Scaling</strong>: Resizes images to 9:16 aspect ratio</p>
</li>
<li><p><strong>Validation</strong>: Ensures image quality and accessibility</p>
</li>
</ul>
<h3 id="heading-4-precise-video-composition-videocomposerpyhttpcomposerpy">4. Precise Video Composition (<code>video_</code><a target="_blank" href="http://composer.py"><code>composer.py</code></a>)</h3>
<p>The video composer handles the complex task of synchronizing audio, images, and text overlays:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">_create_background_slideshow</span>(<span class="hljs-params">self, image_paths: List[str], duration: float</span>):</span>
    <span class="hljs-comment"># Calculate precise timing with NO transitions</span>
    base_time_per_image = duration / num_images

    <span class="hljs-keyword">for</span> i, image_path <span class="hljs-keyword">in</span> enumerate(image_paths):
        <span class="hljs-keyword">if</span> i == len(image_paths) - <span class="hljs-number">1</span>:
            <span class="hljs-comment"># Last image gets ALL remaining time</span>
            clip_duration = duration - cumulative_time
        <span class="hljs-keyword">else</span>:
            clip_duration = base_time_per_image
</code></pre>
<p><strong>Video Composition Features:</strong></p>
<ul>
<li><p><strong>Perfect Timing Sync</strong>: Audio and video durations match exactly</p>
</li>
<li><p><strong>Visual Effects</strong>: Subtle zoom/pan effects for engagement</p>
</li>
<li><p><strong>Text Overlays</strong>: Title integration with fallback support</p>
</li>
<li><p><strong>Quality Optimization</strong>: YouTube Shorts specifications</p>
</li>
</ul>
<h3 id="heading-5-dual-generation-modes">5. Dual Generation Modes</h3>
<p>The system supports two distinct workflows:</p>
<h4 id="heading-file-based-generation-traditional">File-Based Generation (Traditional)</h4>
<pre><code class="lang-python"><span class="hljs-comment"># Uses topics.json for automated progression</span>
orchestrator = VideoOrchestrator()
result = orchestrator.run_single_generation()
</code></pre>
<h4 id="heading-direct-data-generation-api-friendly">Direct Data Generation (API-Friendly)</h4>
<pre><code class="lang-python"><span class="hljs-comment"># Direct topic data input</span>
topic_data = {
    <span class="hljs-string">"title"</span>: <span class="hljs-string">"Machine Learning"</span>,
    <span class="hljs-string">"description"</span>: <span class="hljs-string">"ML algorithms learn from data..."</span>
}
orchestrator = VideoOrchestrator.from_topic_data(topic_data)
result = orchestrator.generate()
</code></pre>
<h2 id="heading-performance-optimization">Performance Optimization</h2>
<h3 id="heading-timing-analysis">Timing Analysis</h3>
<p>The system provides detailed performance metrics:</p>
<pre><code class="lang-python">result = {
    <span class="hljs-string">"timing"</span>: {
        <span class="hljs-string">"validation"</span>: <span class="hljs-number">0.05</span>,
        <span class="hljs-string">"audio_generation"</span>: <span class="hljs-number">4.68</span>,
        <span class="hljs-string">"image_fetching"</span>: <span class="hljs-number">2.34</span>,
        <span class="hljs-string">"video_creation"</span>: <span class="hljs-number">15.23</span>,
        <span class="hljs-string">"file_update"</span>: <span class="hljs-number">0.12</span>,
        <span class="hljs-string">"total"</span>: <span class="hljs-number">22.42</span>
    }
}
</code></pre>
<h3 id="heading-memory-management">Memory Management</h3>
<ul>
<li><p><strong>Clip Cleanup</strong>: Automatic MoviePy clip disposal</p>
</li>
<li><p><strong>Temp File Management</strong>: Automatic cleanup with age-based purging</p>
</li>
<li><p><strong>Cache Management</strong>: Intelligent image cache with size limits</p>
</li>
</ul>
<h2 id="heading-setup-and-installation">Setup and Installation</h2>
<p>The project includes automated setup scripts for different platforms:</p>
<h3 id="heading-coqui-tts-setup-recommended">Coqui TTS Setup (Recommended)</h3>
<pre><code class="lang-bash">chmod +x setup_scripts/CoquiSetup.sh
./setup_scripts/CoquiSetup.sh
</code></pre>
<h3 id="heading-macos-specific-fixes">macOS-Specific Fixes</h3>
<pre><code class="lang-bash">./setup_scripts/macOs_engines_setup.sh
./setup_scripts/MoviePyImageMagickFix.sh
</code></pre>
<h2 id="heading-usage-examples">Usage Examples</h2>
<h3 id="heading-basic-single-video-generation">Basic Single Video Generation</h3>
<pre><code class="lang-bash">python videoOrchestrator.py --mode single --verbose
</code></pre>
<h3 id="heading-batch-processing">Batch Processing</h3>
<pre><code class="lang-bash">python videoOrchestrator.py --mode continuous --max-iterations 5
</code></pre>
<h3 id="heading-system-health-check">System Health Check</h3>
<pre><code class="lang-bash">python videoOrchestrator.py --mode status
</code></pre>
<h3 id="heading-programmatic-usage">Programmatic Usage</h3>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> videoOrchestrator <span class="hljs-keyword">import</span> VideoOrchestrator

topic_data = {
    <span class="hljs-string">"title"</span>: <span class="hljs-string">"API Design"</span>,
    <span class="hljs-string">"description"</span>: <span class="hljs-string">"Creating effective APIs..."</span>
}

mo = VideoOrchestrator.from_topic_data(topic_data)
result = mo.generate()

<span class="hljs-keyword">if</span> result[<span class="hljs-string">"success"</span>]:
    print(<span class="hljs-string">f"Video created: <span class="hljs-subst">{result[<span class="hljs-string">'video_path'</span>]}</span>"</span>)
</code></pre>
<h2 id="heading-integration-possibilities">Integration Possibilities</h2>
<h3 id="heading-web-api-integration">Web API Integration</h3>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> flask <span class="hljs-keyword">import</span> Flask, request, jsonify

<span class="hljs-meta">@app.route('/generate', methods=['POST'])</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">generate_video</span>():</span>
    data = request.json
    mo = VideoOrchestrator.from_topic_data(data)
    result = mo.generate()
    <span class="hljs-keyword">return</span> jsonify(result)
</code></pre>
<h3 id="heading-queue-processing">Queue Processing</h3>
<p>The modular design allows easy integration with job queues like Celery for scalable video processing.</p>
<h2 id="heading-technical-challenges-solved">Technical Challenges Solved</h2>
<h3 id="heading-1-audio-video-synchronization">1. Audio-Video Synchronization</h3>
<p>The system ensures perfect timing alignment by calculating exact frame durations and handling audio extension when needed.</p>
<h3 id="heading-2-cross-platform-tts">2. Cross-Platform TTS</h3>
<p>Multiple TTS engine support ensures the system works across different operating systems and hardware configurations.</p>
<h3 id="heading-3-resource-management">3. Resource Management</h3>
<p>Intelligent cleanup and caching prevent memory leaks during batch processing.</p>
<h3 id="heading-4-error-recovery">4. Error Recovery</h3>
<p>Comprehensive error handling with graceful degradation ensures the system continues working even if individual components fail.</p>
<h2 id="heading-future-enhancements">Future Enhancements</h2>
<p>The modular architecture enables several exciting possibilities:</p>
<ul>
<li><p><strong>Multi-language Support</strong>: Additional TTS engines for different languages</p>
</li>
<li><p><strong>Custom Voice Training</strong>: Integration with voice cloning technologies</p>
</li>
<li><p><strong>Advanced Visual Effects</strong>: More sophisticated image processing and transitions</p>
</li>
<li><p><strong>Content Intelligence</strong>: AI-powered topic generation and optimization</p>
</li>
<li><p><strong>Analytics Integration</strong>: YouTube Analytics integration for performance tracking</p>
</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>This YouTube Shorts generator demonstrates how thoughtful architecture and component design can create powerful automation tools. By prioritizing local processing, providing multiple fallback options, and maintaining detailed performance tracking, the system achieves both reliability and efficiency.</p>
<p>The project serves as an excellent example of:</p>
<ul>
<li><p><strong>Modular Python Architecture</strong>: Clean separation of concerns</p>
</li>
<li><p><strong>Graceful Degradation</strong>: Multiple fallback options for each component</p>
</li>
<li><p><strong>Performance Optimization</strong>: Detailed timing analysis and resource management</p>
</li>
<li><p><strong>Developer Experience</strong>: Comprehensive setup scripts and documentation</p>
</li>
</ul>
<p>Whether you're looking to automate content creation, learn about video processing pipelines, or explore text-to-speech integration, this project provides a solid foundation and demonstrates best practices in Python automation development.</p>
<p><a target="_blank" href="https://github.com/iresharma/Shorts-Content-Generator"><strong>GitHub Repository</strong></a> <strong>License</strong>: MIT (Open Source)</p>
<hr />
<p><em>The complete source code, setup instructions, and detailed documentation are available in the GitHub repository. Feel free to contribute, fork, or adapt the project for your specific needs!</em></p>
]]></content:encoded></item><item><title><![CDATA[Calculating analytics for webpages]]></title><description><![CDATA[Lately, I've been diving deep into the world of my SaaS product, Reach. I've been thoroughly immersed in figuring out how to calculate basic site…]]></description><link>https://blog.iresharma.com/calculating-analytics-for-webpages</link><guid isPermaLink="true">https://blog.iresharma.com/calculating-analytics-for-webpages</guid><dc:creator><![CDATA[Iresh Sharma]]></dc:creator><pubDate>Fri, 09 Aug 2024 22:54:45 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1706569110321/60b8dfb9-3b00-435c-8e26-a9582ecd823d.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Lately, I've been diving deep into the world of my SaaS product, Reach. I've been thoroughly immersed in figuring out how to calculate basic site analytics—focusing on the usual suspects like views, unique views, clicks, and a range of other interesting metrics. It's been a bit of a rollercoaster, so I thought I'd give you a quick recap of the journey I've been on while striving to achieve these analytics goals with Reach. Buckle up for the ride! 🚀</p>
<p>To give you some context, the web pages we're discussing are straightforward contact pages, similar to a basic Linktree page—essentially a webpage that lists all your important links and products. When dealing with such pages, the metrics that users are most interested in are clicks, unique clicks, and similar engagement indicators.</p>
<p>Here's a breakdown of the key metrics we'll be tracking:</p>
<ul>
<li><p><strong>Views</strong></p>
</li>
<li><p><strong>Clicks</strong></p>
</li>
<li><p><strong>Unique Views</strong></p>
</li>
<li><p><strong>Unique Clicks</strong></p>
</li>
<li><p><strong>Geographical distribution of views and clicks</strong></p>
</li>
</ul>
<h3 id="heading-basic-setup">Basic Setup</h3>
<p>Being a tech enthusiast, I find the setup far more exciting than the actual calculation of metrics. Ideally, the analytics system should be built on top of a messaging queue, allowing it to handle a multitude of click and view requests without overwhelming the server.</p>
<p>In our case, since we're just starting out and not expecting a flood of users or views, we opted for a simpler setup with a Flask server handling incoming requests. These requests are then added to a MongoDB collection. We chose MongoDB because of its excellent aggregation capabilities, which are crucial for the analytics we’re building.</p>
<h3 id="heading-calculating-metrics">Calculating Metrics</h3>
<p>As you're probably aware, calculating basic metrics like views and clicks is relatively straightforward. When a page loads, we send an API request to log the view. Similarly, when a link is clicked, another API request logs the click.</p>
<p>The interesting part comes with calculating unique clicks and views. There are multiple ways to approach this, but for now, we've decided to use IP addresses and user agents. This method not only helps in distinguishing unique users but also allows us to use the IP data to calculate geographical distribution. This is how we've set up our web page analytics so far.</p>
]]></content:encoded></item><item><title><![CDATA[React and Email Templates: Crafting Stunning Templates Made Simple]]></title><description><![CDATA[The context discusses some of the challenges with creating email templates such as inconsistent rendering across different email clients...]]></description><link>https://blog.iresharma.com/react-and-email-templates-crafting-stunning-templates-made-simple</link><guid isPermaLink="true">https://blog.iresharma.com/react-and-email-templates-crafting-stunning-templates-made-simple</guid><category><![CDATA[React]]></category><category><![CDATA[react-email]]></category><category><![CDATA[software development]]></category><category><![CDATA[email]]></category><category><![CDATA[email templates]]></category><dc:creator><![CDATA[Iresh Sharma]]></dc:creator><pubDate>Thu, 28 Dec 2023 06:06:13 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1703693087972/dd5defdd-0bc6-4916-9d8f-574f489d8b6c.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In a world where communication is key, email templates play a crucial role in delivering messages effectively. Explore the transformative power of React in simplifying the intricate art of crafting email templates. From streamlined development workflows to responsive designs, dive into the realm where React and email seamlessly converge. Discover how this powerful JavaScript library empowers developers to create stunning, dynamic email templates with ease. Join us on a journey through the intricacies of React Email, and unlock the secrets to effortlessly designing emails that captivate and communicate.</p>
<h3 id="heading-problems-with-the-original-solution">Problems with the original solution</h3>
<p>Writing email templates can be a significant challenge for several reasons, making it a cumbersome task for many developers. Here are some key pain points:</p>
<ol>
<li><p><strong>Inconsistent Renderer Maturity:</strong> Different email clients use renderers at varying levels of maturity. What works seamlessly in one client may fail to display correctly in another. The lack of a standardized rendering engine across all email providers means that developers must navigate the nuances of each platform, resulting in a fragmented and time-consuming development process. A template that appears flawless in Gmail might encounter issues when viewed in Superhuman or Outlook.</p>
</li>
<li><p><strong>Outdated HTML Renderers:</strong> The HTML renderers used by popular email clients such as Gmail and Outlook often lag behind modern web standards. These outdated renderers do not fully support essential CSS properties like flexbox and grid layout. This limitation hampers the ability to create sophisticated and responsive email designs, as developers are forced to resort to older, less flexible layout techniques.</p>
</li>
<li><p><strong>Lack of Testing Capabilities:</strong> Unlike web development, where testing across different browsers is relatively straightforward, email template testing poses unique challenges. There is no easy and standardized way to test email templates across various providers. Developers often resort to manual testing on multiple platforms, which is not only time-consuming but also prone to oversight. The absence of comprehensive testing tools exacerbates the difficulty of ensuring consistent rendering and functionality across diverse email clients.</p>
</li>
</ol>
<p>In summary, the combination of outdated renderers, inconsistent maturity levels among email clients, and the absence of robust testing mechanisms contributes to the frustration and complexity associated with crafting effective email templates. Developers grapple with these challenges to ensure that their messages are presented consistently and professionally across the wide array of email platforms in use today.</p>
<h3 id="heading-solution-react-email-by-resendhttpsresendcom">Solution: React Email by <a target="_blank" href="https://resend.com">Resend</a></h3>
<p>React Email represents a paradigm shift in how developers approach the design and development of email content. Leveraging the declarative and component-based architecture of React, developers can now bring the same ease and efficiency to email templates that they've enjoyed in web development. This innovation doesn't just streamline the coding process; it revolutionizes the way emails are conceived and delivered.</p>
<p>React Email offers several advantages that make it a powerful and useful tool for developers tasked with creating engaging and responsive email templates. Here are some key points highlighting the utility of React Email:</p>
<ol>
<li><p><strong>Declarative and Component-Based Structure:</strong> React's declarative syntax and component-based structure bring a more intuitive and modular approach to email template development. Developers can create reusable components, making it easier to manage and maintain complex email layouts. This structure enhances code organization and promotes efficiency in template creation.</p>
</li>
<li><p><strong>Consistent User Experience Across Platforms:</strong> React Email helps address the challenge of inconsistent rendering across different email clients. By leveraging React's virtual DOM and component-based architecture, developers can design templates that adapt seamlessly to various email clients, ensuring a consistent and polished user experience regardless of the platform used by the recipient.</p>
</li>
<li><p><strong>Dynamic Content and Interactivity:</strong> React's ability to manage state and handle dynamic content enables the inclusion of interactive elements within email templates. Whether it's incorporating personalized user data or creating dynamic, responsive components, React Email allows developers to go beyond static content, resulting in more engaging and interactive emails.</p>
</li>
<li><p><strong>Efficient Development Workflow:</strong> The modular nature of React components facilitates a more efficient development workflow. Developers can focus on building individual components, testing them independently, and then assembling them to create complex email templates. This approach not only enhances code reusability but also accelerates the development process.</p>
</li>
<li><p><strong>Easy Integration with Data and APIs:</strong> React Email seamlessly integrates with data sources and APIs, allowing developers to fetch and display dynamic content within email templates. This capability is particularly useful for creating personalized and data-driven email campaigns, providing a dynamic and tailored experience for each recipient.</p>
</li>
<li><p><strong>Enhanced Testing Capabilities:</strong> React's popularity in web development has led to the development of robust testing tools and libraries. Developers can leverage these tools to test React Email components more effectively, ensuring that templates function as intended across a variety of email clients. This helps address the challenge of testing email templates on different platforms.</p>
</li>
<li><p><strong>Community Support and Resources:</strong> React's large and active community provides a wealth of resources, tutorials, and libraries that can be leveraged for email template development. This support network can be invaluable for developers seeking solutions to common challenges and looking to stay updated on best practices in React Email development.</p>
</li>
</ol>
<p>In summary, React Email is a valuable tool that empowers developers to create sophisticated, responsive, and interactive email templates with greater ease and efficiency. Its adoption addresses longstanding challenges in the email development space, making it an increasingly popular choice for those looking to enhance the quality and functionality of their email campaigns.</p>
<h3 id="heading-react-email-an-overviewhttpsreactemail"><a target="_blank" href="https://react.email/">React Email: An overview</a></h3>
<p>React Email offers a streamlined and efficient API, utilizing JSX and a syntax reminiscent of React, to expedite the creation of email templates. Drawing inspiration from the React Native team, the Resend team has innovatively crafted a renderer and essential primitives, simplifying the template development process.</p>
<h3 id="heading-how-it-works">How it works ?</h3>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">The following explanation on how react email works is a speculation I couldn't find any documentation on how it works.</div>
</div>

<p>If you have worked with react you'd know working with requires a minimum of two dependencies "react" and "react-dom". "react-dom" is an interesting one that because this is sort of a compiler/interpreter/renderer that takes all the jsx (react code) and converts into the DOM (Document Object Model) or virtual DOM to be exact.</p>
<p>Similarly React Email uses it's own renderer to render out the react components/primitives that they designed.</p>
<p>The best part of react email is that they have a render function that not only provides you with the rendered not HTML but also has a option for plain text which is great because people who have outdated machines or have images/html blocked on there email client this text is really helpful.</p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>In conclusion, ReactEmail stands out as a powerful and versatile tool for modern email development. Its intuitive component-based architecture, seamless integration with React, and robust features make it a go-to choice for developers aiming to create dynamic and responsive email templates. By leveraging ReactEmail, developers can streamline their workflow, enhance user engagement, and ensure a consistent and visually appealing experience across various email clients.</p>
]]></content:encoded></item><item><title><![CDATA[Learning ROP: Resiliency, Observability and Performance]]></title><description><![CDATA[Tech stack breakdown: Reach | Building my SAAS]]></description><link>https://blog.iresharma.com/learning-rop-resiliency-observability-and-performance</link><guid isPermaLink="true">https://blog.iresharma.com/learning-rop-resiliency-observability-and-performance</guid><category><![CDATA[TechStack]]></category><category><![CDATA[tech stacks]]></category><category><![CDATA[System Design]]></category><category><![CDATA[Microservices]]></category><dc:creator><![CDATA[Iresh Sharma]]></dc:creator><pubDate>Wed, 20 Dec 2023 11:47:52 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1702908909950/5b164e8b-0234-4c6f-9a1b-cb2261bce2da.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In the dynamic landscape of digital content creation, where innovation is the key to staying ahead, a robust and tailored tech stack is the lifeblood of success. For content-first teams navigating the ever-evolving challenges of collaboration, scalability, and seamless workflow integration, the right software can make all the difference. In this blog series, we embark on a journey to demystify the technological marvel behind a SaaS platform meticulously crafted for content-first teams.</p>
<h2 id="heading-ideologies-behind-the-choices">Ideologies behind the choices</h2>
<p>When making decisions about the technology for this project, I kept in mind three key factors or goals that I personally aim to achieve, beyond the obvious monetary benefits. With four years of engineering college and one year of industry experience, I've been actively involved in building various projects both personally and professionally. My projects have functioned well for smaller user bases, ranging from tens to hundreds—maybe a thousand people at most. Therefore, my overarching goals for this project include:</p>
<ol>
<li><p>Resilience</p>
</li>
<li><p>Observability</p>
</li>
<li><p>Performance</p>
</li>
</ol>
<h2 id="heading-exploring-these-ideologies">Exploring these ideologies</h2>
<ul>
<li><p><strong>Resilience</strong></p>
<blockquote>
<p><em>Definition:</em> Resilience in software engineering refers to a system's ability to maintain functionality and recover quickly from failures or disruptions. It involves designing software architectures and components to gracefully handle errors, faults, or unexpected conditions.</p>
</blockquote>
<p>  As previously stated, I have successfully obtained the desired outcomes from my projects, although this achievement has typically been confined to a specific instance or a limited set of cases. Additionally, I have never attempted nor achieved the creation of a comprehensive user flow where all conceivable elements function seamlessly.</p>
</li>
<li><p><strong>Observability</strong></p>
<blockquote>
<p><em>Definition:</em> Observability is the ability to understand and monitor a software system's internal state and behavior using various tools and techniques. It involves collecting and analyzing data, logs, and metrics to gain insights into the system's performance, health, and potential issues.</p>
</blockquote>
<p>  A significant aspect of attaining comprehensive resilience, or any form of resilience, lies in observability. Therefore, observability is an area I intend to emphasize and concentrate on.</p>
</li>
<li><p><strong>Performance</strong></p>
<blockquote>
<p><em>Definition:</em> Performance in software engineering refers to the efficiency and speed at which a software system or application executes tasks and processes data. It involves optimizing code, algorithms, and infrastructure to achieve optimal response times and resource utilization.</p>
</blockquote>
<p>  In my previous endeavors, my focus was primarily on creating products that fulfilled their intended purpose, without paying meticulous attention to the time aspect—whether it took a millisecond or a few minutes. However, with Reach, I aim to rectify this approach. I aspire for every aspect to not merely fall within the acceptable spectrum but to reach the pinnacle of excellence, achieving a status beyond acceptable, in the "hot damn" category.</p>
</li>
</ul>
<h2 id="heading-basic-architecture">Basic Architecture</h2>
<p>The following diagram provides a concise overview of the cloud architecture employed in this project. We will delve into the rationale behind these choices and discuss the utilized technologies immediately following this illustration.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1702910828068/16760289-b042-4c32-be8a-4b9ca2e5a8cc.png" alt class="image--center mx-auto" /></p>
<hr />
<h3 id="heading-remix">Remix</h3>
<p>Choosing Remix over Next.js comes down to several key factors:</p>
<ol>
<li><p><strong>Simpler APIs:</strong></p>
<p> Remix offers simpler APIs, streamlining the development process. Its API design is intuitive and user-friendly, making it easier for developers to understand and work with.</p>
</li>
<li><p><strong>Pure MPA Experience:</strong></p>
<p> Remix provides a pure Multi-Page Application (MPA) experience. This approach aligns with specific project requirements that benefit from a multi-page structure without the need for a client-side routing paradigm, offering a straightforward and efficient solution.</p>
</li>
<li><p><strong>Uses Stable and Reliable Web APIs:</strong></p>
<p> Remix relies on stable and reliable web APIs, contributing to a robust foundation for web development. By leveraging well-established standards, Remix ensures compatibility and stability, reducing the likelihood of compatibility issues and enhancing the overall reliability of the application.</p>
</li>
</ol>
<p>In summary, Remix stands out over Next.js due to its simpler APIs, commitment to a pure MPA experience, and reliance on stable and reliable web APIs. These factors collectively contribute to a more streamlined and dependable development process.</p>
<h3 id="heading-microservices">Microservices</h3>
<p>Microservices architecture offers several advantages over a monolithic approach, especially in scenarios where project features are complex and require a high level of separation. Here are some key reasons why microservices might be preferable:</p>
<ol>
<li><p><strong>Great Separation of Concerns for Complex Features:</strong></p>
<p> Microservices excel in providing a high degree of separation of concerns. In projects with complex features, breaking down the functionality into individual services allows for better isolation and management. Each microservice can focus on a specific feature or business capability, making the system more modular and maintainable.</p>
</li>
<li><p><strong>Variable Traffic and Horizontal Scaling:</strong></p>
<p> Microservices are well-suited for scenarios where traffic across different features can vary significantly. Since individual microservices can be scaled independently, this architecture provides a more efficient and flexible solution for handling varying workloads. It enables horizontal scaling, allowing you to allocate resources dynamically to the services that need them most.</p>
</li>
<li><p><strong>Granular Feature Control:</strong></p>
<p> Microservices enable fine-grained control over features. In projects where features can be turned on or off based on user requirements, microservices provide the granularity needed for managing feature flags. This allows for better control over the functionality offered to users and simplifies the process of rolling out new features or changes incrementally.</p>
</li>
<li><p><strong>Technology Stack Diversity:</strong></p>
<p> Microservices afford the flexibility to use different technology stacks for different services. This is particularly advantageous when certain technologies are better suited to specific tasks. With a microservices architecture, you can choose the most appropriate technology for each service, optimizing for performance, scalability, and developer expertise.</p>
</li>
</ol>
<p>In summary, for projects with complex features, variable traffic patterns, and a need for technology diversity, microservices architecture provides a scalable and flexible solution. The ability to separate concerns, scale horizontally, and choose diverse technology stacks makes microservices well-suited for addressing the challenges posed by intricate and dynamic project requirements.</p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">⚠</div>
<div data-node-type="callout-text">Microservices complicate resilience and observability by introducing distributed complexities. Decentralized logs, numerous network dependencies, and diverse technology stacks hinder seamless error handling and real-time monitoring. Identifying and addressing issues promptly becomes challenging, impacting the overall resilience and observability of the microservices architecture.</div>
</div>

<h3 id="heading-using-a-proxy">Using a proxy</h3>
<p>Employing a proxy between your frontend and various microservices offers several advantages:</p>
<ol>
<li><p><strong>Only One Service Exposed to the Internet:</strong></p>
<p> By using a proxy, you can expose only the proxy service to the internet. This adds an additional layer of security, reducing the attack surface and potential vulnerabilities. The internal microservices can remain hidden behind the proxy, enhancing the overall security posture of your application.</p>
</li>
<li><p><strong>Separation of Concerns:</strong></p>
<p> A proxy allows for a clear separation of concerns between the frontend and microservices. This separation facilitates a modular and scalable architecture, making it easier to manage and update individual components without affecting the entire system.</p>
</li>
<li><p><strong>Single Point for Caching:</strong></p>
<p> Having a proxy enables you to centralize caching logic. Instead of implementing caching mechanisms in each microservice, the proxy can handle caching at a single point. This not only simplifies cache management but also improves efficiency and reduces redundancy in caching efforts.</p>
</li>
<li><p><strong>Browser Support for gRPC Isn't Great:</strong></p>
<p> Utilizing a proxy becomes particularly valuable when dealing with microservices that communicate using gRPC and Protobufs. As browser support for gRPC isn't as widespread, the proxy acts as an intermediary, allowing you to communicate with microservices seamlessly while ensuring compatibility with browsers that may not fully support gRPC.</p>
</li>
</ol>
<p>In summary, employing a proxy between your frontend and microservices offers benefits such as enhanced security, clear separation of concerns, centralized caching, and improved compatibility with browser technologies like gRPC and Protobufs.</p>
<h3 id="heading-grpc">gRPC</h3>
<p>gRPC emerges as a superior choice for microservices communication due to several key factors:</p>
<ol>
<li><p><strong>Performance with Protobufs and HTTP/2:</strong></p>
<p> Leveraging Protocol Buffers (Protobufs) and HTTP/2, gRPC offers superior performance. Protobufs, being more compact than JSON, reduce payload size, and HTTP/2 enables multiplexing, resulting in faster, more efficient communication between microservices.</p>
</li>
<li><p><strong>Protobuf Over JSON:</strong></p>
<p> Protobuf's binary serialization is more efficient than JSON, reducing bandwidth and enhancing serialization/deserialization speed. This efficiency is crucial in microservices environments where minimizing data transfer overhead is paramount.</p>
</li>
<li><p><strong>HTTP/2:</strong></p>
<p> gRPC utilizes HTTP/2 as its transport protocol, providing features like multiplexing, header compression, and flow control. These features contribute to improved resource utilization, reduced latency, and better handling of concurrent requests—essential for microservices communication.</p>
</li>
<li><p><strong>End-to-End Type Safety:</strong></p>
<p> gRPC provides strong typing through Protobuf's schema definition. This end-to-end type safety ensures that communication between microservices is well-defined, reducing the likelihood of errors related to data inconsistencies and enhancing overall system reliability.</p>
</li>
</ol>
<p>In summary, gRPC's performance optimizations with Protobufs and HTTP/2, efficient serialization with Protobufs, utilization of HTTP/2 features, and end-to-end type safety make it a superior option for seamless and efficient communication between microservices in distributed architectures.</p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">While I had the option to employ RESTful APIs instead of gRPC, a crucial aspect of this project involves exploring technologies that genuinely intrigue me. gRPC, a technology that has captivated my interest for some time, aligns with this learning objective, prompting my decision to incorporate it into the project.</div>
</div>

<h3 id="heading-postgres-with-redis">Postgres (with redis)</h3>
<p>Honestly, there's no clear winner, but on a serious note, my aim is to enhance my SQL skills, and PostgreSQL encompasses all the features necessary for this project at a moderate scale. Given my limited experience in evaluating the performance and scalability of various databases, I've decided to opt for PostgreSQL as my primary database choice.</p>
<h3 id="heading-r2-over-s3">R2 over S3</h3>
<p>Opting for Cloudflare R2 with AWS Glacier backup over S3 offers several advantages:</p>
<ol>
<li><p><strong>Pricing:</strong></p>
<p> Cloudflare R2, coupled with AWS Glacier, can often present a more cost-effective storage solution compared to S3, especially for long-term archival needs. Glacier's pricing model, designed for infrequently accessed data, can result in lower costs for certain use cases.</p>
</li>
<li><p><strong>Data Duplication Safety with Two Vendors:</strong></p>
<p> Utilizing Cloudflare and AWS as separate vendors introduces redundancy and data duplication safeguards. Storing data in multiple locations enhances data resilience and provides an extra layer of protection against potential data loss or service disruptions.</p>
</li>
<li><p><strong>Great CDN Support with Cloudflare:</strong></p>
<p> Cloudflare excels in providing robust Content Delivery Network (CDN) support. This can significantly enhance the performance and availability of your data, ensuring faster and more reliable access for users across the globe. S3 also supports CDN, but Cloudflare's specialized focus on CDN services can offer additional benefits.</p>
</li>
</ol>
<p>It's important to note that the choice between Cloudflare R2 with AWS Glacier and S3 depends on specific project requirements, including the frequency of data access, budget considerations, and the need for CDN support. Each solution has its strengths, and the decision should align with the unique demands of your storage and access patterns.</p>
<h2 id="heading-other-small-stuff">Other small stuff</h2>
<p>Apart from the above mentioed technologies I also use the following things (languages, libraries and stuff)</p>
<ul>
<li><p>Resend</p>
</li>
<li><p><a target="_blank" href="https://railway.app">Railway</a> (for a temporary dev setup)</p>
</li>
<li><p><a target="_blank" href="https://ui.shadcn.com/">shadcn/ui</a></p>
</li>
<li><p>Tailwind</p>
</li>
<li><p>Github</p>
</li>
<li><p>Postman</p>
</li>
<li><p>Scss</p>
</li>
<li><p>Mantine/hooks</p>
</li>
</ul>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">This is the first version of the tech stack reveal</div>
</div>

<h2 id="heading-conclusion">Conclusion</h2>
<p>In wrapping up our exploration of Reach tech stack choices and ideologies, it becomes evident that the decisions made today are not just about the tools we employ but about crafting a foundation for the future. This marks the beginning of a journey where performance, resilience, and observability converge. The choices we've examined are pivotal, setting the stage for a deeper dive into optimizing performance and hinting at the integral role that resilience will play in our upcoming discussions. Stay tuned for the later blog, where I bring all three ideologies together, forging a path toward a SaaS tech stack that transcends expectations.</p>
]]></content:encoded></item><item><title><![CDATA[From a Remix monolith to microservices]]></title><description><![CDATA[A small story of me learning micro services, gRPC and a multitude of things.]]></description><link>https://blog.iresharma.com/from-a-remix-monolith-to-microservices</link><guid isPermaLink="true">https://blog.iresharma.com/from-a-remix-monolith-to-microservices</guid><category><![CDATA[Remix]]></category><category><![CDATA[Kubernetes]]></category><category><![CDATA[Microservices]]></category><category><![CDATA[Go Language]]></category><category><![CDATA[Redis]]></category><dc:creator><![CDATA[Iresh Sharma]]></dc:creator><pubDate>Wed, 15 Nov 2023 17:49:37 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1700070444932/9644d1ea-d285-4b59-8e50-42fda36b5b51.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Greetings, brave software voyagers! Today, we're here to discuss a transition that's as dramatic as a soap opera breakup but with significantly fewer tears (we hope). Picture this: you and your trusty Remix monolith, once the power couple of your development universe, are now contemplating a conscious uncoupling.</p>
<p>I'm working on developing a SaaS product that assists content teams not only with content management but also with their day-to-day operations. This includes features such as issue tracking, content storage and management, file versioning, a review system, calendar integration, email functionality, Shopify store management, and analytics for various platforms.</p>
<p>At first, I made it as this big remix app, like a remix monolith, with all the backend logic crammed into loader functions, actions, and a bunch of different handler routes. It seemed alright at the time, but with the crazy number of APIs, I started wondering if that would cut it... This is a kind of reason I should have said but to be honest this project is my learning experiment I am trying to built a production ready performant software so that I can learn a multitude of things.</p>
<p>So when I started working on this project I could already make a application that might sometimes work, I mean the one perfect way to do things always work but will it work if you click slightly to the left. Well god knows, so I made the first version,i.e, the monolith with the aim of learning error handling and good practices. And now I can successfully make applications that can run in more than one scenarios.</p>
<p>But I wasn't very happy with the UI and an extreme lack of separation between frontend and backend code. As well as the horrific performance I was getting out of the damning combination of prisma + mongodb. All of that with no TS.</p>
<p><img src="https://images.contentstack.io/v3/assets/blt39790b633ee0d5a7/blta7c13826bb2f4024/647a2edf4166504108319a1c/MDB_and_Prisma_Article_1_1.png" alt class="image--center mx-auto" /></p>
<p>So here's my plan to kick of a microservice based architecture.</p>
<p>I will still have a remix SSR that talks to RESTful API which acts as a auth proxy, this auth proxy then delegates traffic to all the other services via gRPC.</p>
<p><img src="https://content.pstmn.io/13c9a173-17b8-48a5-91c2-0c583db8174a/UEhPVE8tMjAyMy0xMC0xMS0yMC00MC00Ny5qcGc=" alt class="image--center mx-auto" /></p>
<p>Ignore the (express app) written under the services, I have decided to give up node from my backend stack it's most GoLang and Python. This happened because I started with Golang for auth proxy because it would need to be very performant. That continued along in the pursuit of performance, I hear ya I hear ya performance and python ?</p>
<p>I use python ony for services that are just basic crud and to be crud performance depends mostly on the database and the queries you run (correct me if I am wrong).</p>
<p>This seems like a good idea, the go auth proxy on look is giving me extremely good performance. On my local setup with postgres and redis cache the auth proxy responds with sub millisecond responses.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1700068595199/beee393b-b459-4d0d-bb38-10b5bd81c05b.jpeg" alt class="image--center mx-auto" /></p>
<p>This seems to be great performance I mean for sure it's local but these services in a k8s cluster with the postgres database in the mix, and redis running on all these individual services it should be very fast.</p>
<p>You can look at this project here:</p>
<ul>
<li><p>Monolith: <a target="_blank" href="https://github.com/iresharma/reach-io-remix">code</a> <a target="_blank" href="https://reach-io.vercel.app">demo</a></p>
</li>
<li><p>Microservices: <a target="_blank" href="https://github.com/users/iresharma/projects/1">github project</a></p>
</li>
<li><p>API def for the microservice: <a target="_blank" href="https://documenter.getpostman.com/view/12309600/2s9Y5R1Rqs">postman</a></p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Mindful-me: A mental health tracker for the modern world]]></title><description><![CDATA[My submission for Appwrite hackathon]]></description><link>https://blog.iresharma.com/mindful-me-a-mental-health-tracker-for-the-modern-world</link><guid isPermaLink="true">https://blog.iresharma.com/mindful-me-a-mental-health-tracker-for-the-modern-world</guid><category><![CDATA[Appwrite Hackathon]]></category><category><![CDATA[Appwrite]]></category><category><![CDATA[mentalhealth]]></category><dc:creator><![CDATA[Iresh Sharma]]></dc:creator><pubDate>Wed, 14 Jun 2023 21:44:54 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1686772617243/edae5112-5a9e-49bb-8c2d-975e1115b194.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Mental health is crucial for overall well-being. It affects our thoughts, emotions, and behaviours, shaping how we perceive and navigate the world. Prioritising mental health promotes resilience, productivity, and healthy relationships. It enables us to cope with stress, seek support when needed, and maintain a balanced life. By nurturing our mental well-being, we can unlock our full potential, achieve personal growth, and lead fulfilling lives.</p>
<h3 id="heading-why-mood-tracking">Why mood tracking?</h3>
<p>Mood tracking plays a significant role in promoting better mental health. By regularly monitoring and documenting our moods, we gain valuable insights into our emotional patterns and triggers. This self-awareness empowers us to identify and address negative thought patterns, manage stress more effectively, and make informed decisions about self-care. Additionally, mood tracking can help track progress, identify trends, and assist healthcare professionals in tailoring personalized treatments. Ultimately, it fosters a proactive approach to mental well-being, leading to improved overall mental health.</p>
<h3 id="heading-tech-stack">Tech Stack</h3>
<ul>
<li><p>Vue.js</p>
</li>
<li><p>Appwrite</p>
</li>
</ul>
<h3 id="heading-features">Features</h3>
<ol>
<li><p><strong>Mood Tracking😁</strong></p>
<p> Mood tracking involves monitoring and recording our emotional states over time. By consistently tracking our moods, we gain valuable insights into the factors that influence our well-being. It helps us identify patterns, triggers, and correlations between our emotions and external circumstances. With this awareness, we can make informed decisions about self-care, seek appropriate support, and implement effective coping strategies. Mood tracking also facilitates communication with healthcare professionals, enabling them to tailor treatments and interventions. Ultimately, it empowers us to take an active role in managing our mental health, promoting self-awareness, emotional regulation, and overall well-being.</p>
</li>
<li><p><strong>Image Analysis🏞️</strong><br /> By harnessing the power of image analysis, we unlock a new dimension in understanding mood. Our innovative approach analyzes facial expressions, body language, and other visual cues to provide valuable insights into emotional states. This technology allows us to detect and interpret subtle nuances, helping individuals gain a deeper understanding of their own moods and emotional well-being. By leveraging image analysis, we offer a unique and objective perspective that complements traditional self-reporting methods. This advanced tool facilitates self-reflection, enables personalized interventions, and empowers individuals to make informed choices for their mental health and overall happiness.</p>
</li>
<li><p><strong>Insight📈</strong></p>
<p> Harnessing the power of tracked emotional data, we generate meaningful insights for our users. By analyzing and interpreting this data, we uncover patterns, trends, and correlations that offer valuable information about their emotional well-being. Our approach allows individuals to gain a deeper understanding of their own emotions, identify triggers, and make informed decisions about their mental health. With this knowledge, users can develop personalized strategies for self-care, manage stress effectively, and improve their overall emotional resilience. By leveraging tracked emotional data, we provide a valuable resource that empowers individuals to take control of their emotional well-being and live more fulfilling lives.</p>
</li>
<li><p><strong>Journal📔:</strong></p>
<p> A personal journal serves as a powerful tool for capturing and exploring our feelings. It provides a safe and private space to express and reflect upon our emotions, thoughts, and experiences. By jotting down our feelings regularly, we gain clarity and insight into our inner world. It helps us identify patterns, triggers, and areas of growth. Moreover, journaling promotes self-discovery, self-expression, and emotional healing. It serves as a trusted companion during challenging times, allowing us to vent, process emotions, and find solace. Journaling is a transformative practice that nurtures self-awareness, promotes mental well-being, and encourages personal growth.</p>
</li>
</ol>
<h3 id="heading-team">Team</h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Name</td><td>Github</td><td>Website</td></tr>
</thead>
<tbody>
<tr>
<td>Iresh Sharma</td><td><a target="_blank" href="https://github.com/iresharma">iresharma</a></td><td><a target="_blank" href="https://iresharma.vercel.app">iresharma</a></td></tr>
<tr>
<td>Shreesh Kulkarni</td><td><a target="_blank" href="https://github.com/sgkul2000">sgkul2000</a></td><td><a target="_blank" href="https://shreeshkulkarni.com">shreeshkulkarni.com</a></td></tr>
</tbody>
</table>
</div><h3 id="heading-links">Links</h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Name</td><td>Link</td></tr>
</thead>
<tbody>
<tr>
<td>Demo</td><td><a target="_blank" href="https://mindful-me.vercel.app">mindful-me</a></td></tr>
<tr>
<td>Github</td><td><a target="_blank" href="https://github.com/sgkul2000/mindful-me">mindful-me</a></td></tr>
<tr>
<td>Youtube</td><td>--</td></tr>
</tbody>
</table>
</div><h3 id="heading-demo-credentials">Demo Credentials</h3>
<ul>
<li><p>Email - example@gmail.com</p>
</li>
<li><p>Password - Hello123#</p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Making linktr.ee using next 13 and vercel]]></title><description><![CDATA[Building Reach]]></description><link>https://blog.iresharma.com/making-linktree-using-next-13-and-vercel</link><guid isPermaLink="true">https://blog.iresharma.com/making-linktree-using-next-13-and-vercel</guid><category><![CDATA[Next.js]]></category><category><![CDATA[Vercel]]></category><dc:creator><![CDATA[Iresh Sharma]]></dc:creator><pubDate>Wed, 10 May 2023 18:18:24 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1683742625223/52bf4f4e-e477-452d-bc00-d43d616c6bed.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><a target="_blank" href="https://reach-page-server.vercel.app/iresharma">Demo</a></p>
<p>For a pretty long time, I am trying to build a saas solution for content-heavy teams and influencer teams called <a target="_blank" href="https://ireshsharma8.wixsite.com/reach-io">reach</a>. Being an advocate of open source I believe in <em>building in public</em>. Hence here are my series of blog post about building said product.</p>
<p>One of the features of reach is a brand page feature similar to <a target="_blank" href="https://lintr.ee">linktr.ee</a>. For those who don't know what linktr.ee is, here's what they explain themselves as.</p>
<blockquote>
<p>One link to help you share everything you create, curate and sell from your Instagram, TikTok, Twitter, YouTube and other social media profiles.</p>
</blockquote>
<p>In simple words, it gives people an easy way to create simple but useful pages that conveys basic information about them as well as all important links, <a target="_blank" href="https://linktr.ee/gdsc_nie">here's an example</a>.</p>
<p><strong>How I summarise the product from a technical point of view</strong></p>
<blockquote>
<p>A URL shortener which instead of redirecting you to a link, shows you a page with a multitude of links.</p>
</blockquote>
<p>So here's what I did,</p>
<ul>
<li><p>I create a Next 13 app with ISR</p>
</li>
<li><p>Now next allows me to use <code>server components</code> and things like <code>generateStaticParams</code> and <code>generateMetaData</code></p>
</li>
<li><p>So during build time I look up my database for existing pages and generate params based on route</p>
</li>
</ul>
<pre><code class="lang-typescript"><span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">generateStaticParams</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">const</span> cursor = <span class="hljs-keyword">await</span> pages.find({}, { projection: { route: <span class="hljs-number">1</span> } });
    <span class="hljs-keyword">const</span> pageIds = <span class="hljs-keyword">await</span> cursor.toArray();
    <span class="hljs-keyword">return</span> pageIds.map(<span class="hljs-function"><span class="hljs-params">el</span> =&gt;</span> ({ route: el.route }));
}
</code></pre>
<ul>
<li>Inside the component, I use the await syntax to fetch the details about the page and build it out</li>
</ul>
<pre><code class="lang-typescript"><span class="hljs-comment">// I use the route from params as it's inject by generateStaticParams</span>
<span class="hljs-keyword">const</span> pageData = <span class="hljs-keyword">await</span> getPage(params.route);
<span class="hljs-comment">// the type for pageData look something like this</span>
<span class="hljs-keyword">type</span> Data = {
    route: <span class="hljs-built_in">string</span>;
    links: Link[];
    template: {
        profile: {
            name:<span class="hljs-built_in">string</span>;
            desc:<span class="hljs-built_in">string</span>;
            image:<span class="hljs-built_in">string</span>;
        };
        button:<span class="hljs-built_in">string</span>;
        background:<span class="hljs-built_in">string</span>;
        font:<span class="hljs-built_in">string</span>;
        fontColor:<span class="hljs-built_in">string</span>;
        metaTags:Meta[];
    };
}
</code></pre>
<ul>
<li>Now if you see the <code>template</code> property includes a bunch of information about the UI and SEO for the page, which I use to both style as well as run the <code>generateMetaData</code> function for the sweet SEO tags</li>
</ul>
<p>The next steps will be to include adding things A11y for better accessibility and add support for more complicated widgets and social icons.</p>
<p>Here are a few screenshots from Reach to show you the update/create UI of these pages.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1683742146795/f659c40d-7c20-4609-bda0-d727709b0ef4.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1683742157289/a56975d5-de50-47ec-b805-b4d51581f197.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1683742164074/b6430b1d-478d-4234-9139-1f50600e2006.png" alt class="image--center mx-auto" /></p>
]]></content:encoded></item><item><title><![CDATA[Implementing VS-Code on my website]]></title><description><![CDATA[P.S. It was pretty easy]]></description><link>https://blog.iresharma.com/implementing-vs-code-on-my-website</link><guid isPermaLink="true">https://blog.iresharma.com/implementing-vs-code-on-my-website</guid><category><![CDATA[Netlify]]></category><category><![CDATA[NetlifyHackathon]]></category><category><![CDATA[Hashnode]]></category><category><![CDATA[Visual Studio Code]]></category><category><![CDATA[Nuxt]]></category><category><![CDATA[Next.js]]></category><dc:creator><![CDATA[Iresh Sharma]]></dc:creator><pubDate>Mon, 21 Feb 2022 01:07:02 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1645405587205/vVn1SWoqZ.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>So You would have seen these websites with a full blown vs-code like text editor built into them right ? I mean look at websites like <a target="_blank" href="https://codesandbox.io">codesandbox</a> or <a target="_blank" href="https://codedamn.com">codedamn</a> . Well my current project has a code editor need well there are a few options out there. Here's my journey of getting an actual vs-code like editor on the site.</p>
<h2 id="heading-1-diy">1. DIY</h2>
<p>Bad bad bad idea, I mean maybe with a couple of years in my hand could have been able to do it but no no no no.</p>
<h2 id="heading-2-hacking-with-hightlightjshttpshighlightjsorg">2. Hacking with <a target="_blank" href="https://highlightjs.org">Hightlight.js</a></h2>
<p>This was a better idea but still wasn't good, I was basically trying to capture user key presses and do some DOM manipulation to put them a in div which was running highlight.js . Well this solution worked sort of but 1 it was very very buggy and 2 it was a half baked solution.</p>
<h2 id="heading-3-acebrace-editorhttpsacec9io">3. <a target="_blank" href="https://ace.c9.io">Ace/Brace Editor</a></h2>
<p>These turned out to be good alternatives to vs-code but they liked features and in general didn't a very convincing feel, apart from there lack of contextual autocomplete and visual appearance these were great choices</p>
<h2 id="heading-4-monaco-editorhttpsmicrosoftgithubiomonaco-editor">4. <a target="_blank" href="https://microsoft.github.io/monaco-editor/">Monaco Editor</a></h2>
<p>This is Microsoft's original veriosn of the viscose editor with all the quirks and features. Embedding this was fairly simple a two liner config change for Nuxt just to add a loader for it's ism files and voila it worked like a charm.
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1645405029334/N2jKJF3sd.png" alt="ss1.png" /></p>
]]></content:encoded></item><item><title><![CDATA[Nuxt on Netlify]]></title><description><![CDATA[Learning a lot more about the SSG aspect of Nuxt]]></description><link>https://blog.iresharma.com/nuxt-on-netlify</link><guid isPermaLink="true">https://blog.iresharma.com/nuxt-on-netlify</guid><category><![CDATA[Netlify]]></category><category><![CDATA[NetlifyHackathon]]></category><category><![CDATA[Hashnode]]></category><category><![CDATA[Nuxt]]></category><category><![CDATA[Emails]]></category><dc:creator><![CDATA[Iresh Sharma]]></dc:creator><pubDate>Sat, 19 Feb 2022 10:20:03 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1645265945927/yLnO8bppi.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>My last couple of days were spent only doing one thing, converting my Server Side Rendered Nuxt.js app to a Netlify compatible (static hosting) static application. Well in theory this is a simple operation as Nuxt as a framework provides simple tooling to statically generate a static website so in theory I just have to run</p>
<p><code>npm run generate</code></p>
<p>and voila my SSR should be converted into a SSG output, but but but that's not very true.</p>
<p>Now see what happened was my app has major chunk of it as data representation, basically gets a lot of data from our database and lays it out. This was the biggest reason I went with SSR, the best way to this on pages which are just a list of documents is fetch them on the server as it is faster and the javascript bundle shipped to client is much much smaller.</p>
<p>So the best way of doing that for Nuxt is using a lifecycle hook called asyncData which runs on the server, now the thing is this hook is not exported to generated js. Even though is way to disable server fetching and making it client side even that woke on only if you are Nuxt in SSr mode. So I had to re-write all my asyncData hooks to mounted hooks which took me an easy couple of hours figuring this out and fixing it.</p>
<p>Next problem I faced was running my backend on  my express based backend on Netlify functions, well initial I thought it was as simple as setting my API folder as my functions holder with the <code>index.js</code> now that didn't give me an error, neither did it give me a response 😢. </p>
<p>Some research done the line I realised I need to convert it into a Serverless-http server. After doing it both worked and did not work. </p>
<p>This needed up giving me a sweet error:</p>
<pre><code><span class="hljs-attribute">12</span>:<span class="hljs-number">09</span>:<span class="hljs-number">13</span> AM: Request must be smaller than <span class="hljs-number">69905067</span> bytes for the CreateFunction operation
<span class="hljs-attribute">12</span>:<span class="hljs-number">09</span>:<span class="hljs-number">15</span> AM: Request must be smaller than <span class="hljs-number">69905067</span> bytes for the CreateFunction operation
<span class="hljs-attribute">12</span>:<span class="hljs-number">09</span>:<span class="hljs-number">17</span> AM: Request must be smaller than <span class="hljs-number">69905067</span> bytes for the CreateFunction operation
<span class="hljs-attribute">12</span>:<span class="hljs-number">09</span>:<span class="hljs-number">19</span> AM: Request must be smaller than <span class="hljs-number">69905067</span> bytes for the CreateFunction operation
<span class="hljs-attribute">12</span>:<span class="hljs-number">09</span>:<span class="hljs-number">22</span> AM: Request must be smaller than <span class="hljs-number">69905067</span> bytes for the CreateFunction operation
</code></pre><p>every two minutes Netlify shouted at me that my express app is too big, soooooooooo
At midnight with my DBMS semester end exam tomorrow I wanted to kill myself but no I can do this is what I told myself. Then I needed up realising I already have an SSR version hosted on heroic, so I added soon CORS policies on that hosting and voila I had a version of my Application on Netlify contiously fetching data from a heroic server.</p>
<p><a target="_blank" href="https://g-notify.netlify.com">Netlify Hosting</a>
<a target="_blank" href="https://g-notify.herokuapp.com">Heroku Hosting</a>
<a target="_blank" href="https://github.com/iresharma/G-notify">Github</a></p>
]]></content:encoded></item><item><title><![CDATA[Twilio interview experience]]></title><description><![CDATA[Twilio India on-campus interview experience]]></description><link>https://blog.iresharma.com/twilio-interview-experience</link><guid isPermaLink="true">https://blog.iresharma.com/twilio-interview-experience</guid><category><![CDATA[twilio]]></category><category><![CDATA[interview]]></category><category><![CDATA[College]]></category><category><![CDATA[Hashnode]]></category><dc:creator><![CDATA[Iresh Sharma]]></dc:creator><pubDate>Fri, 11 Feb 2022 19:44:22 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1644608618185/To-hfWv0D.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Interviewing for big tech I always a very scary and ambitious situation. Recently I interviewed for a summer intern in <a target="_blank" href="https://twilio.com">Twilio</a> and here's how it went down.</p>
<h2 id="heading-a-few-pointers-before-we-start">A few pointers before we start:</h2>
<ul>
<li>It was an on-campus opportunity  🏫</li>
<li>Yes, I got selected 🎉</li>
<li>The CTC for full-time was 43.4LPA (16LPA in hand) 💰</li>
<li>My stipend is 1.22LPA (84k in hand) 💰</li>
</ul>
<h1 id="heading-rounds">Rounds</h1>
<h3 id="heading-1-coding-round-90mins">1. Coding round (90mins)</h3>
<p>It was one of the best coding round I ever gave, for a change the problems weren't just random DSA problem but were actually based real world problem and were framed like a story in the terms of a problem faced by Twilio.</p>
<p>The first question was pretty simple, I don't exactly remember but it was something like</p>
<blockquote>
<p>Given an array of files, having to data points</p>
<ol>
<li>file URL</li>
<li>file size in bytes</li>
</ol>
<p>We have to return files in categories of KB, MB, GB</p>
<p>input : [['link', 1234], ...]</p>
</blockquote>
<p>The second question was a string manipulation question</p>
<blockquote>
<p>Given a string use some given conditions to tell if it's telephone, WeChat, whatsApp or Invalid</p>
<p>WhatsApp = 'wta: 322424'</p>
<p>telephone  = 'tel:2342423424'</p>
<p>weChat = 'wec:ireaf_343'</p>
<p>With a few more conditions for each</p>
</blockquote>
<p>The second question ended up taking some time, but I still managed ti do both of them In 29mins which was pretty good.</p>
<h3 id="heading-2-tech-hr-interview">2. Tech + HR interview</h3>
<p>This round was a STAR + project discussion + CS Core interview. In my case the CS core question involved a Computer Networking question :</p>
<blockquote>
<p>When we hit a domain in the browser what happens next ?
Ans: A get request is sent to a DNS server, which gives us the IP associated with the domain and then we are routed through servers and finally receive a response</p>
</blockquote>
<p><em>My answer was a little vague as I didn't know the complete answer but did know the basic so didn't want to be quiet or not answer</em></p>
<p>Other than that we discussed some of my projects, and my experience at my older workplace.</p>
<h3 id="heading-3-coding-interview">3. Coding interview</h3>
<pre><code class="lang-python"><span class="hljs-comment"># In the pre-pandemic world (or when we get back in the office), we find it very challenging to find meeting rooms in </span>
<span class="hljs-comment"># our Twilio offices and we want to solve that problem. We have the data of bookings for each conference room. For the sake of </span>
<span class="hljs-comment"># this problem, we can assume that each meeting is one hour long. Each interval is one hour long. e.g. A session 2-10 consists</span>
<span class="hljs-comment">#  of 8 meetings of one hour each. (2,3), (3,4) ........ (9,10)</span>

<span class="hljs-comment"># Given this data (a set of booking timings across meeting rooms), find out the busiest hours of the day i.e when most the rooms are engaged concurrently.</span>

<span class="hljs-comment"># sample data set:</span>

<span class="hljs-comment"># room 1: 2-10</span>
<span class="hljs-comment"># room 2: 3-15</span>
<span class="hljs-comment"># room 3: 4-9</span>
<span class="hljs-comment"># room 4: 8-14</span>
<span class="hljs-comment"># room 5: 7-13</span>
<span class="hljs-comment"># room 6: 5-10</span>
<span class="hljs-comment"># room 7: 11-15</span>

_input = [
    [<span class="hljs-number">2</span>,<span class="hljs-number">10</span>],
    [<span class="hljs-number">3</span>,<span class="hljs-number">15</span>],
    [<span class="hljs-number">4</span>,<span class="hljs-number">9</span>],
    [<span class="hljs-number">8</span>,<span class="hljs-number">14</span>],
    [<span class="hljs-number">7</span>,<span class="hljs-number">13</span>],
    [<span class="hljs-number">5</span>,<span class="hljs-number">10</span>],
    [<span class="hljs-number">11</span>,<span class="hljs-number">15</span>]
]


<span class="hljs-comment"># O(n*m)+O(n) n=number of rooms, m=largest room interval</span>
<span class="hljs-comment"># def solution(testCase):</span>
<span class="hljs-comment">#     hours = [0]*24</span>
<span class="hljs-comment">#     for item in testCase:</span>
<span class="hljs-comment">#         start = item[0]</span>
<span class="hljs-comment">#         end = item[1]</span>
<span class="hljs-comment">#         for i in range(start-1,end):</span>
<span class="hljs-comment">#             hours[i]+=1</span>
<span class="hljs-comment">#     busy = max(hours)</span>
<span class="hljs-comment">#     print(f"BUSIEST HOUR =&gt; {hours.index(busy)+1}")</span>
<span class="hljs-comment">#     # print(f"FINAL {hours}")</span>
<span class="hljs-comment">#     pass</span>


<span class="hljs-comment"># O(n*m) n=number of rooms, m=largest room interval</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">solution</span>(<span class="hljs-params">testCase</span>):</span>
    hours = [<span class="hljs-number">0</span>]*<span class="hljs-number">24</span>
    busy = <span class="hljs-number">-1</span>
    index = <span class="hljs-number">-1</span>
    <span class="hljs-keyword">for</span> item <span class="hljs-keyword">in</span> testCase:
        start = item[<span class="hljs-number">0</span>]
        end = item[<span class="hljs-number">1</span>]
        <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(start<span class="hljs-number">-1</span>,end):
            hours[i]+=<span class="hljs-number">1</span>
            <span class="hljs-keyword">if</span> busy&lt;hours[i]:
                busy=hours[i]
                index = i
                print(hours,busy,index)

    print(<span class="hljs-string">f"Solution =&gt; <span class="hljs-subst">{index+<span class="hljs-number">1</span>}</span>"</span>)
    <span class="hljs-keyword">pass</span>


solution(_input)
</code></pre>
<p>I was able to get the a solution upto O(n) but I don't the solution to that. But in this interview they were more interested in compatibility and conversation during pair programming I say this because a friend of mine was able to get the solution quicker than me but was very quiet and didn't communicate a lot and hence didn't get selected.</p>
]]></content:encoded></item><item><title><![CDATA[Working in startup v/s corporates - 1]]></title><description><![CDATA[Part 1: My experience at a startup]]></description><link>https://blog.iresharma.com/working-in-startup-vs-corporates-1</link><guid isPermaLink="true">https://blog.iresharma.com/working-in-startup-vs-corporates-1</guid><category><![CDATA[Startups]]></category><category><![CDATA[internships]]></category><category><![CDATA[Hashnode]]></category><category><![CDATA[programing]]></category><dc:creator><![CDATA[Iresh Sharma]]></dc:creator><pubDate>Thu, 23 Sep 2021 18:17:12 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1632420951059/Mo0QZIhFNK.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>I have been working in a service startup for about an year now and now I'll soon be join fidelity investments as a summer intern. I was very curious on how it would be to move from a chill but a busy environment to a very strictly monitored one. I'll be writing this blog in 2 parts, this one is about startup experience and next one will come after the internship about corporate</p>
<h2 id="let-me-paint-a-picture-for-you">Let me paint a picture for you</h2>
<p>The startup I work at is an App studio, i.e, a company building software for contracts. Here we have a small team so the pressure is always high and it's really really fun. Especially it being a startup we get days where we have no work and then we get days where we sit to work at 12PM and might not be done till 3-4AM.</p>
<h3 id="pros">Pros</h3>
<ol>
<li><p><strong>It's a unique experience</strong>, where big corporates might have skateboards in hallway and a bunch of gaming and retreat solutions these startups have a completely different feel, a small office space with plastic toys and random stuff as decorations.</p>
</li>
<li><p><strong>YOU LEARN A LOT</strong>, I mean a hell lot when I say a lot. So I joined in Feb 2020, with basic HTML, CSS, and Js knowledge within a month I was proficient with Vue.js and was working on a production level App. Fast forward a few months and I made my first PR into a backend repo. A few more months and I am now in a client meet demoing the app. Now after a year and a half I frequently make PRs to frontend, backend, native apps. I end up taking a lot of clients meets also managing the cloud infrastructure.</p>
</li>
<li><p><strong>Employees work without supervision</strong>, in a startup since the team is small you end up working not very down the ladder. The supervision I have is an Aasna table and code review for my PRs.</p>
</li>
<li><p><strong>You can innovate</strong>, you get a lot of creative freedom in a startup. Not only in terms of a solution to the given problem but also the core product itself.</p>
</li>
<li><p><strong>Perks</strong>, </p>
<ul>
<li>flexible working hours</li>
<li>working from home</li>
<li>shorter work weeks</li>
<li>a casual atmosphere</li>
</ul>
</li>
</ol>
<h3 id="cons">Cons</h3>
<ol>
<li><strong>The workload is heavy,</strong> Expect to work long hours, with few holidays and vacations.</li>
<li><strong>What social life?</strong> You might have fun at the office, but you work hard too. Employees work under extreme pressure to avoid losses, so don't count on having much of social life. Work-life balance is tough, and exhaustive hours at the office can take a toll.</li>
<li><p>Not in my case (intern) but for a full timer <strong>job security</strong> might be a huge concern while planning to work in a startup. </p>
<blockquote>
<p>Research by UC Berkeley &amp; Stanford and other contributors suggests that over 90%              of startups fail within their first three years! Tech startups, in particular, face the threat of technological advancements and new inventions wiping out their business.</p>
</blockquote>
</li>
</ol>
<h2 id="conclusion">Conclusion</h2>
<p>Overall my experience over at a startup has been super fun and a great boost to my knowledge and hopefully career. Soon i'll have a follow up taking about corporate work culture my experience and a simple comparison.</p>
]]></content:encoded></item><item><title><![CDATA[Live Streaming Protocols]]></title><description><![CDATA[These are the most commonly used Live Streaming protocols. Where HLS -> HTTP Live Stream which is a standard made by Apple in 2008 with the launch of…]]></description><link>https://blog.iresharma.com/live-streaming-protocols</link><guid isPermaLink="true">https://blog.iresharma.com/live-streaming-protocols</guid><category><![CDATA[programing]]></category><category><![CDATA[HTML5]]></category><category><![CDATA[video streaming]]></category><category><![CDATA[Hashnode]]></category><dc:creator><![CDATA[Iresh Sharma]]></dc:creator><pubDate>Mon, 31 May 2021 09:39:47 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1622453884416/hLtxcLCpp.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="hls-and-mpeg-dash">HLS and MPEG-DASH</h2>
<p>These are the most commonly used Live Streaming protocols. Where HLS -&gt; <strong>HTTP Live Stream</strong> which is a standard made by Apple in 2008 with the launch of iPhone 3g. It is a protocol accepted by all all apple devices and browsers along with android devices but chromium based browsers.</p>
<p>I had a lot of fun experimenting with these protocols even though I was not able to completely implement MPEG-DASH but that's probably because both lack of technical skills and lack of good documentation</p>
<h3 id="heres-what-i-know">Heres what I know</h3>
<p>HTTP Live Streaming supports video on just about every device. Although it was originally created for use on Safari and iOS devices, <strong>HLS is now supported on almost every modern web browser—mobile, desktop, tablet, etc.</strong></p>
<p>HLS uses a method called Adaptive Bitrate Streaming. This method measures the internet speed available to each viewer of a given video. Then, the video quality they are being served is adjusted dynamically</p>
<p><strong><em>Video delivered using HLS, if configured properly, will dynamically provide you with the best possible video quality while minimizing buffering and lagging.</em></strong> This approach leads to a superior user experience.</p>
<p><strong><em>HLS was designed to maximize quality, not to minimize absolute latency. Its keyframe interval, packet size, and playback buffer requirement simply aren’t suitable for super-rapid live streaming. Therefore, it usually adds a delay of 20-60 seconds to your stream. These live streaming software platforms offer integrated low latency solutions, and those are the ones to consider.</em></strong></p>
<h3 id="breakdown-of-hls-works">Breakdown of HLS works</h3>
<ol>
<li>Capturing devices (cameras, microphones, etc.) capture the content.</li>
<li>The content is sent from the capturing device to a live <a target="_blank" href="https://www.dacast.com/blog/what-is-video-encoding/">video encoder</a>.</li>
<li>The encoder transmits the content to the video hosting platform via <strong>RTMP</strong>.</li>
<li>The video hosting platform uses <strong><a target="_blank" href="https://www.dacast.com/blog/stream-software-solutions/">HLS ingest</a></strong> to transmit the content to an <strong>HTML5 video player</strong>.</li>
</ol>
<h3 id="technical-overview-of-hls-streaming"><strong>Technical Overview of HLS Streaming</strong></h3>
<p>With that background in mind, how does HLS streaming technology work?</p>
<p>First, the HLS protocol <strong>chops up MP4 video content into short (10-second) chunks with the .ts file extension (MPEG2 Transport Stream)</strong>. Next, an HTTP server stores those streams, and HTTP delivers these short clips to viewers on their devices.</p>
<p>HLS will play video encoded with the <strong>H.264 or HEVC/H.265 codecs.</strong></p>
<p>The HTTP server also <strong>creates an <a target="_blank" href="https://www.dacast.com/support/knowledgebase/how-to-create-an-m3u8-media-link-walkthrough/">M3U8 playlist file</a> (e.g. manifest file) that serves as an index for the video chunks.</strong>  That way, even if you choose to <a target="_blank" href="https://www.dacast.com/why-dacast-to-broadcast-live/">broadcast live</a> using only a single quality option, the file will still exist.</p>
<p>Now, let’s consider how playback quality works with HLS video streaming. With this protocol, a given user’s <a target="_blank" href="https://www.dacast.com/blog/best-live-streaming-software-for-hls-streaming/">video player software</a> (like an HTML5 video player) detects deteriorating or improving network conditions.</p>
<p>If either occurs, the player software first reads the main index playlist and determines which quality video is ideal. Then the software reads the quality-specific index file to determine which chunk of video corresponds to the point at which the viewer is watching.</p>
<h3 id="this-is-what-an-m3u8-playlist-will-look-like">This is what an .m3u8 playlist will look like</h3>
<pre><code><span class="hljs-selector-id">#EXTM3U</span>
<span class="hljs-selector-id">#EXT-X-PLAYLIST-TYPE</span><span class="hljs-selector-pseudo">:VOD</span>
<span class="hljs-selector-id">#EXT-X-TARGETDURATION</span><span class="hljs-selector-pseudo">:10</span>
<span class="hljs-selector-id">#EXT-X-VERSION</span><span class="hljs-selector-pseudo">:4</span>
<span class="hljs-selector-id">#EXT-X-MEDIA-SEQUENCE</span><span class="hljs-selector-pseudo">:0</span>
<span class="hljs-selector-id">#EXTINF</span><span class="hljs-selector-pseudo">:10.0</span>,
<span class="hljs-selector-tag">http</span>:<span class="hljs-comment">//example.com/movie1/fileSequenceA.ts</span>
<span class="hljs-selector-id">#EXTINF</span><span class="hljs-selector-pseudo">:10.0</span>,
<span class="hljs-selector-tag">http</span>:<span class="hljs-comment">//example.com/movie1/fileSequenceB.ts</span>
<span class="hljs-selector-id">#EXTINF</span><span class="hljs-selector-pseudo">:10.0</span>,
<span class="hljs-selector-tag">http</span>:<span class="hljs-comment">//example.com/movie1/fileSequenceC.ts</span>
<span class="hljs-selector-id">#EXTINF</span><span class="hljs-selector-pseudo">:9.0</span>,
<span class="hljs-selector-tag">http</span>:<span class="hljs-comment">//example.com/movie1/fileSequenceD.ts</span>
<span class="hljs-selector-id">#EXT-X-ENDLIST</span>
</code></pre><h4 id="these-are-the-tags-used-in-the-video-on-demand-playlist-example">These are the tags used in the Video on Demand playlist example:</h4>
<blockquote>
<p><strong>EXTM3U</strong>: Indicates that the playlist is an extended M3U file. This type of file is distinguished from a basic M3U file by changing the tag on the first line to EXTM3U. All HLS playlists must start with this tag.</p>
<p><strong>EXT-X-PLAYLIST-TYPE</strong>: Provides mutability information that applies to the entire playlist file. This tag may contain a value of either EVENT or VOD. If the tag is present and has a value of EVENT, the server must not change or delete any part of the playlist file (although it may append lines to it). If the tag is present and has a value of VOD, the playlist file must not change.</p>
<p><strong>EXT-X-TARGETDURATION</strong>: Specifies the maximum media-file duration.</p>
<p><strong>EXT-X-VERSION</strong>: Indicates the compatibility version of the playlist file. The playlist media and its server must comply with all provisions of the most recent version of the IETF Internet-Draft of the HTTP Live Streaming specification that defines that protocol version.</p>
<p><strong>EXT-X-MEDIA-SEQUENCE</strong>: Indicates the sequence number of the first URL that appears in a playlist file. Each media file URL in a playlist has a unique integer sequence number. The sequence number of a URL is higher by 1 than the sequence number of the URL that preceded it. The media sequence numbers have no relation to the names of the files.</p>
<p><strong>EXTINF</strong>: A record marker that describes the media file identified by the URL that follows it. Each media file URL must be preceded by an EXTINF tag. This tag contains a duration attribute that's an integer or floating-point number in decimal positional notation that specifies the duration of the media segment in seconds. This value must be less than or equal to the target duration.</p>
</blockquote>
<p>source:  <a target="_blank" href="https://developer.apple.com/documentation/http_live_streaming/example_playlists_for_http_live_streaming/video_on_demand_playlist_construction">Apple</a> </p>
<h2 id="read-more">Read More:</h2>
<ul>
<li><p>https://www.dacast.com/blog/hls-streaming-protocol/</p>
</li>
<li><p>https://www.dacast.com/blog/stream-software-solutions/</p>
</li>
<li><p>https://hackernoon.com/building-a-media-streaming-server-using-go-and-hls-protocol-j85h3wem</p>
</li>
</ul>
<h3 id="my-attempt-in-making-a-live-streaming-server">My attempt in making a Live Streaming Server</h3>
<p>https://github.com/iresharma/Variable-bitrate-Live-streamin-server</p>
<blockquote>
<p>MGNIX Config: https://www.nginx.com/blog/video-streaming-for-remote-learning-with-nginx/</p>
</blockquote>
]]></content:encoded></item><item><title><![CDATA[MVP in flutter]]></title><description><![CDATA[Models - View - Presenter architecture is an extended version on model - view - controller architecture which is mostly used to design User Interfaces. In…]]></description><link>https://blog.iresharma.com/mvpflutter</link><guid isPermaLink="true">https://blog.iresharma.com/mvpflutter</guid><category><![CDATA[programing]]></category><category><![CDATA[Flutter]]></category><category><![CDATA[Flutter Examples]]></category><category><![CDATA[Google]]></category><category><![CDATA[mvp]]></category><dc:creator><![CDATA[Iresh Sharma]]></dc:creator><pubDate>Tue, 19 Jan 2021 18:41:44 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1611081690155/c7FAf4l0x.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="mvp-in-flutter">MVP in flutter</h1>
<h3 id="mvp-architecture">MVP Architecture</h3>
<p>Models - View - Presenter architecture is an extended version on model - view - controller architecture which is mostly used to design User Interfaces.</p>
<p><img src="https://upload.wikimedia.org/wikipedia/commons/d/dc/Model_View_Presenter_GUI_Design_Pattern.png" alt="https://upload.wikimedia.org/wikipedia/commons/d/dc/Model_View_Presenter_GUI_Design_Pattern.png" /></p>
<p>In my personal experience MVP is the best design pattern or architecture that you can go for in small scale personal and production projects.
I always seen the MVP architecture only been used in native iOS and Android development, but in a framework like flutter which supports and promotes breaking code of and making files as small as possible it's important to have an MVP approach</p>
<pre><code class="lang-python">- Project
    - Android          <span class="hljs-comment"># already there</span>
    - ios              <span class="hljs-comment"># already there</span>
    - build            <span class="hljs-comment"># already there</span>
    - release          <span class="hljs-comment"># To keep the latest build handy</span>
        - latest.apk
    - assets           <span class="hljs-comment"># Your typical assets folder</span>
        - fonts
        - images
        - logo
        - JSON/Animation <span class="hljs-comment"># Lottie .jsons or rive .flrs</span>
    - lib
        - Config         <span class="hljs-comment"># Config files linke theme.dart and stuff</span>
        - Models         <span class="hljs-comment"># Various Models</span>
            - DataModels.  <span class="hljs-comment"># Data models like User model</span>
            - ViewModels.  <span class="hljs-comment"># View models like provider for a complex animation</span>
        - Service        <span class="hljs-comment"># Presenter folder</span>
            - API          <span class="hljs-comment"># handler files for REST API calls</span>
            - firebase.    <span class="hljs-comment"># handler files for firebase</span>
            - Cache        <span class="hljs-comment"># handler files for caching data (I prefer hivedb)</span>
            - Global       <span class="hljs-comment"># Files with global functions and stuff</span>
        - Views          <span class="hljs-comment"># Various Views</span>
        - Widgets        <span class="hljs-comment"># Components</span>
</code></pre>
<h3 id="config-folder">Config Folder</h3>
<p>This is the so called configs folder containing the configs file. The config files in case of flutter would be files like </p>
<ul>
<li>ThemeConfig.dart</li>
<li>Router.dart</li>
<li>APISecret.dart</li>
</ul>
<h3 id="models-folder">Models Folder</h3>
<p>Models folder this is supposed be the Models to be things like user models, response model and things like that. I prefer to put all the providers necessary in here as well</p>
<p>This folder I usually divide into two sub folders:</p>
<ul>
<li>DataModels</li>
<li>ViewsModels</li>
</ul>
<h3 id="servcie">Servcie</h3>
<p>This folder is what would include our <strong>presenter</strong> part of the <strong>MVP</strong> pattern.
This usually contains things like</p>
<ul>
<li><p>API</p>
<p>  I use chopper for my API calls so all the service files and the generated .chopper.dart files go here separated in diff. folders</p>
</li>
<li><p>Firebase</p>
<p>  This contains all firebase related stuff, like any functions talking to firestore / Firebase Storage functions and things like FCM and dynamic links setup</p>
</li>
<li><p>Cache</p>
<p>  This contains files that have functions related to caching function, I use hiveDb so I'd generally have a folder called typeAdapters and have all my adapters there</p>
</li>
<li><p>Global</p>
<p>  This is a wrapper folder for files containing global functions, like basic string manipulation and stuff</p>
</li>
</ul>
<h3 id="views">Views</h3>
<p>This is pretty self explanatory containing file related to various views / pages of the app</p>
<h3 id="widgets">Widgets</h3>
<p>To all web developers this would correspond to the Components folder in your React or Vue app. To others this folder will contain files including reusable widgets</p>
<h4 id="this-about-it-for-mvp-in-flutter-i-hope-this-was-helpful-to-you">This about it for MVP in flutter I hope this was helpful to you.</h4>
]]></content:encoded></item><item><title><![CDATA[Best documentation award goes to NUXT.js]]></title><description><![CDATA[Ooof that's a big claim, well yes but just listen me out. I have been writing Vue.js code for almost a year and I have made a lot of projects with Vue not…]]></description><link>https://blog.iresharma.com/nuxt1</link><guid isPermaLink="true">https://blog.iresharma.com/nuxt1</guid><category><![CDATA[Hashnode]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[Next.js]]></category><category><![CDATA[Vue.js]]></category><category><![CDATA[Startups]]></category><dc:creator><![CDATA[Iresh Sharma]]></dc:creator><pubDate>Sun, 20 Dec 2020 21:56:24 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1608501338614/I9KHPCtHG.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="best-documentation-award-goes-to-nuxtjs">Best documentation award goes to NUXT.js</h1>
<p>Ooof that's a big claim, well yes but just listen me out.
I have been writing Vue.js code for almost a year and I have made a lot of projects with Vue not just personal but also a couple of production projects at my internship.
That's enough prefaces, I am currently working in an edtech startup and have been exploring a lot of new things, SSR (Server-Side-Rendering) with Nuxt.js being one of then.</p>
<h3 id="why-server-side-rendering">Why Server Side Rendering ?</h3>
<p>SSR or server side rendering, according to me is very useful when you have app that shows a lot data on the frontend so let's an app which serves the main purpose of showing you all the stats for your company or an app lists out nearby restaurants  or something.
This is because if your app is a server side rendered all your data is already there and in place instead of showing a table a with a loader it presents you with a table straight away, another use case for SSR is if your user base comprises of people who would have phones/pcs that might be able to or be very slow in rendering js that is delivered by modern web frameworks like React, Vue or Angular</p>
<p><strong>PS I am new to the SSR world, this is my basic understanding of the tech <em>I'd love to get corrected in the comments❤️</em></strong></p>
<h3 id="our-service-and-why-ssr">Our service and why SSR ?</h3>
<p>Well as I mentioned I am working on an edtech startup and hence we have an app for it. Now we need a portal check our user data, generate reports and have a place to enter questions and content.
So if you think of it the frontend basically has two jobs:</p>
<ul>
<li>Show data</li>
<li>Input for educational content</li>
</ul>
<p>So the major part is data showcase we opted for SSR.</p>
<h2 id="nuxt-basics">Nuxt Basics</h2>
<p>Well SSR application structure(or atleast for Nuxt) is very very different, instead  of over general src and dist folders you are represented with a huge folder structure (given you use <code>npx create-nuxt-app &lt;project-name&gt;</code>)</p>
<ul>
<li>assets</li>
<li>components</li>
<li>layouts</li>
<li>middleware</li>
<li>pages</li>
<li>plugins</li>
<li>static</li>
<li>store</li>
</ul>
<h4 id="assets">Assets</h4>
<p>Well not a lot to talk about assets is the folder that contains your assets. 
<code>'~/assets/'</code> here's an awesome thing with Nuxt, it already has aliases set for you</p>
<h4 id="components">Components</h4>
<p>Love of modern frontend frameworks <strong><em>components</em></strong> well this is the place where you keep all your components global or not (maybe not but that's what we are doing right now)</p>
<h4 id="layout">layout</h4>
<p>This is where my new love for nuxt starts, i used to hate writing way too many v-if statements in my App.vue file and have a huge set of spaghetti code which might be a nightmare to get back to fix bugs or add features. But Iresh what is it ??
Well Vue.js developers here's the thing files in the layout folder contains your layouts
So let's say you have a navbar which is supposed show Sign in and Register buttons only, when the user is not logged in but you wanna show a lot more options along with a sidebar ?? Well now you can have the navbar with more options and the sidebar in the <code>~/layout/default.vue</code> as that's the default file that loads your UI unless specified to do something else.
And for your constrained view you can make a new file in the layouts folder called <code>auth.js</code> or anything and specific that in your login/register or relevant pages.
Here's a small example from my current project</p>
<pre><code class="lang-html"><span class="hljs-comment">&lt;!-- default.vue --&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">template</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">sideBar</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">vs-row</span> <span class="hljs-attr">style</span>=<span class="hljs-string">"height: 100vh"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">vs-col</span> <span class="hljs-attr">:offset</span>=<span class="hljs-string">"side ? 2 : 0"</span> <span class="hljs-attr">:w</span>=<span class="hljs-string">"side ? 10 : 12"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">navBar</span> /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Nuxt</span> /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">cusFooter</span> /&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">vs-col</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">vs-row</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">template</span>&gt;</span>
</code></pre>
<pre><code class="lang-html"><span class="hljs-comment">&lt;!-- auth.vue --&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">template</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">navBar</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">Nuxt</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">cusFooter</span> /&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">template</span>&gt;</span>
</code></pre>
<p><strong> So the <code>&lt;Nuxt /&gt;</code> component that you see is responsible for rendering your pages, we'll talk about that later </strong></p>
<p>Now to render the auth layout when you are on the login/register screen all you have to do is add a property called layout in the export object of your page</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> {
  <span class="hljs-attr">layout</span>: <span class="hljs-string">'auth'</span>,
}
</code></pre>
<p>Additionally you can also add an <code>error.vue</code> file which gives you access to the error object and the UI there would be rendered in case you face an error, <strong>An important thing to note you are not supposed to put the <code>&lt;Nuxt /&gt;</code> component there as you would not want your UI to render if there's an error</strong></p>
<h4 id="middlewares">Middlewares</h4>
<p>The files here are supposed to have a butch of middlewares, basically functions that you'd want to run write before the user changes routes. An example would be sending an auth call to check your JWT token or basically any kind of auth that you are using. I haven't played a lot with this yet.</p>
<h4 id="pages">Pages</h4>
<p>This folder would correspond to the Views page in your vue.js project, just with add benefit that you don't need to write your route file, which may /may not be a benefit given your use case.
A few things to remember the folder structure defines your router as in,
a file <code>login.vue</code> could correspond to <code>baseurl/login</code> but a file <code>Auth/login</code> would correspond to <code>baseurl/Auth/login</code>. Additional this comes with a index.vue file which corresponds to the home route.</p>
<h4 id="plugins">Plugins</h4>
<p>Another great feature of nuxt.js is that it supports something called modules/plugins which is essentially wrappers for various commonly used node_modules which are tuned for use with SSR and nuxt specifically. A few plugins that we are using include firebase, axios, content, vuesax, etc.
Here's the <a target="_blank" href="https://modules.nuxtjs.org/">official list of nuxt modules</a>.
You setup, initialize and customize how your modules work in the nuxt.config.js file.</p>
<h4 id="static">Static</h4>
<p>This folder doesn't look like something very fancy but this here to basically keep all your static that will be available in the browser.
<strong>Note you are not supposed to keep any confidential files here</strong></p>
<h4 id="store">Store</h4>
<p>This folder is entirely dedicated to the Vuex store and only exists if you add the vuex module. A few differences  in the normal vuex uses in vanilla Vue.js and nuxt is that here you need to export your state, mutations, actions and all separately from the file instead of exporting a single Vuex object. Plus Nuxt support vuex modules out of the box just create a new file in the store folder and you have a new vuex module</p>
<h3 id="well-disclosure-time-all-of-this-i-leanrt-directly-from-the-nuxtjs-official-documentation-hence-best-documentation">Well disclosure time all of this I leanrt directly from the nuxtjs official documentation, hence <strong>best documentation</strong>.</h3>
<p>Also I have been writing a few flutter blogs here but now that I jumped into Nuxt.js It'll be a fun ride and I wanna share this experience with everyone so I'd be writing more blogs about it so do follow. </p>
]]></content:encoded></item><item><title><![CDATA[My goto flutter packages]]></title><description><![CDATA[Well, it's not a hidden fact that I'm a flutter dev and have encountered various dart packages across my small year-long journey, so here's a list of some…]]></description><link>https://blog.iresharma.com/my-goto-flutter-packages</link><guid isPermaLink="true">https://blog.iresharma.com/my-goto-flutter-packages</guid><category><![CDATA[Hashnode]]></category><category><![CDATA[Flutter]]></category><category><![CDATA[General Programming]]></category><category><![CDATA[Dart]]></category><category><![CDATA[Mobile Development]]></category><dc:creator><![CDATA[Iresh Sharma]]></dc:creator><pubDate>Sat, 12 Dec 2020 07:04:36 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1607756611865/AQZquM22x.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="my-goto-flutter-packages">My goto flutter packages</h1>
<p>Well, it's not a hidden fact that I'm a flutter dev and have encountered various dart packages across my small  year-long journey, so here's a list of some flutter dependencies which I use in almost all my projects:</p>
<h2 id="flutter-iconshttpspubdevpackagesfluttericons"><a target="_blank" href="https://pub.dev/packages/flutter_icons">Flutter Icons</a></h2>
<p>Material and Cupertino icons already included in flutter SDK (Cupertino icons is an added dependency but it's there by default) are really good and sometimes you wanna branch out and move to other design languages. Coming from web background I always had almost infinite options to select from, This package brings the most famous ones directly into fluter:</p>
<p>these include famous ones like:</p>
<ul>
<li>Ant design</li>
<li>font awesome</li>
<li>font awesome 5</li>
<li>feather icons</li>
<li>Ionic icons and many more...</li>
</ul>
<h2 id="floating-bottom-navigation-barhttpspubdevpackagesfloatingbottomnavigationbar"><a target="_blank" href="https://pub.dev/packages/floating_bottom_navigation_bar">Floating Bottom Navigation Bar</a></h2>
<p>I usually don't like using dart packages for UI but this one is really great, it's my go-to bottom navigation bar, the implementation is amazing, the amount of customisation is great and i love the way it looks</p>
<p><img src="https://github.com/right7ctrl/flutter_floating_bottom_navigation_bar/blob/master/image.png?raw=true" /></p>
<p>I think it looks really good and this package covers my need for any kinda bottom bar.</p>
<h2 id="lottiehttpslottiefilescom"><a target="_blank" href="https://lottiefiles.com">Lottie</a></h2>
<p>This is an animation package which provides you with really good looking high-end animation to bring your app to life, you can replace the boring old <code>CircularProgressIndicator()</code> with Lottie animations.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1607755511794/gtXrEx8KQ.gif" alt="animation_500_kik3zowe.gif" /></p>
<p>Now, this is a place where a lot of people would argue that rive/flare is much better because they worked closely with flutter team, well true they did work with flutter team but the point is Lottie has been doing this for much much longer and already supports all platforms that's why they much-assorted array docs and has a lot more community-sourced animation than rive and personally I have had a better developer experience with Lottie then with rive.</p>
<h2 id="loggerhttpsgithubcomleisimlogger"><a target="_blank" href="https://github.com/leisim/logger">Logger</a></h2>
<p>Well, this is a great one, remember those times. when you are using an emulator and it starts spitting java or swift logs right on the debug console and you can't find your print statements 😢.</p>
<p>Well, that's why I prefer Logger a dependency made by <a target="_blank" href="https://github.com/leisim">Simon Leier</a>, the creator of hivedb a NoSQL database for flutter. Well, I don't really need to talk a lot about this let me just show you the logs that this package prints.</p>
<p><img src="https://raw.githubusercontent.com/leisim/logger/master/art/screenshot.png" alt="https://raw.githubusercontent.com/leisim/logger/master/art/screenshot.png" /></p>
<p>Another part you don't really need to connect your phone to laptop and try recreating that one bug which random appeared from nowhere, at least on your dev builds you can add a button that directly opens the logger console on the app.</p>
<p><code>LogConsole.open(context)</code> add a button that runs this function and viola you have a console on your app showing the logs</p>
<p><img src="https://raw.githubusercontent.com/leisim/logger/master/art/log_console_light.png" alt="https://raw.githubusercontent.com/leisim/logger/master/art/log_console_light.png" /></p>
<h2 id="flutter-screenutilhttpspubdevpackagesflutterscreenutil"><a target="_blank" href="https://pub.dev/packages/flutter_screenutil">Flutter ScreenUtil</a></h2>
<p>Well, this package deserves a blog on it own, this is my goto solution to text scaling and responsiveness in general. It's a package that lets you define the size of the device that using to make the designs and then it handles the text scaling and other nicknack given you use <code>ScreenUtil().foo</code> to define the values. It mostly handles all my responsiveness needs.</p>
<p><strong>Note: using this doesn't mean you don't have to write media queries, all it does is reduces the number of media queries you write by a long shot</strong></p>
<h2 id="providerhttpspubdevpackagesprovider"><a target="_blank" href="https://pub.dev/packages/provider">Provider</a></h2>
<p>Well, I really don't need to talk about it, and honestly, I ain't qualified enough to talk provider or complex state management like BLoc or riverpod. I haven't really explored this a lot but I mostly find everything that I want to do can be done with provider so I don't wander a lot.</p>
<h2 id="flutter-toasthttpspubdevpackagesfluttertoast"><a target="_blank" href="https://pub.dev/packages/fluttertoast">Flutter Toast</a></h2>
<p>Ever got into the mess where no matter what you try a simple error,</p>
<p><code>Scaffold.of(context) context does not contain a Scaffold</code> ??</p>
<p>Trying to show a snackbar to tell your user something happened and all you get is an error, well here's a solution. Flutter Toast is a buildContext free toast package that works on both iOS and Android. This gives you more than enough customisation to make it look like to want it to</p>
<p><img src="https://raw.githubusercontent.com/ponnamkarthik/FlutterToast/master/screenshot/11.jpg" alt="https://raw.githubusercontent.com/ponnamkarthik/FlutterToast/master/screenshot/11.jpg" /></p>
<h2 id="flutter-svghttpspubdevpackagesfluttersvg"><a target="_blank" href="https://pub.dev/packages/flutter_svg">Flutter SVG</a></h2>
<p>Flutter is not an HTML renderer and hence does not support SVGs right of the back. So here's a package which until a few months ago had the most reliable SVG support for flutter. Sadly It has not been working with flutter 1.22 as of right now but I still put it in the list as it has some community support and I am hoping they soon release and update and fix it.</p>
<h2 id="url-launcherhttpspubdevpackagesurllauncher"><a target="_blank" href="https://pub.dev/packages/url_launcher">URL Launcher</a></h2>
<p>Ever wanted to open a link from inside your app ??</p>
<p>Well URL launcher can let you do that, not just that we can also open the dialer by changing the protocol from HTTP to tel so <code>launch('tel:8888888888')</code> opens the dialer using <code>mailto:</code> we can change to the default email client and same works for SMS with <code>sms:</code> protocol</p>
<h2 id="flutter-blurhashhttpspubdevpackagesflutterblurhash"><a target="_blank" href="https://pub.dev/packages/flutter_blurhash">Flutter Blurhash</a></h2>
<p>Ever wondered how Instagram has that blur version of image right before it loads up the proper version of the image? Well, I don't know how they do it, I for sure how to implement that, with a package called blurhash.</p>
<p><img src="https://user-images.githubusercontent.com/1295961/75059847-129d6800-54de-11ea-8832-d19ea58eb7eb.png" alt="https://user-images.githubusercontent.com/1295961/75059847-129d6800-54de-11ea-8832-d19ea58eb7eb.png" /></p>
<p>You can use your backend microservice to generate a hash for every image upload and send that hash along with the image then you can use the blurhash package like </p>
<pre><code class="lang-dart">AspectRatio(
  aspectRatio: <span class="hljs-number">1.6</span>,
  child: BlurHash(hash: <span class="hljs-string">"L5H2EC=PM+yV0g-mq.wG9c010J}I"</span>),
),
</code></pre>
<p>The blurhash widget takes in a hash, shows that until the network image is completely loaded and then shows that</p>
<h2 id="afterlayouthttpspubdevpackagesafterlayout"><a target="_blank" href="https://pub.dev/packages/after_layout">after_layout</a></h2>
<p>Brings functionality to execute code after the first layout of a widget has been performed, i.e. after the first frame has been displayed.</p>
<p>Add with <code>AfterLayoutMixin&lt;MyWidget&gt;</code> mixin to your <code>State&lt;MyWidget&gt;</code> class and then implement the <code>void afterFirstLayout(BuildContext context)</code> abstract method. Code in this method will be called the first time this widget is laid out on the screen.</p>
]]></content:encoded></item><item><title><![CDATA[Type safe http calls in Flutter with Chopper]]></title><description><![CDATA[I am not sure about you but for me when I started working with Flutter (or dart) I had great difficulty in handling API calls and JSON responses because of…]]></description><link>https://blog.iresharma.com/chopper-flutter</link><guid isPermaLink="true">https://blog.iresharma.com/chopper-flutter</guid><category><![CDATA[Flutter]]></category><category><![CDATA[Dart]]></category><category><![CDATA[REST API]]></category><category><![CDATA[Hashnode]]></category><category><![CDATA[General Programming]]></category><dc:creator><![CDATA[Iresh Sharma]]></dc:creator><pubDate>Tue, 08 Dec 2020 18:30:34 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1607451501854/NvuwkuSfj.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="type-safe-http-calls-in-flutter-with-chopper">Type safe HTTP calls in Flutter with Chopper</h1>
<h2 id="problem">Problem:</h2>
<p>I am not sure about you but for me when I started working with Flutter (or dart) I had great difficulty in handling API calls and JSON responses because of lack of a native JSON support as easy as python or Js (the languages I was previously working with), I mean the data type <code>Map&lt;String, dynamic&gt;</code> is almost equivalent to a JSON but naah. Also, I believe when you are going with a strictly typed language like dart you would like your API responses to also be dart objects rather than a random Map.</p>
<p>Well my current project requires a lot of communication with an Express-based API, initially I was using flutter team's own <a target="_blank" href="https://pub.dev/packages/http">http package</a> which was really good but adding query parameters and headers in them is terribly handled and in short, I don't like it.</p>
<h5 id="thats-when-i-came-across-chopper-which-is-dubbed-as-retrofit-for-flutter-this-is-what-ill-be-talking-about-in-this-blog">That's when I came across <strong>Chopper</strong> which is dubbed as <strong><em>retrofit for flutter,</em></strong> this is what I'll be talking about in this blog</h5>
<h1 id="solution-chopperhttpspubdevpackageschopper">Solution: <a target="_blank" href="https://pub.dev/packages/chopper">Chopper</a></h1>
<p>Well chopper is a flutter package that helps you simplify your REST call</p>
<h2 id="apihttp-calls-will-be-handled-using-chopper">API/HTTP calls will be handled using chopper</h2>
<pre><code class="lang-dart"><span class="hljs-keyword">import</span> <span class="hljs-string">'package:chopper/chopper.dart'</span>;

<span class="hljs-comment">// the line below is strictly supposed to be &lt;fileName&gt;.chopper.dart</span>
<span class="hljs-keyword">part</span> <span class="hljs-string">'chopper.chopper.dart'</span>;

<span class="hljs-meta">@ChopperApi</span>(baseUrl: <span class="hljs-string">'api/v1/'</span>)
<span class="hljs-keyword">abstract</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">API</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">ChopperService</span> </span>{
  <span class="hljs-meta">@Get</span>()
  Future&lt;Response&gt; getter();

  <span class="hljs-meta">@Post</span>()
  Future&lt;Response&gt; post(<span class="hljs-meta">@Body</span>() <span class="hljs-built_in">Map</span>&lt;<span class="hljs-built_in">String</span>, <span class="hljs-built_in">dynamic</span>&gt; body);

  <span class="hljs-keyword">static</span> API create() {
    <span class="hljs-keyword">final</span> client = ChopperClient(
        baseUrl: <span class="hljs-string">'https://d2def3d9f930.ngrok.io/'</span>,
        services: [_$API()],
        converter: JsonConverter());
  }
}
</code></pre>
<p>Well, chopper is one those dependencies which generate code for you <strong><em>coooool,</em></strong> that's why we need the <em>part of</em> directive.</p>
<p>The above snippet is the simplest implementation of the chopper packages without any type safety or interceptors. Showing only 2 calls a get and a post request both to <code>https://d2def3d9f930.ngrok.io/api/v1</code></p>
<p>we can run the following command to build the .chopper.dart file</p>
<pre><code class="lang-bash">flutter packages pub run build_runner watch
</code></pre>
<p>Your Service should be an abstract class and should extend the ChopperService class</p>
<p>The decorator @ChopperAPI is needed as it defines the abstract class (or interface) as a ChopperService</p>
<p>Every call is a separate function and the method is defined by the corresponding decorator, which takes in a fixe</p>
<ul>
<li>path: the path duh 🤷🏻</li>
<li>headers&gt;: A dictionary/Map of headers apart from default ones</li>
</ul>
<h5 id="dynamic-decorators-as-parameters">Dynamic decorators as parameters</h5>
<p>This is followed by a list of parameters to the actual function, these need to specified with suitable decorators like</p>
<ul>
<li><p>@Path: if you have a variable path as in you send a user id or order id in your path itself you can use this directive</p>
<pre><code class="lang-dart">  <span class="hljs-meta">@Get</span>(path: <span class="hljs-string">'/hashnode/{user}'</span>)
  Future&lt;Response&gt; getUser(<span class="hljs-meta">@Path</span> <span class="hljs-built_in">String</span> userId);
</code></pre>
</li>
<li><p>@Query: To send query parameters with the call</p>
<pre><code class="lang-dart">  <span class="hljs-meta">@Get</span>(path: <span class="hljs-string">'/hashnode/iresharma'</span>)
  Future&lt;Response&gt; getUser(<span class="hljs-meta">@Query</span>(<span class="hljs-string">'search'</span>) <span class="hljs-built_in">String</span> searchString);
</code></pre>
</li>
<li><p>@QueryMap: To send a series of Query parameters you can use this directive to pass a Map which will be converted to multiple queries</p>
<pre><code class="lang-dart">  <span class="hljs-meta">@Get</span>(path: <span class="hljs-string">'/hashnode/iresharma'</span>)
  Future&lt;Response&gt; getUser(<span class="hljs-meta">@QueryMap</span>() <span class="hljs-built_in">Map</span>&lt;<span class="hljs-built_in">String</span>, <span class="hljs-built_in">dynamic</span>&gt; queries);
</code></pre>
</li>
<li><p>@Headers: To send headers along, I am not sure but this is the only way you can send dynamic headers</p>
<pre><code class="lang-dart">  <span class="hljs-meta">@Get</span>(path: <span class="hljs-string">'/hashnode/iresharma'</span>)
  Future&lt;Response&gt; getUser(<span class="hljs-meta">@Headers</span>(<span class="hljs-string">'search'</span>) <span class="hljs-built_in">String</span> searchString);
</code></pre>
</li>
<li><p>@Body: To send a Body in case of POST or PUT or PATCH request</p>
<pre><code class="lang-dart">  <span class="hljs-meta">@Post</span>(path: <span class="hljs-string">'/hashnode/iresharma'</span>)
  Future&lt;Response&gt; getUser(<span class="hljs-meta">@Body</span>() <span class="hljs-built_in">Map</span>&lt;<span class="hljs-built_in">String</span>, <span class="hljs-built_in">dynamic</span>&gt; queries);
</code></pre>
</li>
</ul>
<h3 id="lets-talk-about-the-request-and-response-objects">Let's talk about the <code>Request</code> and <code>Response</code> objects</h3>
<ul>
<li><p><strong>Response Object</strong></p>
<p>  The response object is pretty simple and has only a few attributes</p>
<ul>
<li><p>base</p>
<p>  which contains the Request, statuscode and some stuff</p>
</li>
<li><p>Body</p>
<p>  this contains body of the response. The datatype  is determined by the converter you use</p>
</li>
<li><p>error</p>
</li>
</ul>
</li>
<li><p><strong>Request Object</strong></p>
<p>  Well here's the variable declaration for the Request class</p>
<pre><code class="lang-dart">      <span class="hljs-keyword">final</span> <span class="hljs-built_in">String</span> method;
    <span class="hljs-keyword">final</span> <span class="hljs-built_in">String</span> baseUrl;
    <span class="hljs-keyword">final</span> <span class="hljs-built_in">String</span> url;
    <span class="hljs-keyword">final</span> <span class="hljs-built_in">dynamic</span> body;
    <span class="hljs-keyword">final</span> <span class="hljs-built_in">List</span>&lt;PartValue&gt; parts;
    <span class="hljs-keyword">final</span> <span class="hljs-built_in">Map</span>&lt;<span class="hljs-built_in">String</span>, <span class="hljs-built_in">dynamic</span>&gt; parameters;
    <span class="hljs-keyword">final</span> <span class="hljs-built_in">Map</span>&lt;<span class="hljs-built_in">String</span>, <span class="hljs-built_in">String</span>&gt; headers;
    <span class="hljs-keyword">final</span> <span class="hljs-built_in">bool</span> multipart;
</code></pre>
<p>  it's pretty self-explanatory</p>
</li>
</ul>
<h2 id="interceptors">Interceptors</h2>
<p>Interceptors are basically a set of commands that are run with every command</p>
<p>All interceptors are client wide</p>
<p>we put interceptors inside the client</p>
<pre><code class="lang-dart"><span class="hljs-keyword">static</span> API create() {
    <span class="hljs-keyword">final</span> client = ChopperClient(
        baseUrl: <span class="hljs-string">'https://d2def3d9f930.ngrok.io'</span>,
        services: [_$API()],
                interceptors: [],
        converter: JsonConverter());
  }
</code></pre>
<p>A few built-in interceptors are:</p>
<ul>
<li><p>HeadersInterceptor</p>
<pre><code class="lang-dart">  <span class="hljs-keyword">static</span> API create() {
      <span class="hljs-keyword">final</span> client = ChopperClient(
          baseUrl: <span class="hljs-string">'https://d2def3d9f930.ngrok.io'</span>,
          services: [_$API()],
                  interceptors: [
                      HeadersInterceptor({<span class="hljs-string">'Content-type'</span>: <span class="hljs-string">'Application/json'</span>})
                  ],
          converter: JsonConverter());
    }
</code></pre>
<p>  The above code will add the <code>'Content-type': 'Application/JSON'</code> header to all the requests that it makes.</p>
</li>
<li><p>HttpLoggingInterceptor</p>
<p>  We use this header to log everything that's happening with the request, but this requires some setup which is as follows:</p>
<p>  we include the logging package which is preloaded by chopper.</p>
<p>  Add make the following changes to main.dart</p>
<pre><code class="lang-dart">  <span class="hljs-keyword">void</span> main() {
          Logger.root.level = Level.ALL;
          Logger.root.onRecord((rec) {
              <span class="hljs-built_in">print</span>(<span class="hljs-string">'<span class="hljs-subst">${rec.level) ${rec.message}</span>);        
          });
          runApp(MyAPP());
  }</span>
</code></pre>
<p>  The above code will instantiate the Logger and now we can add the <code>HttpLoggingInterceptor</code> interceptor to the Client</p>
<pre><code class="lang-dart">  <span class="hljs-keyword">static</span> API create() {
      <span class="hljs-keyword">final</span> client = ChopperClient(
          baseUrl: <span class="hljs-string">'https://d2def3d9f930.ngrok.io'</span>,
          services: [_$API()],
                  interceptors: [
                      HeadersInterceptor({<span class="hljs-string">'Content-type'</span>: <span class="hljs-string">'Application/json'</span>}),
                      HttpLoggingInterceptor()
                  ],
          converter: JsonConverter());
    }
</code></pre>
<p>  <strong>I personally use a custom logging interceptor, this prints way more information than needed and makes the debug console very very messy</strong></p>
</li>
<li><p>CurlInterceptor</p>
<p>  This is not used as much but It's really cool because it prints out the curl command for the request just made</p>
<h3 id="custom-interceptors">Custom interceptors</h3>
<p>  +— async functions</p>
<p>  +— class-based</p>
<p>  <strong>Async Functions</strong></p>
<p>  we can create both request and response interceptors and I'd suggest not using the HttpLoggingInterceptor because it logs a lot of not so important information like the whole response which may make the more important information like the route, headers and query parameter difficult to read</p>
<pre><code class="lang-dart">  <span class="hljs-keyword">static</span> API create() {
      <span class="hljs-keyword">final</span> client = ChopperClient(
          baseUrl: <span class="hljs-string">'https://d2def3d9f930.ngrok.io'</span>,
          services: [_$API()],
                  interceptors: [
                      HeadersInterceptor({<span class="hljs-string">'Content-type'</span>: <span class="hljs-string">'Application/json'</span>}),
                      <span class="hljs-comment">// HttpLoggingInterceptor(),</span>
                      (Request req) <span class="hljs-keyword">async</span> {
                              chopperLogger.info(<span class="hljs-string">'<span class="hljs-subst">${req.headers}</span>'</span>);
                              <span class="hljs-comment">// VERY VERY IMPORTANT TO RETURN req</span>
                              <span class="hljs-keyword">return</span> req;
                      }
                  ],
          converter: JsonConverter());
    }
</code></pre>
<p>  The above code is an example of request interceptor which logs the headers of the request, note it's <strong>very very important to return the req back from the function</strong> because the way it's made it does not give a lint but ends up crashing or compilation error</p>
<p>  below is an example of a response interceptor</p>
<pre><code class="lang-dart">  <span class="hljs-keyword">static</span> API create() {
      <span class="hljs-keyword">final</span> client = ChopperClient(
          baseUrl: <span class="hljs-string">'https://d2def3d9f930.ngrok.io'</span>,
          services: [_$API()],
                  interceptors: [
                      HeadersInterceptor({<span class="hljs-string">'Content-type'</span>: <span class="hljs-string">'Application/json'</span>}),
                      <span class="hljs-comment">// HttpLoggingInterceptor(),</span>
                      (Request req) <span class="hljs-keyword">async</span> {
                              chopperLogger.info(<span class="hljs-string">'<span class="hljs-subst">${req.headers}</span>'</span>);
                              <span class="hljs-comment">// VERY VERY IMPORTANT TO RETURN req</span>
                              <span class="hljs-keyword">return</span> req;
                      },
                      (Response res) {
                          chopperLogger(<span class="hljs-string">'<span class="hljs-subst">${res.statusCode}</span>'</span>);
                      }
                  ],
          converter: JsonConverter());
    }
</code></pre>
<p>  <strong>Custom Class-based interceptors</strong></p>
<p>  Well according to our need we can have various reasons and functionality where we'd want to have interceptors but here we are gonna implement a simple interceptor which does not make the request if the user is on mobile data</p>
<p>  Important to note the below example uses <code>connectivity</code> package </p>
<pre><code class="lang-dart">  <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MobileDataInterceptor</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">RequestInterceptor</span> </span>{
      <span class="hljs-meta">@override</span>
      FutureOr&lt;Request&gt; onRequest(Request req) {
          <span class="hljs-keyword">final</span> connection = <span class="hljs-keyword">await</span> connectivity().checkConnnectivity();
          <span class="hljs-keyword">if</span>(connection == ConnenctivityResult.mobile) {
                  <span class="hljs-comment">// throw an appropriate exception</span>
          }
          <span class="hljs-keyword">return</span> req;
      }
  }
</code></pre>
</li>
</ul>
<h3 id="custom-convertors">Custom convertors</h3>
<p>The code below is a generic converter</p>
<pre><code class="lang-dart"><span class="hljs-keyword">import</span> <span class="hljs-string">'dart:convert'</span>;

<span class="hljs-keyword">import</span> <span class="hljs-string">'package:chopper/chopper.dart'</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">GenericConvertor</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">JsonConverter</span> </span>{
  <span class="hljs-keyword">final</span> <span class="hljs-built_in">Map</span>&lt;<span class="hljs-built_in">Type</span>, <span class="hljs-built_in">Function</span>&gt; typeToJsonFactoryMap;

  GenericConvertor(<span class="hljs-keyword">this</span>.typeToJsonFactoryMap);

  <span class="hljs-meta">@override</span>
  Response&lt;BodyType&gt; convertResponse&lt;BodyType, InnerType&gt;(Response response) {
    <span class="hljs-keyword">return</span> response.copyWith(
      body: fromJsonData&lt;BodyType, InnerType&gt;(
          response.body, typeToJsonFactoryMap[InnerType]),
    );
  }

  T fromJsonData&lt;T, InnerType&gt;(<span class="hljs-built_in">String</span> jsonData, <span class="hljs-built_in">Function</span> jsonParser) {
    <span class="hljs-keyword">var</span> jsonMap = json.decode(jsonData);
    <span class="hljs-keyword">if</span> (jsonMap <span class="hljs-keyword">is</span> <span class="hljs-built_in">List</span>) {
      <span class="hljs-keyword">return</span> jsonMap
          .map((item) =&gt; jsonParser(item <span class="hljs-keyword">as</span> <span class="hljs-built_in">Map</span>&lt;<span class="hljs-built_in">String</span>, <span class="hljs-built_in">dynamic</span>&gt;) <span class="hljs-keyword">as</span> InnerType)
          .toList() <span class="hljs-keyword">as</span> T;
    }

    <span class="hljs-keyword">return</span> jsonParser(jsonMap);
  }
}
</code></pre>
<p>How does this work ???</p>
<p>well the convertor is called like</p>
<pre><code class="lang-dart">GenericConvertor({
  UserModel: (jsonData) =&gt; UserModel.fromJson(jsonData),
  AuthCheck: (jsonData) =&gt; AuthCheck.fromJson(jsonData)
})
</code></pre>
<p>Basically, it takes in a <code>Map&lt;Type, function&gt;</code> corresponding to the class and the fromJson() function for each type</p>
<p>Then it runs a function which copies the response object and replaces the body with the object we want</p>
<p>it does that running the fromJson function and encoding the object as a bodyType, as required by the response object.</p>
<p><strong>Even though it handles the list but that only works if the body of your response is directly a list else it breaks, and this true for normal values as well it works only if the body is directly the object you want</strong></p>
<p>For a case where the data structure is different, you use the code snippet below as reference to write a custom converter</p>
<p>the data i received had body['chapters'] = List so i had to use this convertor</p>
<pre><code class="lang-dart"><span class="hljs-keyword">import</span> <span class="hljs-string">'dart:convert'</span>;

<span class="hljs-keyword">import</span> <span class="hljs-string">'package:chopper/chopper.dart'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'package:learners/models/DataModels/Chapters/chapterModel.dart'</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SubjectConvertor</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">JsonConverter</span> </span>{
  <span class="hljs-meta">@override</span>
  Response&lt;BodyType&gt; convertResponse&lt;BodyType, InnerType&gt;(Response response) {
    <span class="hljs-keyword">return</span> response.copyWith(
      body: fromJsonData&lt;BodyType, InnerType&gt;(response.body),
    );
  }

  T fromJsonData&lt;T, InnerType&gt;(<span class="hljs-built_in">String</span> jsonData) {
    <span class="hljs-keyword">var</span> jsonMap = json.decode(jsonData);
    <span class="hljs-built_in">List</span>&lt;<span class="hljs-built_in">dynamic</span>&gt; chapters = jsonMap[<span class="hljs-string">'chapters'</span>];
    <span class="hljs-keyword">if</span> (chapters == <span class="hljs-keyword">null</span>) {
      <span class="hljs-keyword">return</span> ChapterModel.fromJson(jsonMap[<span class="hljs-string">'chapter'</span>]) <span class="hljs-keyword">as</span> T;
    }
    <span class="hljs-keyword">return</span> chapters.map((e) =&gt; ChapterModel.fromJson(e)).toList() <span class="hljs-keyword">as</span> T;
  }
}
</code></pre>
<h5 id="for-more-watch-the-tutorial-by-reso-coder">for more watch the tutorial by reso coder</h5>
<p><a target="_blank" href="https://www.youtube.com/watch?v=zFXK5EsrUF0">ResoCoder Chopper</a></p>
]]></content:encoded></item></channel></rss>