<?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" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Pavel Bernshtam on Medium]]></title>
        <description><![CDATA[Stories by Pavel Bernshtam on Medium]]></description>
        <link>https://medium.com/@javaap?source=rss-95faca73a77f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*CifyzOnRatLclE_r.</url>
            <title>Stories by Pavel Bernshtam on Medium</title>
            <link>https://medium.com/@javaap?source=rss-95faca73a77f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 17:26:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@javaap/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Три битвы у нашего дома. Ноябрь 1917]]></title>
            <link>https://medium.com/@javaap/%D1%82%D1%80%D0%B8-%D0%B1%D0%B8%D1%82%D0%B2%D1%8B-%D1%83-%D0%BD%D0%B0%D1%88%D0%B5%D0%B3%D0%BE-%D0%B4%D0%BE%D0%BC%D0%B0-%D0%BD%D0%BE%D1%8F%D0%B1%D1%80%D1%8C-1917-08475801eac3?source=rss-95faca73a77f------2</link>
            <guid isPermaLink="false">https://medium.com/p/08475801eac3</guid>
            <category><![CDATA[wwi]]></category>
            <category><![CDATA[war]]></category>
            <category><![CDATA[israel]]></category>
            <category><![CDATA[history]]></category>
            <category><![CDATA[palestine]]></category>
            <dc:creator><![CDATA[Pavel Bernshtam]]></dc:creator>
            <pubDate>Tue, 01 Sep 2026 08:36:41 GMT</pubDate>
            <atom:updated>2026-10-21T12:01:31.617Z</atom:updated>
            <content:encoded><![CDATA[<p>Все три места — в пятнадцати-двадцати минутах езды от дома. Их видно с шоссе 40 и с холмов вокруг Реховота.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*P0NJUKjWmGN5yB5Q.png" /><figcaption><em>Реховот, Гедера, Нес-Циона, Ришон. Три боя, четыре дня.</em></figcaption></figure><p>За четыре дня, с 13 по 16 ноября 1917 года, здесь произошли три боя: Эль-Мугар, Аюн-Кара, Абу-Шуше. Они почти прорвали турецко-германский фронт и открыли британцам дорогу на Яффо и Иерусалим.</p><p>Про Беэр-Шеву знают все. Про эти три — почти никто. Ни в Израиле, ни тем более снаружи.</p><h3>Как страна дошла до этой точки</h3><p>Османская империя входит в войну на стороне Германии и Австро-Венгрии в конце 1914-го. Палестина становится дальним, но настоящим фронтом: сначала британцы держат Суэцкий канал, потом идут через Синай.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Fyo7Ju2-chfuvJVA.jpg" /><figcaption>Кампания Алленби в Палестине, 1917–1918.</figcaption></figure><p>В марте и апреле 1917-го — две атаки на Газу. Тяжёлые потери, без результата. Линия замирает на несколько месяцев.</p><p>В июне командование Египетским экспедиционным корпусом получает генерал Эдмунд Алленби. Энергичный, пассивности не терпит. Лондон говорит прямо: возьмите Иерусалим до Рождества. Рождественский подарок британской публике после мрачного года на Западном фронте.</p><p>Алленби не бьёт в Газу в лоб. Скрытно перебрасывает силы к Беэр-Шеве, на восточный фланг. Там мало воды, наступление через пустыню считалось почти невозможным. Турки удара не ждут.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/0*dFo8-BRboFRBT1Se.jpg" /><figcaption>Falls, Military Operations Egypt &amp; Palestine, 1930. Ситуация после прорыва.</figcaption></figure><p>31 октября австралийская и новозеландская конная дивизия берёт Беэр-Шеву в тот же день. 4-я австралийская конная бригада успевает захватить колодцы неповреждёнными. Линия Газа–Беэр-Шева, которую держали почти год, рушится за несколько дней.</p><p>До Иерусалима ещё почти полтора месяца. Три боя из них — буквально у нас на пороге.</p><p>После Газы и Беэр-Шевы турецкие 7-я и 8-я армии отходят на север. Новая линия — гряда холмов Катра–Эль-Мугар, барьер из куркара, местного песчаника, над прибрежной равниной.</p><p>Ключ — станция Вади-Сарар, она же Джанкшн-Стейшн. Железнодорожный узел: линии на Иерусалим и на Яффо. Возьмут узел — две турецкие армии окажутся разъединены и не смогут поддерживать друг друга. За это и идут бои 12–16 ноября. Все в пределах одного взгляда от Реховота.</p><p>Но жители поселений встречают британцев в ситуации, когда еврейский ишув уже несколько лет находится в очень сложном положении.</p><p>В 1915-м — одно из крупнейших нашествий саранчи в истории страны. Почти пять месяцев едят посевы, виноградники, деревья. Сверху — военный голод и эпидемии.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*n6cVqVu-UD_FKvSs.jpg" /><figcaption>Саранча, 1915. Library of Congress, American Colony Photo Dept.</figcaption></figure><p>Йехиэль Михаэль Похачевский из Ришон-ле-Циона описывает тучи, закрывающие солнце: «ולפתע פתאום רואה לפני עיניו עננים כבדים המכסים את פני השמש». Сам говорит, что встретился лицом к лицу с жёлтым ангелом смерти.</p><p>В апреле 1917-го Джемаль-паша приказывает выселить всё еврейское и часть арабского населения Яффо и Тель-Авива. Около 10 000 человек на дорогах. Многие уходят в Галилею. Часть гибнет от болезней и голода. Жители Петах Тивкы отказываются принять беженцев.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*414L1r5JJZ_wtPyR.jpg" /><figcaption>Памятник изгнанным из Яффо и Тель-Авива. Кладбище Киннерет.</figcaption></figure><p>Похачевский: «ועוד מעט תור יפו תל אביב יגיע… הלב נקרע לאכזריות כזו שפגשנו פנים אל פנים» — «скоро и до Яффо-Тель-Авива дойдёт черёд… сердце разрывается от такой жестокости, с которой мы столкнулись лицом к лицу».</p><p>На фоне депортаций Джемаль-паша говорит ещё жёстче: прежде чем англичане успеют войти, он не оставит камня на камне от еврейских поселений в этой стране. Примерно в тоже время османские власти обнаруживают подполье “Нили” которое шпионило для англичан. На еврейский ишув обрушиваются репрессии.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/0*SvQFF-HNJ9fOJNfE.jpg" /><figcaption>Джемаль-паша.</figcaption></figure><p>В тех же мемуарах — другой образ: англичан ждут «как жених ждёт невесту». Ужас перед резнёй и почти мессианская надежда. В этом напряжении застаёт поселения ноябрь 1917-го.</p><h3>Эль-Мугар, 13 ноября</h3><p>На британских и османских военных картах 1917 года Реховота нет. Есть Zernuka.</p><p>Карты Египетского экспедиционного корпуса сидят на съёмке Palestine Exploration Fund 1870–1880-х. Реховот основан в 1890-м, на землях полузаброшенного имения Хирбет-Дейран. Военные картографы спешно рисовали окопы и колодцы. Базовую топонимику часто не трогали.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S436XWT7E8Ygwt4jH1m01w.png" /></figure><p>Zernuka — это Зарнука, большая арабская деревня. Веками на месте, окружена кактусовыми изгородями и садами, нормальный ориентир. Сейчас там реховотский Кирьят-Моше.</p><p>Утро 13 ноября. Две турецкие армии на хребте Катра–Эль-Мугар. Куркар — окаменевший песчаник, прибрежная гряда параллельно морю. Единственная существенная возвышенность на пути от Газы к Яффо. Около 3000 турок с пулемётами и артиллерией. Позиция почти идеальная.</p><p>Сегодня на этом месте — национальный парк Гваот-Мрар, у 40-го шоссе. До Реховота несколько минут.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TdBlcsrcx-lJlPS8.jpg" /><figcaption>Национальный парк Гивот-Мрар. На вырезе щита — кавалерист.</figcaption></figure><p>52-я дивизия, шотландская низменная пехота, должна взять высоту за день. Иначе турки закрепятся на следующей линии, и вся операция потеряет темп.</p><p>Утренняя атака захлёбывается. Наступающие залегают в вади Джамус — сухое русло, простреливаемое почти по всей длине. Продвижения нет. Потери растут.</p><p>К середине дня ясно: пехота одна хребет не возьмёт. Если турки продержатся до ночи — перегруппируются.</p><p>И тогда 6-я конная дивизия делает то, что учебники потом называют почти самоубийством: бросает кавалерию через открытую равнину на пулемёты и артиллерию. На Западном фронте эту тактику уже похоронили. Здесь, на открытом театре, у неё внезапно оказывается шанс.</p><p>В 14:30 6-я конная бригада — три йоменских полка, Бакингемшир, Беркшир, Дорсет — выстраивается в лаву и идёт три километра по совершенно открытому полю. Сначала рысью, чтобы сохранить строй и не выдохнуть лошадей. Потом галоп, уже под огнём.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*SikgLudxPSBo_m76.jpg" /><figcaption>James Prinsep Beadle, «The Action of the 6th Mounted Brigade at El Mughar», 1922.</figcaption></figure><p>Гребень взят. Турецкая позиция смята. У бригады — 16 убитых, 114 раненых, 265 убитых или раненых лошадей. У турок — около 1400 пленных, орудия, пулемёты.</p><p>Одну из последних крупных кавалерийских атак в военной истории заканчивают на холме под Гедерой.</p><p>Йомены — это не кадровая кавалерия. Территориальные конные полки по графствам. Формально резерв. Что-то среднее между регулярной армией и ополчением землевладельцев и фермеров. И именно они несут главный удар.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/0*Vrjt2xNjXF-Q96_C.jpg" /><figcaption>Berkshire Yeomanry в Палестине, 1917.</figcaption></figure><p>Символ атаки — маленький эпизод. Командир видит, как капрал Уиттл вырывается далеко вперёд, и орёт: «Ты что творишь?!» Тот на скаку: «Сэр, у меня сегодня день рождения, и это лучший день в моей жизни!»</p><p>Среди атакующих — майор Эвелин Ашиль де Ротшильд, 1886–1917, сын банкира Леопольда де Ротшильда, офицер Royal Bucks Hussars. Тяжело ранен пулей на середине равнины. Умирает от ран в госпитале Каирской цитадели 17 ноября, через четыре дня.</p><p>Его двоюродный брат Нил Примроуз погибнет через два дня при Абу-Шуше.</p><p>Ротшильда сначала хоронят в Каире. В 1919-м останки перезахоронили на еврейском кладбище Ришон-ле-Циона. Представитель семьи, которая поддерживала заселение страны, возвращается на эту землю уже навсегда.</p><p>Похачевский пишет из Ришона, из вторых-третьих рук, и у него история уже плывёт: «בקְרָב על יד גדרה נפלו שני אפיצרים ממשפחת הרוטשילדים» — «в бою у Гедеры погибли два офицера из семьи Ротшильдов».</p><p>На самом деле это два разных боя. Эвелин де Ротшильд — Эль-Мугар, 13-е. Нил Примроуз, Ротшильд по материнской линии — Абу-Шуше, 15-е. Слухи склеили соседние дни в один.</p><p>Саму Гедеру тоже задело: синагогу обстреляли и частично обрушили. В 2025-м школьник в роще недалеко от неё нашёл шрапнельный снаряд. Сто восемь лет в земле.</p><p>Взятие хребта открывает путь к Джанкшн-Стейшн.</p><p>Французская Яффо — Иерусалим шла так: Яффо → Рамле → Лод → Wadi Surar → Иерусалим. В 1915-м османы сделали там военную развязку. От Вади-Сарар — линия на юг, к Беэр-Шеве, Газе и фронту. Поэтому станция и стала узлом. (Впрочем жд линии до яффы в 17-м уже не было, турки разобрали её до лода на стройматериалы для своей ветки на синай.)</p><p>14 ноября станция падает. 8-я турецкая армия уходит на север, к Яффо. 7-я — на восток, в Иудейские горы, к Иерусалиму. Две армии разъединены. Это и было задачей.</p><p>Пока штабы разбираются со станцией, севернее, в дюнах между Нес-Ционой и Ришон-ле-Ционом, уже начинается второй бой.</p><h3>Аюн-Кара, 14 ноября</h3><p>Новозеландская конная стрелковая бригада идёт на север, к Яффо, за отступающими турками. И натыкается на арьергард в дюнах — около 1500 человек.</p><p>При Эль-Мугаре у британцев было явное превосходство. Здесь силы примерно равны. Редкий случай для всей палестинской кампании. Поэтому не кавалерийский рывок, а тяжёлый ближний бой. Целиком под новозеландским командованием.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/0*JHvijV6wr0VJSc55.jpg" /><figcaption>Карта атаки при Аюн-Кара. <a href="http://nzhistory.govt.nz/">nzhistory.govt.nz</a>, тропы Ngā Tapuwae.</figcaption></figure><p>Разведки контакта почти нет. Противник обнаруживает себя первым огнём. Местность — не открытая равнина, песчаные гряды и заросли. Галопом не взять. Спешиваются и дерутся почти как пехота, только что до этого шли конным строем.</p><p>По карте из официальной новозеландской истории 1922 года бой распадается на несколько очагов вдоль дюн. Не одна общая атака.</p><p>Турки несколько раз контратакуют. Доходит до штыков и гранат на нескольких метрах. Совсем не вчерашний Эль-Мугар.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/0*Qh392O7iQ8C7t2e6.jpg" /><figcaption>Anzac Mounted Division on the charge. Alexander Turnbull Library.</figcaption></figure><p>Новозеландцы теряют, по разным подсчётам, от 44 до 53 убитыми. Самые тяжёлые потери New Zealand Mounted Rifles Brigade за всю кампанию в Синае и Палестине.</p><p>И одна из немногих операций, которую они вели полностью сами, не как придаток британского или австралийского соединения. Отсюда особый статус этого боя в новозеландской памяти.</p><p>Похачевский описывает день из Ришона, в паре километров: «קרבנות אדם נופלים משני הצדדים… מוצאים להם איזה מקום מנוחה תחת צל של עץ» — «жертвы падают с обеих сторон… находят себе покой в тени какого-нибудь дерева».</p><p>По его цифрам — около 900 турок и около 90 англичан, включая новозеландцев. Турецкие потери, судя по всему, завышены слухами. Порядок величины — нет.</p><p>В самом поселении — полная, неестественная тишина. Канонаду слышно. Видно почти ничего. Из домов не выходят.</p><p>«ובמרחק איזה מאות מטרים שקט גמור במושבה ועולם כמנהגו נוהג, וכל אחד עובד עבודתו כבכל ימות השנה».<br>«А в нескольких сотнях метров оттуда — полная тишина в мошаве, жизнь идёт своим чередом, и каждый занимается своим делом, как в любой другой день года».</p><p>Похачевский формулирует состояние одной фразой и обрывает её: «מי אנחנו? טורקים־עותומנים, או…» — «кто мы теперь? Турецкие подданные, или…»</p><p>За три года депортаций и угроз Джемаля люди привыкли ждать худшего от любой смены власти. Даже вести об успехах британцев — не только радость. А вдруг турки вернутся и отыграются на тех, кто рано обрадовался. Этот страх держит ставни закрытыми, пока в соседних дюнах идёт бой.</p><p>Потом в поселение входит новозеландская конница. «כלם מכוסי אבק» — все покрыты пылью. Люди и лошади несколько дней без нормальной воды, после дюн и боя.</p><p>И вместе с этими всадниками в Ришон-ле-Цион впервые приходит весть о декларации Бальфура. Подписана 2 ноября. «והם הביאו לנו את הבשורה הבלפורית» — «и они принесли нам бальфурскую весть».</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*pfxP0eAr4uhILKnu.jpg" /><figcaption>Декларация Бальфура. Письмо лорду Ротшильду, 2 ноября 1917. British Library.</figcaption></figure><p>Документ, который определил судьбу сионистского движения на десятилетия, доходит до поселения не по телеграфу. На словах. Вместе с конницей. Жители выносят на улицы столы с вином.</p><p>Место боя сегодня — Гиват-Михаэль в Нес-Ционе. Жилые кварталы и памятный знак. В Ришон-ле-Ционе жители поставили свой памятник новозеландцам, павшим 14 ноября 1917-го.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/435/0*dXJdGW3g1q12l0zs.jpg" /><figcaption>Памятник, поставленный жителями Ришон-ле-Циона. На кресте — сержант J.A. Kay, Auckland Mounted Rifles, 14.11.1917.</figcaption></figure><p>Каждый год 14 ноября церемонии идут парно: в Израиле и в Новой Зеландии.</p><h3>Реховот. Тот же день</h3><p>Пока в дюнах идёт бой, в самом Реховоте — другой взгляд. Моше Смилянский, фермер и писатель. Очерк «הם באו!» — «Они пришли!».</p><p>Три года подряд он выходил и смотрел на юг: не покажется ли конница. «שלש שנים רצופות הייתי צופה בלילות כלפי הים…»</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*IMHbHYMhk7I1NBdq.jpg" /><figcaption>Синагога поселения Реховот, 1918. Снял австралийский солдат. Australian War Memorial, H02817.</figcaption></figure><p>В ночь на 14 ноября турецкий гарнизон уходит бесшумно, без боя. Точного момента никто из жителей не знает. Утро: турок уже нет, англичан ещё нет.</p><p>Первый явный знак — не солдаты. Крестьяне из соседней арабской деревни Зарнука. У ворот апельсиновой рощи спрашивают апельсины. С тех пор как турецкий лагерь побежал, скупщики перестали приезжать. Для кого покупать?</p><p>«למה לכם תפוחי הזהב — העוד צבא תורכי אצלכם?»</p><p>«לא, חוַג’ה, אינגליז».</p><p>Нет, хозяин. Англичане.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/0*yqsg8w9Z-V0bWyuK.jpg" /><figcaption>Яффо, 1917. Австралийские лёгкие кавалеристы поят лошадей.</figcaption></figure><p>Смилянский описывает вид: «העמק הרחב… מכוסה כולו גדודים מרובעים של פרשים» — широкая долина вся покрыта квадратными колоннами всадников. До Явне, насколько видит глаз. Эскадроны, повозки, автомобили.</p><p>Гарнизон из поселения уже ушёл. Но турецкая артиллерия, отходящая к Рамле, весь день бьёт по местности. Английская батарея западнее отвечает. Шрапнель рвётся над крышами.</p><p>Жители смотрят «в равновесии духа». То ли от усталости за три года, то ли отдельный обстрел уже не кажется самым страшным.</p><p>Счёт при этом кровавый. Смилянский пишет «אותות דם» — кровавые знаки. Турецкий снаряд убивает двух австралийцев у здания винодельни. Ещё двое жителей ранены у одного из домов. Ранена женщина из йеменской общины — редкое прямое упоминание гражданского в этих мемуарах.</p><p>Не расстрел отступающими. Не бой в поселении. Случайные потери от артиллерии уже, по сути, освобождённого Реховота.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4AXurZcHmWoZ9GdO.jpg" /><figcaption>Историческое здание винокурни Реховота. PikiWiki Israel.</figcaption></figure><p>Вечером — импровизированный ужин. Полковник произносит тост, Смилянский приводит его на иврите: «עם האוסטרלים, העם הצעיר בלאומים, מאושר להלחם לשחרורו של העם העתיק ביותר בעולם» — «мы, австралийцы, молодой народ среди народов, счастливы сражаться за освобождение древнейшего народа в мире».</p><p>Отдельная история — Sid Scherason, австралийский пастух-доброволец. С детства знал Библию почти наизусть и хотел когда-нибудь помочь вернуть родину «народу без родины».</p><p>Смилянский ищет глазами еврейские лица среди офицеров и солдат — и почти не находит. Армия-освободительница почти целиком не еврейская. Для него это отдельный, неприятный штрих на фоне общей радости.</p><p>К сумеркам — ещё одна сцена. «ובין הצבא עוברת מרכבה של הצלב האדום, ובה שני מתים… ומאחורי המרכבה פרשים עם מעדרים לחצוב קברים» — между войсками повозка Красного Креста, в ней двое мёртвых, за повозкой всадники с мотыгами.</p><p>«שניהם אוסטרלים». Те самые двое от снаряда у винокурни. Смилянский называет их «שנהרגו על אדמת מושבתנו בעד שחרורה» — павшими на земле нашего поселения за его освобождение.</p><p>Пока конница ждёт приказа на Рамлу, товарищи сами роют могилы мотыгами на старом кладбище.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wfhZCWaglbpSBt4W.jpg" /><figcaption>Старое кладбище Реховота, с 1890 года. Главный вход.</figcaption></figure><p>Ночь освобождения. Покоя нет. «ובלילה נדדה שנתי… אין שלום בנפשי» — сон бежал, нет покоя в душе.</p><p>Ум говорит душе: что ты скорбишь? Взошло солнце избавления. Душа облеклась мраком. Три года голода, депортаций и страха не стираются за один день.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aaWiM0uPcSAzy7MM.jpg" /><figcaption>Поля у Реховота. 2021.</figcaption></figure><h3>Абу-Шуше, 15 ноября</h3><p>Третий бой — восточнее. Арабская деревня Абу-Шуше на холме библейского Гезера. Холм запирает долину Аялон: главный проход с равнины в Иудейские горы. Со времён Иисуса Навина и до сих пор.</p><p>Эль-Мугар — юго-запад от Реховота, километров шесть-семь. Аюн-Кара — север, примерно столько же. Гезер — восток, десять-одиннадцать. Чуть дальше, но всё ещё с холмов вокруг поселения.</p><p>Турецкий арьергард держит высоту, чтобы прикрыть отход и не пустить на Иерусалим. Атаковать снова той же 6-й конной бригаде. Двумя днями раньше они уже брали Эль-Мугар. Теперь не разгон по равнине, а подъём по каменистому склону под огнём.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-z5s4ozL_swhS9Zs.jpg" /><figcaption>Долина Аялон с Гезера. <a href="http://holylandphotos.org/">holylandphotos.org</a>, Carl Rasmussen.</figcaption></figure><p>Те же йомены Бакингемшира, Беркшира и Дорсета. Не свежие резервы. Недоспавшие люди, уставшие лошади.</p><p>Историки считают штурм Абу-Шуше даже более дерзким, чем Эль-Мугар. Там хотя бы была равнина: строй, скорость. Здесь конница теряет своё главное.</p><p>22-я конная бригада атакует с севера спешенной. Imperial Camel Corps — тоже пешком. Командир 6-й бригады генерал Годвин идёт конным строем с юго-запада. Сначала Berkshire Yeomanry и пулемётчики спешиваются, чтобы подавить турецкие пулемёты. Потом Buckinghamshire Yeomanry галопом, за ними Dorset.</p><p>Среди погибших — капитан Нил Примроуз, 1882–1917. Действующий депутат парламента от Уисбеча. Второй сын бывшего премьер-министра лорда Розбери. Мать — Ханна де Ротшильд. Двоюродный брат Эвелина де Ротшильда, того самого, что двумя днями раньше на равнине у Эль-Мугара. Тот эпизод, который у Похачевского слился в один бой «у Гедеры».</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/0*e345oJ6AKApK0Y2a.jpg" /><figcaption>Neil James Archibald Primrose, 1882–1917.</figcaption></figure><p>Смертельное ранение — когда позиция уже фактически взята. Гибнуть не в разгар, а на пороге. Похоронен на военном кладбище в Рамле. На плите: депутат парламента, кавалер Военного креста.</p><p>Холм, за который шли 15 ноября, — это ещё и Тель-Гезер. Город Иисуса Навина, потом крепость Соломона на подходах к Иерусалиму. Бронзовый век, Соломон и кавалерия 1917-го — один рельеф, военный ключ к горам на три тысячи лет.</p><p>Сегодня национальный парк с раскопками. Можно приехать и увидеть оба слоя сразу.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SW99uKAHAtxq272c.jpg" /><figcaption>Тель-Гезер сегодня.</figcaption></figure><h3>Четыре дня</h3><p>13–16 ноября. Три боя в радиусе нескольких километров: Эль-Мугар, Джанкшн-Стейшн, Аюн-Кара и параллельно освобождение Реховота, Абу-Шуше у Тель-Гезера.</p><p>Турецкий фронт разрезан. Обе армии отступают. Британцы занимают Рамлу, Лод, вскоре Яффо. Дорога на Иерусалим с запада открыта.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WGPMuQ0PWBJUwsjl.jpg" /><figcaption>C. G. Powles, «The New Zealanders in Sinai and Palestine». Ситуация на фронте 16.11.1917.</figcaption></figure><p>Именно эти три малоизвестных боя, стали непосредственной причиной падения Иерусалима через месяц.</p><p>11 декабря Алленби входит в Иерусалим через Яффские ворота. Пешком. С коня сходит у стен. Кайзер Вильгельм II в 1898-м въезжал верхом. Жест сознательный: уважение к святому городу трёх религий, в пику немецкому имперскому высокомерию.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/0*caW0z3FgXlyWMPup.jpg" /><figcaption>Алленби у стен Иерусалима, 11 декабря 1917. Library of Congress, American Colony Photo Dept.</figcaption></figure><p>То, что произошло на трёх холмах несколькими неделями раньше, сделало возможной эту куда более известную сцену.</p><h3>Генерал и олива</h3><p>16 ноября, через два дня после Абу-Шуше, войска входят в Реховот. Генерал сэр Гарри Шовель — командующий Пустынным конным корпусом, тот же, кто брал Беэр-Шеву и координировал все три боя, — ставит штаб в доме Элиэзера Слуцкина, одного из основателей поселения.</p><p>Ключи он получил ещё в Австралии, до всей кампании. Сам Слуцкин, эмигрировавший туда из Реховота, отдал их со словами: возьми ключи, и когда доберёшься до страны — живи там.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*PNFvIm8y4eY0ERLW.jpg" /><figcaption>Шовель со штабом Пустынного конного корпуса на ступенях дома Слуцкина. Фрэнк Хёрли, 1918. <a href="http://rehovotarchive.org.il/">rehovotarchive.org.il</a></figcaption></figure><p>Штаб простоит в этом доме почти пять месяцев. Дольше, чем где-либо ещё за всю палестинскую кампанию.</p><p>На праздник деревьев, Ту би-Шват, жители устраивают концерт в народном доме — Бейт-ха-Ам — и зовут офицеров штаба. Аарон Эйзенберг, один из основателей Реховота, цитирует «כי תבואו אל הארץ ונטעתם» — «и когда придёте в страну, и посадите…» — и приглашает «героя-завоевателя» выйти и посадить первое дерево праздника.</p><p>Не с мечом. С лопатой.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*hs2DPm5CCRQAWWu2.jpg" /><figcaption>Реховот, аэрофото баварской эскадрильи 304, 1919. Подписи: народный дом (Бейт-ха-Ам), дом Слуцкина. <a href="http://rehovotarchive.org.il/">rehovotarchive.org.il</a></figcaption></figure><p>На улице — зимний ливень. Пожилой генерал не отказывается. Выходит во двор, сгибается и сам сажает саженец оливы. Мотыгой засыпает лунку мокрой землёй.</p><p>Свидетель Амихуд Нахмани, ему тогда восемнадцать, вспоминает: Шовель насквозь мокрый, взволнован, пытается сказать что-то торжественное — и не находит слов, кроме тихого: «אמור נא להם, מה רב הכבוד אשר נחלתי פה הלילה, הכבוד הגדול שבחיי» — «скажи же им, какая великая честь была оказана мне сегодня ночью, величайшая честь моей жизни».</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/0*HuDan2BvFW6Ry8L1.jpg" /><figcaption>Генерал сэр Гарри Шовель.</figcaption></figure><p>Через год, весной 1919-го, генерал возвращается с женой, леди Сибил. Перед отплытием в Австралию хочет посмотреть, как выросло «его» дерево.</p><p>Паника. За год движение повозок, ослов и верблюдов перед зданием так усилилось, что деревце не выдержало и погибло. Старейшины решают: правду говорить нельзя. Ночью несколько парней выкапывают другое, уже годовалое оливковое дерево и сажают на то же место.</p><p>Генерал приезжает, видит «своё» дерево и радуется, как хорошо оно принялось. Эту ложь повторят ещё раз, двадцать пять лет спустя, во Вторую мировую: постаревший Шовель пришлёт в Реховот знакомого священника специально узнать о судьбе дерева.</p><p>В 2007-м, к девяностолетию Беэр-Шевы, приезжает внучка — Дорин Бинни. Фотографируется на тех же ступенях дома Слуцкина. Мэр дарит ей оливковый бонсай.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/0*0ngoPR5SQQN6pqhE.jpg" /><figcaption>Дорин Бинни на лестнице дома Слуцкина. Ами Шидловицки, 2007. <a href="http://rehovotarchive.org.il/">rehovotarchive.org.il</a></figcaption></figure><p>Дом стоит. Сейчас в нём администрация школы «Де-Шалит». Те же ступени.</p><h3>Рамле</h3><p>Британское военное кладбище в Рамле (CWGC) — крупнейшее захоронение Первой мировой в этой части страны. Около 3300 могил. В том числе те, кто погиб во всех трёх боях.</p><p>Здесь Нил Примроуз. Эвелин де Ротшильд — отдельно, по просьбе семьи, на еврейском кладбище Ришона.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AColmn-nG7wstN4w.jpg" /><figcaption>Ramleh War Cemetery. CWGC.</figcaption></figure><p>Три холма. Одна неделя. Похачевский смотрит из Ришона, Смилянский — из Реховота, новозеландцы и австралийцы пишут свои дневники.</p><h3>Источники</h3><p>Похачевский — из Ришона. Смилянский — из Реховота. Йомены — свои дневники. Новозеландцы — официальную историю. Про оливу — Рахели Рогель.</p><p>Йехиэль Михаэль Похачевский. <em>מהתם להכא</em> («Оттуда сюда»). Яд Бен-Цви, 2013. <a href="https://benyehuda.org/collections/16893">https://benyehuda.org/collections/16893</a></p><p>Моше Смилянский. <em>הם באו!</em> («Они пришли!»). Двир, 1947. <a href="https://benyehuda.org/read/24099">https://benyehuda.org/read/24099</a></p><p>Cyril Falls. <em>Military Operations Egypt and Palestine</em>. 1930.</p><p>C. G. Powles. <em>The New Zealanders in Sinai and Palestine</em>. 1922.</p><p>R. M. P. Preston. <em>The Desert Mounted Corps: An Account of the Cavalry Operations in Palestine and Syria 1917–1918</em>. Houghton Mifflin, 1921. <a href="https://www.gutenberg.org/ebooks/54964">https://www.gutenberg.org/ebooks/54964</a></p><p>Berkshire Yeomanry Museum. The Action at El Mughar. <a href="https://www.berkshireyeomanrymuseum.org/el_mughar/">https://www.berkshireyeomanrymuseum.org/el_mughar/</a></p><p>War diaries of 6th Mounted Brigade and the yeomanry regiments (WO 95/4506), National Archives, Kew. Сводка: Over Open Sights. <a href="https://over-open-sights.blogspot.com/2014/07/a-trip-to-national-archives.html">https://over-open-sights.blogspot.com/2014/07/a-trip-to-national-archives.html</a></p><p>Рахели Рогель. «תחיית עץ הזית של הגנרל שובל». Архив Реховота; также на сайте ассоциации наследия Первой мировой в Израиле. <a href="https://www.rehovotarchive.org.il/cgi-webaxy/item?2879">https://www.rehovotarchive.org.il/cgi-webaxy/item?2879</a> <a href="https://www.ww1-israel.org/%D7%AA%D7%97%D7%99%D7%99%D7%AA-%D7%A2%D7%A5-%D7%94%D7%96%D7%99%D7%AA-%D7%A9%D7%9C-%D7%94%D7%92%D7%A0%D7%A8%D7%9C-%D7%A9%D7%95%D7%91%D7%9C-%D7%98%D7%95-%D7%91%D7%A9%D7%91%D7%98-%D7%AA%D7%A8%D7%A2/">https://www.ww1-israel.org/%D7%AA%D7%97%D7%99%D7%99%D7%AA-%D7%A2%D7%A5-%D7%94%D7%96%D7%99%D7%AA-%D7%A9%D7%9C-%D7%94%D7%92%D7%A0%D7%A8%D7%9C-%D7%A9%D7%95%D7%91%D7%9C-%D7%98%D7%95-%D7%91%D7%A9%D7%91%D7%98-%D7%AA%D7%A8%D7%A2/</a></p><p>Подписи к фото — сразу под картинками. Архив Реховота, Library of Congress, Australian War Memorial, British Library, CWGC, <a href="http://nzhistory.govt.nz/">nzhistory.govt.nz.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=08475801eac3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How We Enabled Product Manager to Write Features: Vibe Coding in Production]]></title>
            <link>https://itnext.io/how-we-enabled-product-manager-to-write-features-vibe-coding-in-production-bc0115d7e5d9?source=rss-95faca73a77f------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc0115d7e5d9</guid>
            <category><![CDATA[vibe-coding]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[google-ai-studio]]></category>
            <dc:creator><![CDATA[Pavel Bernshtam]]></dc:creator>
            <pubDate>Wed, 28 Jan 2026 13:07:22 GMT</pubDate>
            <atom:updated>2026-01-28T18:52:12.995Z</atom:updated>
            <content:encoded><![CDATA[<p>At <a href="https://anymaint.com/"><strong>AnyMaint</strong></a>, we develop maintenance management software for industrial equipment. In our industry, customers often need highly specialized dashboards or data views. This led us to a bold experiment: “Vibe Coding” for production.</p><p>The vision for this workflow came from our CEO/Product Manager <a href="https://www.linkedin.com/in/vladimir-krasniansky-69b48420/"><strong>Vladimir Krasniansky</strong></a>, the technical architecture was built by <a href="https://www.linkedin.com/in/timofey-lebedev-851a8b119"><strong>Timofey Lebedev</strong></a>, and I acted as the bridge between product and engineering (and chronicler of this journey).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SZY0TPo6X6ZSOd_Gh2GWQg.jpeg" /></figure><h3>1. The Strategy: Isolation via the “New Tab”</h3><p>To avoid breaking our complex <strong>Angular</strong> monolith, we decided that every AI-generated feature must be a standalone “mini-frontend.” These apps open in a <strong>new browser tab</strong>, ensuring 100% isolation. We use <strong>Vite + React 19</strong> for these tools because of their near-instant build speed and ease of deployment as static sites on <strong>AWS S3</strong>.</p><h3>2. How the AI “Knows” the Backend: Type-Safe Blueprints</h3><p>We don’t expect the AI to guess our API. We provide it with a “Source of Truth”:</p><ul><li><strong>The Entity Registry:</strong> We feed the AI our interfaces/api/ directory. These are TypeScript definitions of every AnyMaint entity (Events, Tools, Parts).</li><li><strong>Precise Prompting:</strong> When a PM asks for a “table of tools,” the AI references tools.ts to know exactly which fields exist (e.g., id_num, status) and which endpoints to call.</li><li><strong>Read-Only Safety:</strong> Our API specifications for the AI include only <strong>Read-Only</strong> methods. This ensures the PM’s experiments can never accidentally modify or delete production data.</li></ul><h3>Template Project Structure</h3><p>The following directory structure is what makes the “Vibe Coding” template work:</p><pre>.<br>├── auth/                 # Dev-mode session and simulation UI<br>├── coreApi/              # Native platform connectivity &amp; fetch wrapper<br>├── interfaces/           # Corporate Type Registry (The &quot;Source of Truth&quot;)<br>│   ├── api/              # Entity specifications (Tools, Events, etc.)<br>│   ├── common/           # Pagination and HTTP types<br>│   └── constants/        # Shared enums (Status, Types)<br>├── src/                  # Plugin-specific Application Logic<br>│   ├── components/       # Branded UI (AG-Grid, Header, Logo)<br>│   ├── utils/            # Data hydration (Excel &amp; IndexedDB)<br>│   └── App.tsx           # Main controller and param parsing<br>├── index.css             # Corporate design tokens (CSS Variables)<br>└── <a href="http://vite.config.prod.ts/">vite.config.prod.ts</a>   # Multi-chunk production build config</pre><h3>3. Data Transfer &amp; Auth Handshake</h3><p>Since there is no direct communication between the main app and the new tab, we use a <strong>Shared Storage Handshake</strong>:</p><ul><li><strong>Authentication:</strong> The mini-app silently retrieves the _token and _company ID from <strong>localStorage</strong> (shared across our domain).</li><li><strong>Data Hydration:</strong> The main app passes keys via <strong>URL parameters</strong>. The mini-app then pulls the corresponding dataset from <strong>IndexedDB</strong>.</li><li><strong>The Excel Trick:</strong> During development in Google AI Studio, the PM can upload an <strong>Excel file</strong> into a built-in form. A utility parses it and populates IndexedDB with mock data, allowing the PM to “vibe” and iterate without a live API connection.</li></ul><h3>4. Visual Consistency</h3><p>To ensure these tools look native, the template includes:</p><ul><li><strong>Design Tokens:</strong> A global index.css with corporate CSS variables (palette, spacing, typography).</li><li><strong>Pre-styled Components:</strong> We use <strong>AG-Grid (Quartz theme)</strong> and <strong>Bootstrap 5.3</strong>, wrapped in custom React components to maintain consistent interaction patterns.</li></ul><h3>5. Sandbox vs. Production (Data Hydration)</h3><p>To allow the AI or a developer to build the plugin in isolation without access to the full platform’s runtime environment, we use a declarative schema approach. The file link-parameters.ts acts as the contract between the main application and the plugin. It defines exactly what inputs the plugin requires — ranging from simple strings to complex file uploads.</p><p>In the sandbox environment, PluginForm.tsx dynamically renders a configuration form based on this schema. This allows the Product Manager (PM) or developer to “mock” the data injection that the main app would usually perform.</p><p>Crucially, we solve the data transfer limit of URL parameters using IndexedDB. When a user uploads a heavy Excel file in the sandbox:</p><ol><li>The PluginForm intercepts the file.</li><li>It parses the file to JSON client-side.</li><li>It stores the JSON blob in IndexedDB.</li><li>It generates a unique key (e.g., excel:filename:size) and passes <em>only that key</em> to the application via the URL.</li><li>The application then hydrates itself by reading from IndexedDB, unaware of whether the data came from the real platform or the sandbox form.</li></ol><p><strong>Code Snippet: Schema Definition</strong></p><pre>export default {<br>  &quot;title&quot;: &quot;Plugin Parameters&quot;,<br>  &quot;fields&quot;: [<br>    {<br>      &quot;type&quot;: &quot;text&quot;,<br>      &quot;name&quot;: &quot;projectName&quot;,<br>      &quot;label&quot;: &quot;Project Name&quot;,<br>      &quot;defaultValue&quot;: &quot;Maintenance Overhaul&quot;,<br>      &quot;required&quot;: true<br>    },<br>    {<br>      &quot;type&quot;: &quot;file&quot;,<br>      &quot;name&quot;: &quot;maintenanceData&quot;,<br>      &quot;label&quot;: &quot;Maintenance Schedule (Excel)&quot;,<br>      &quot;accept&quot;: &quot;.xlsx,.xls&quot;<br>    }<br>  ]<br>}</pre><p><strong>Code Snippet: Emulation &amp; Hydration Logic</strong></p><pre>const handleChange = async (e: <a href="http://react.changeevent/">React.ChangeEvent</a> | HTMLSelectElement&gt;) =&gt; {<br>  const { name, value, type } = e.target as HTMLInputElement;<br>  <br>  // 1. Intercept file upload<br>  if (type === &#39;file&#39;) {<br>    const files = (e.target as HTMLInputElement).files;<br>    const file = files &amp;&amp; files[0] ? files[0] : null;<br>    setFormData(prev =&gt; ({ ...prev, [name]: file }));<br>    <br>    if (file) {<br>      // 2. Generate Reference Key<br>      const key = `excel:${file.name}:${file.size}:${file.lastModified}`;<br>      try {<br>        // 3. Parse &amp; Store in IndexedDB<br>        const json = await excelFileToJson(file);<br>        await idbSet(key, json);<br>        setExcelKey(key);<br>      } catch (err) {<br>        console.error(&#39;Failed to parse/store Excel file&#39;, err);<br>      }<br>    }<br>    return;<br>  }<br>  // ... handle other inputs<br>};<br><br>const handleSubmit = async (e: React.FormEvent&lt;HTMLFormElement&gt;) =&gt; {<br>  e.preventDefault();<br>  // 4. Construct URL parameters with the Reference Key, not the file itself<br>  const plainParams: { [key: string]: string | boolean } = {};<br>  Object.entries(formData).forEach(([k, v]) =&gt; {<br>    if (v instanceof File || v === null) return;<br>    plainParams[k] = v as (string | boolean);<br>  });<br>  if (excelKey) {<br>    plainParams[&#39;excelKey&#39;] = excelKey;<br>  }<br>  onLaunch(plainParams);<br>};</pre><h3>6. Authentication Simulation</h3><p>The AuthModule serves as a bridge between the isolated development environment and the authenticated platform. In a production context, the plugin loads inside the main application where the authentication token usually exists in the browser context.</p><p>However, in the sandbox (Vibe Coding environment), AuthModule detects if the user is unauthenticated. It presents a standalone LoginForm that hits the real API to acquire a JWT. Upon success, it writes the _token and _company ID to localStorage. This mimics the exact state the plugin would find itself in when launched from the main platform, ensuring byte-compatibility between the sandbox and production without changing a single line of the core application code (src/App.tsx).</p><p><strong>Code Snippet: Auth State Management</strong></p><pre>const handleLogin = async (loginData: { username: string, password: string, remember: boolean }) =&gt; {<br>  setIsLoggingIn(true);<br>  try {<br>    const response = await auth.login(loginData);<br><br>    if (response.token &amp;&amp; response.user?.company) {<br>      // Simulate Platform State by writing to localStorage<br>      localStorage.setItem(&#39;_token&#39;, response.token);<br>      localStorage.setItem(&#39;_company&#39;, response.user.company?._id);<br><br>      setIsLoggedIn(true);<br>      setIsLaunched(false);<br>    } else {<br>      throw new Error(&#39;Invalid response from login API.&#39;);<br>    }<br>  } catch (error) {<br>    setLoginError(&#39;Invalid username or password.&#39;);<br>  } finally {<br>    setIsLoggingIn(false);<br>  }<br>};<br><br>// Conditional Rendering Logic<br>if (!isLoggedIn) {<br>    return &lt;LoginForm onLogin={handleLogin} loading={isLoggingIn} error={loginError} /&gt;;<br>}</pre><h3>7. Entrypoint Discrepancy (AI Studio vs. Local/S3)</h3><p>We face a dichotomy in runtime environments: Google AI Studio runs the code directly in the browser using ES modules and CDNs (no build step), while our production environment (S3) requires a bundled, minified artifact.</p><p>To solve this, we maintain two entry files:</p><ol><li><strong>index.html</strong>: Uses importmap to resolve dependencies like react and @google/genai to CDN URLs. This works instantly in the AI Studio preview.</li><li><strong>index.local.html</strong>: Uses standard Vite imports suitable for bundling local node_modules.</li></ol><p>The magic happens in <a href="http://vite.config.prod.ts/">vite.config.prod.ts.</a> During the build process, we instruct Vite to use index.local.html as the source but rename the output asset to index.html. This creates a seamless transition: the file used for local bundling replaces the CDN-dependent file in the final S3 deployment.</p><p><strong>Code Snippet: AI Studio Entry (CDN)</strong></p><pre>&lt;script type=&quot;importmap&quot;&gt;<br>{<br>  &quot;imports&quot;: {<br>    &quot;react&quot;: &quot;<a href="https://esm.sh/react@%5E19.0.0">https://esm.sh/react@^19.0.0&quot;</a>,<br>    &quot;ag-grid-react&quot;: &quot;<a href="https://esm.sh/ag-grid-react@32.3.3">https://esm.sh/ag-grid-react@32.3.3&quot;</a>,<br>    &quot;@google/genai&quot;: &quot;<a href="https://esm.sh/@google/genai@%5E0.7.0">https://esm.sh/@google/genai@^0.7.0&quot;</a><br>  }<br>}<br>&lt;/script&gt;<br>&lt;div id=&quot;root&quot;&gt;&lt;/div&gt;</pre><p><strong>Code Snippet: Production Build Entry (Bundled)</strong></p><pre>&lt;script type=&quot;importmap&quot;&gt;<br>  {<br>    &quot;imports&quot;: {<br>      &quot;react&quot;: &quot;<a href="https://esm.sh/react@%5E19.0.0">https://esm.sh/react@^19.0.0&quot;</a>,<br>      &quot;ag-grid-community&quot;: &quot;<a href="https://esm.sh/ag-grid-community@32.3.3">https://esm.sh/ag-grid-community@32.3.3&quot;</a><br>    }<br>  }<br>&lt;/script&gt;<br>&lt;body&gt;<br>  &lt;div id=&quot;root&quot;&gt;&lt;/div&gt;<br>  &lt;!-- Points to the bundled entry --&gt;<br>  &lt;script type=&quot;module&quot; src=&quot;/index.prod.tsx&quot;&gt;&lt;/script&gt;<br>&lt;/body&gt;</pre><p><strong>Code Snippet: Build-Time Rename Logic (</strong><a href="http://vite.config.prod.ts/">vite.config.prod.ts</a>)</p><pre>export default defineConfig({<br>  build: {<br>    rollupOptions: {<br>      input: {<br>        // Use the local HTML for the build process<br>        index: path.resolve(__dirname, &quot;index.local.html&quot;),<br>      },<br>      plugins: [<br>        {<br>          name: &quot;rename-index-local-to-index&quot;,<br>          // Hook to rename the asset in the final bundle<br>          generateBundle(_options, bundle) {<br>            for (const fileName of Object.keys(bundle)) {<br>              if (fileName.endsWith(&quot;index.local.html&quot;)) {<br>                const asset = bundle[fileName] as any;<br>                delete bundle[fileName];<br>                // Output as standard index.html for S3<br>                bundle[&quot;index.html&quot;] = { ...asset, fileName: &quot;index.html&quot; } as any;<br>                break;<br>              }<br>            }<br>          },<br>        },<br>      ],<br>    },<br>  },<br>});</pre><h3>8. Template Scaffolding &amp; Metadata</h3><p>he architecture relies on a rigid directory structure to ensure that code generated by the LLM (Vibe Coding) integrates cleanly with the host system. The scaffold includes:</p><ul><li><strong>auth/</strong>: The simulation layer for login and form emulation.</li><li><strong>coreApi/</strong>: Standardized wrappers for fetch that handle header injection (Auth tokens, Company IDs) automatically.</li><li><strong>interfaces/</strong>: TypeScript definitions mirrored from the backend to ensure type safety.</li><li><strong>src/</strong>: The actual application logic where the “Vibe” creation happens.</li></ul><p>Additionally, metadata.json acts as the manifest for the plugin. It declares the plugin’s identity and requests specific permissions (like Geolocation) that the host application must grant at runtime.</p><p><strong>Code Snippet: Plugin Manifest</strong></p><pre>{<br>  &quot;description&quot;: &quot;A static login page UI based on a visual design.&quot;,<br>  &quot;requestFramePermissions&quot;: [<br>    &quot;geolocation&quot;<br>  ],<br>  &quot;name&quot;: &quot;Anymaint Plugin Template&quot;<br>}</pre><h3>9. Reality Check and Future Outlook</h3><p>To date, we have successfully deployed <strong>5 mini-apps</strong> using this workflow. However, it is not a “one-click” magic trick; a developer’s touch is still vital for the final mile:</p><ul><li><strong>Build Stability:</strong> Occasionally, a project works perfectly in the Google AI Studio preview but fails to compile locally. A programmer must verify and fix the code before creating a Pull Request.</li><li><strong>Path Correction:</strong> AI Studio often defaults to absolute paths (assuming deployment at the root /). Since we host these tools as subfolders on our <strong>S3 bucket</strong>, a developer must manually correct these to relative paths.</li><li><strong>Scalability Challenges:</strong> While managing 5 mini-apps is currently seamless, we realize that scaling to 50 or 100 will bring new challenges. Managing dependencies, updating shared libraries, and ensuring long-term consistency across dozens of isolated apps will require a more robust orchestration strategy.</li></ul><p><strong>The Verdict:</strong> The initial setup to “lay the tracks” for the first app takes significant effort. However, every subsequent feature is delivered significantly faster. This isn’t about replacing developers; it’s a symbiotic relationship where the AI handles the repetitive UI and data fetching, while the engineer ensures production-grade stability and security.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc0115d7e5d9" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/how-we-enabled-product-manager-to-write-features-vibe-coding-in-production-bc0115d7e5d9">How We Enabled Product Manager to Write Features: Vibe Coding in Production</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using S3 Vector for RAG]]></title>
            <link>https://itnext.io/migrating-from-aws-knowledge-base-to-s3-vector-search-for-tool-normalization-in-maintenance-9b53b5540705?source=rss-95faca73a77f------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b53b5540705</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[embedding]]></category>
            <category><![CDATA[aws-s3]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <dc:creator><![CDATA[Pavel Bernshtam]]></dc:creator>
            <pubDate>Mon, 10 Nov 2025 13:22:04 GMT</pubDate>
            <atom:updated>2025-11-11T11:30:02.133Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LWXG6oMio6Te3HVzA1Bldw.jpeg" /></figure><h3>Introduction</h3><p>Our company, <a href="https://anymaint.com/">AnyMaint </a>, develops maintenance management software for industrial equipment. One of our core challenges is tool normalization — the process of identifying when different tool names actually refer to the same physical asset (by “tool” we mean any industrial asset: machines, equipment, instruments, devices, etc.).</p><p>Why this matters? To use maintenance data from one tool (breakdown history, repair procedures, monthly maintenance schedules) for another tool, we need to know these two tools are actually the same model. Without normalization, knowledge cannot be transferred between similar assets.</p><h3>The Challenge of Tool Normalization</h3><p>Tool normalization is not simple task. The same equipment can be called differently in different companies (or even within same company):</p><ul><li>Different languages</li><li>Different manufacturer codes</li><li>Different categorization systems</li><li>Abbreviations vs full names</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b7f3744df43799eed8fa995e794a305c/href">https://medium.com/media/b7f3744df43799eed8fa995e794a305c/href</a></iframe><p>For more than year, we have been using RAG (Retrieval-Augmented Generation) system based on AWS Knowledge Base for this task. The workflow is:</p><ol><li>When new tool appears in system, we search for similar tools in our database</li><li>If similar tools found (with high enough similarity score), we take their normalized name</li><li>If no similar tools exist, we pass all available tool information to LLM along with list of most probable normalized names</li><li>LLM makes final decision about normalization</li></ol><p>You can read more about our LLM-based normalization approach in <a href="https://medium.com/@javaap/tools-name-normalization-as-a-key-to-collaborative-maintenance-23d615284fec">this article</a>.</p><h3>Why We Decided to Migrate from AWS Knowledge Base</h3><p>The system was working good, but AWS Knowledge Base uses AWS OpenSearch under the hood, which is fast but expensive. Our normalization process is asynchronous — we don’t need super-fast response times. Paying for AWS Knowledge Base infrastructure seemed like overkill for our use case.</p><p>Our database contains approximately <strong>20,000 tools</strong> with verified normalization (checked manually or automatically). The normalization tasks run in Lambda functions triggered by EventBridge events.</p><p>When AWS announced S3 Vector Search (still in beta at time of writing), we decided to try it. The potential cost savings were too attractive to ignore.</p><h3>New Architecture with S3 Vector Search</h3><h3>System Overview</h3><p>Here is how new system works:</p><ol><li><strong>Embedding Generation</strong>: When new tool appears, we create embedding using local LLM model</li><li><strong>Vector Search</strong>: Search in S3 Vector store containing pre-indexed embeddings of existing tools</li><li><strong>Similarity Matching</strong>: If distance is below threshold, use normalized name from matched tool</li><li><strong>LLM Fallback</strong>: If no good match found, fallback to Claude Sonnet 3.5 for final decision</li></ol><h3>Choosing Embedding Model</h3><p>We tried several embedding models and settled on <strong>Xenova/bge-m3</strong>:</p><ul><li>Multilingual support (critical for us)</li><li>Available in both Python and TypeScript</li><li>Good balance between quality and size</li><li>1024-dimensional embeddings</li><li>Can run in Lambda environment</li></ul><h3>Docker Image for Lambda</h3><p>One of biggest challenges was cold start performance. Loading heavy ML model in Lambda takes time. We solved this by:</p><ol><li>Creating Docker image that already contains downloaded Xenova/bge-m3 model</li><li>Model is downloaded during Docker build, not at runtime</li><li>Lambda loads pre-cached model from image filesystem</li></ol><pre># Use AWS Lambda Node.js 20 runtime as base image<br>FROM public.ecr.aws/lambda/nodejs:20<br># Set working directory<br>WORKDIR ${LAMBDA_TASK_ROOT}<br># Copy package.json and package-lock.json first for better caching<br>COPY package*.json ./<br># Install dependencies<br>RUN npm install<br><br># Copy the rest of your app&#39;s source code<br>COPY . .<br>RUN npm run build<br><br># Warm up the model by downloading it during build time<br># This reduces Lambda cold start time by pre-downloading the transformers model<br>RUN echo &quot;🔄 Starting model warmup...&quot; &amp;&amp; \<br>    node dist/src/scripts/warmup-model.js<br>    <br># Set environment variables for Lambda runtime<br>ENV NODE_ENV=production<br>ENV AWS_NODEJS_CONNECTION_REUSE_ENABLED=1<br># The CMD instruction should point to your Lambda function handler<br>CMD [&quot;src/lambda_functions/get-tools-chunk/index.handler&quot;]</pre><p>Script for model downloading to the image:</p><pre>/**<br> * Model warmup script to pre-download transformers model during Docker build<br> *<br> * This script is run during the Docker build process to download and cache<br> * the Xenova BGE-M3 model, reducing Lambda cold start times.<br> *<br> * The script creates a test embedding which triggers the model download<br> * and verifies that the ES module import fix works correctly.<br> */<br><br>import { Embeddings } from &#39;@/helpers/Embeddings&#39;;<br>async function warmupModel() {<br>    console.log(&#39;Warming up S3VectorStorage model in Docker build...&#39;);<br>    try {<br>        // Create instance<br>        const vectorStorage = new Embeddings({<br>            modelConfigKey: &#39;bge-m3&#39;,<br>        });<br>        // Test creating an embedding to trigger model download<br>        console.log(&#39;Creating test embedding to download model...&#39;);<br>        const embedding = await vectorStorage.createEmbedding(<br>            &#39;Warmup text for model download&#39;<br>        );<br>        console.log(&#39;Model downloaded and embedding created successfully&#39;);<br>        console.log(&#39;Embedding length:&#39;, embedding.length);<br>        console.log(&#39;First few values:&#39;, embedding.slice(0, 3));<br>        console.log(&#39;Model warmup completed successfully!&#39;);<br>    } catch (error) {<br>        const errorMessage =<br>            error instanceof Error ? error.message : String(error);<br>        console.error(&#39;Model warmup failed:&#39;, errorMessage);<br>        // Don&#39;t exit with error code in Docker build, just log the issue<br>        console.error(&#39;This may cause slower cold starts in Lambda&#39;);<br>    }<br>}<br>// Run the warmup<br>warmupModel()<br>    .then(() =&gt; {<br>        console.log(&#39;Model warmup process finished.&#39;);<br>        process.exit(0);<br>    })<br>    .catch(error =&gt; {<br>        const errorMessage =<br>            error instanceof Error ? error.message : String(error);<br>        console.error(&#39;Model warmup failed:&#39;, errorMessage);<br>        // Don&#39;t fail the Docker build, just warn<br>        process.exit(0);<br>    });</pre><p>Current Docker image size is <strong>778 MB</strong>. Lambda is configured with <strong>4 GB memory</strong>. With this setup:</p><ul><li>Model loading takes 5–6 seconds</li><li>First cold start sometimes fails due to timeout</li><li>Subsequent invocations are fast (model stays in memory)</li></ul><p>For our asynchronous workload, 5–6 seconds startup is acceptable. If this is too slow for your use case, you can always use managed embedding service from AWS Bedrock instead of local model.</p><h3>S3 Vector Search Integration</h3><p>Unlike AWS Knowledge Base which required one file per tool, S3 Vector Search works differently — you simply use API to store documents and their embeddings. The service handles indexing internally.</p><pre>class S3VectorStorage:<br>    def __init__(self,<br>                 bucket_name: str,<br>                 index_name: str,<br>                 region_name: str = &#39;us-east-1&#39;,<br>                 ):<br>        &quot;&quot;&quot;<br>        Initialize S3VectorStorage with configurable model support.<br>        Args:<br>            bucket_name: S3 bucket name for vector storage<br>            index_name: Optional override for index name (uses model config default if not provided)<br>            region_name: AWS region name<br>        &quot;&quot;&quot;<br>        self.region_name = region_name<br>        self.s3_vectors = boto3.client(&#39;s3vectors&#39;, region_name=region_name)<br>        self.bucket_name = bucket_name<br>        self.index_name = index_name<br>        <a href="http://logger.info/">logger.info</a>(f&quot;S3VectorStorage initialized with model: index: <a href="http://{self.index_name}/">{self.index_name}&quot;</a>)<br><br>    def store_document(self, document_id: str, embedding: List[float], content: str,<br>                       additional_attributes: Dict[str, Any] = None) -&gt; str:<br>        &quot;&quot;&quot;<br>        Store a document with its vector embedding and attributes.<br>        Args:<br>            document_id: Unique identifier for the document<br>            embedding: The document embedding to store<br>            content: The document content to embed and store<br>            additional_attributes: Additional metadata to store with the document        Returns:<br>            The document ID that was stored<br>        &quot;&quot;&quot;<br><br>        try:<br>            # Prepare metadata attributes<br>            attributes = {<br>                &#39;content&#39;: content<br>            }<br><br>            if additional_attributes:<br>                attributes.update(additional_attributes)<br><br>            # Store the vector document<br>            <a href="http://logger.info/">logger.info</a>(f&quot;Storing document: {document_id}&quot;)<br>            self.s3_vectors.put_vectors(<br>                vectorBucketName=self.bucket_name,<br>                indexName=self.index_name,<br>                vectors=[<br>                    {<br>                        &quot;key&quot;: document_id,<br>                        &quot;data&quot;: {&quot;float32&quot;: embedding},<br>                        &quot;metadata&quot;: attributes<br>                    }<br>                ]<br>            )<br>            return document_id<br><br>       except Exception as e:<br>            logger.error(f&quot;Failed to store document {document_id}: {e}&quot;)<br>            raise<br><br>    def store_documents(self, documents: List[Dict[str, Any]]) -&gt; List[str]:<br>        &quot;&quot;&quot;<br>        Store multiple documents with their vector embeddings and attributes.<br>        Args:<br>            documents: A list of dictionaries, where each dictionary contains:<br>                       &#39;document_id&#39;: Unique identifier for the document<br>                       &#39;embedding&#39;: The document embedding to store<br>                       &#39;content&#39;: The document content to embed and store<br>                       &#39;additional_attributes&#39;: Metadata to store with the document<br>        Returns:<br>            List of document IDs that were stored<br>        &quot;&quot;&quot;<br>        try:<br>            vectors_to_store = []<br>            stored_ids = []<br>            for doc in documents:<br>                document_id = doc[&#39;document_id&#39;]<br>                embedding = doc[&#39;embedding&#39;]<br>                content = doc[&#39;content&#39;]<br>                additional_attributes = doc.get(&#39;additional_attributes&#39;)<br>                # Prepare metadata attributes<br>                attributes = {<br>                    &#39;content&#39;: content<br>                }<br>                if additional_attributes:<br>                    attributes.update(additional_attributes)<br>                # Add to vectors list<br>                vectors_to_store.append({<br>                    &quot;key&quot;: document_id,<br>                    &quot;data&quot;: {&quot;float32&quot;: embedding},<br>                    &quot;metadata&quot;: attributes<br>                })<br>                stored_ids.append(document_id)<br>            # Store all vectors in a single batch<br>            <a href="http://logger.info/">logger.info</a>(f&quot;Storing {len(vectors_to_store)} documents&quot;)<br>            self.s3_vectors.put_vectors(<br>                vectorBucketName=self.bucket_name,<br>                indexName=self.index_name,<br>                vectors=vectors_to_store<br>            )<br>            return stored_ids<br>        except Exception as e:<br>            logger.error(f&quot;Failed to store documents: {e}&quot;)<br>            raise</pre><p>For similarity search, we use <strong>cosine distance</strong>. One important difference from AWS Knowledge Base:</p><ul><li>AWS Knowledge Base returns similarity <strong>score</strong> (higher is better)</li><li>S3 Vector returns <strong>distance</strong> (lower is better)</li></ul><p>In AWS Knowledge Base, we used threshold of score &gt;= 0.64 to determine good match. With S3 Vector distance metric, we are still experimenting to find optimal threshold.</p><p><strong>Search method from the class above:</strong></p><pre>def search_documents(self, query_embedding: List[float], query_filter: Dict[str, Any] = None,<br>                         max_results: int = 10) -&gt; List[Dict]:<br>        &quot;&quot;&quot;<br>        Search for similar documents based on query text.<br>         Args:<br>            query_embedding: The embedding of the query text<br>            query_filter: Optional dictionary of filters to apply (e.g., {&#39;company_id&#39;: &#39;customer-456&#39;, &#39;category&#39;: &#39;tech&#39;})<br>            max_results: Maximum number of results to return<br>        Returns:<br>            List of matching documents with similarity scores<br>        &quot;&quot;&quot;<br>        try:<br>            # Prepare search parameters<br>            search_params = {<br>                &#39;vectorBucketName&#39;: self.bucket_name,<br>                &#39;indexName&#39;: <a href="http://self.index_name/">self.index_name</a>,<br>                &#39;queryVector&#39;: {&#39;float32&#39;: query_embedding},<br>                &#39;topK&#39;: max_results,<br>                &#39;returnMetadata&#39;: True,<br>                &#39;returnDistance&#39;: True<br>            }<br>            if query_filter:<br>                # Create filter with $eq operator for each key-value pair<br>                filter_conditions = []<br>                for key, value in query_filter.items():<br>                    filter_conditions.append({key: {&#39;$eq&#39;: value}})<br>                # Use $and operator when there are multiple conditions<br>                if len(filter_conditions) == 1:<br>                    search_params[&#39;filter&#39;] = filter_conditions[0]<br>                else:<br>                    search_params[&#39;filter&#39;] = {&#39;$and&#39;: filter_conditions}<br>            print(search_params)<br>            # Perform the search<br>            response = self.s3_vectors.query_vectors(**search_params)<br>            results = []<br>            for match in response.get(&#39;vectors&#39;, []):<br>                result = {<br>                    &#39;key&#39;: match[&#39;key&#39;],<br>                    &#39;distance&#39;: match[&#39;distance&#39;],<br>                    &#39;metadata&#39;: match.get(&#39;metadata&#39;, {})<br>                }<br>                results.append(result)<br>            <a href="http://logger.info/">logger.info</a>(f&quot;Found {len(results)} matching documents&quot;)<br>            return results<br>        except Exception as e:<br>            logger.error(f&quot;Search failed: {e}&quot;)<br>            raise<br></pre><h3>Performance Comparison</h3><h3>Latency</h3><ul><li><strong>AWS Knowledge Base</strong>: ~1 seconds for vector search</li><li><strong>S3 Vector</strong>: ~7–8 seconds (including embedding generation + search)</li><li><strong>With LLM fallback</strong>: Additional time for Claude API call</li></ul><p>The higher latency with S3 Vector is mainly due to local embedding generation (5–6 seconds for model loading). If you use Bedrock embeddings instead, latency would be closer to Knowledge Base.</p><h3>Cost</h3><p>We haven’t moved to production yet, so cannot provide exact cost comparison. However, expected savings are significant:</p><ul><li>No OpenSearch cluster to maintain</li><li>S3 storage much cheaper than OpenSearch</li><li>Pay only for actual API calls, not for idle infrastructure</li></ul><h3>Lessons Learned</h3><ol><li><strong>Cold starts matter</strong>: Even 5–6 seconds can be problem if you have strict SLAs. Consider: Using provisioned concurrency, Switching to Bedrock embeddings, Pre-warming Lambdas</li><li><strong>Distance vs Score</strong>: Be careful when migrating between systems. Distance and similarity score are inverse metrics. Test your thresholds carefully.</li><li><strong>Model size trade-offs</strong>: Larger models give better accuracy but slower loading. Xenova/bge-m3 was good compromise for us.</li><li><strong>Monitoring is critical</strong>: With asynchronous processing, you need good observability to catch failures and performance issues.</li></ol><h3>Conclusion</h3><p>Migration from AWS Knowledge Base to S3 Vector Search with local model is promising for our use case. Main benefits:</p><ul><li>Significant cost reduction (expected)</li><li>More control over embedding model</li><li>Simpler infrastructure</li></ul><p>Trade-offs:</p><ul><li>Higher latency (acceptable for async workflows)</li><li>More complex Lambda deployment (Docker images)</li><li>Need to manage embedding model ourselves</li></ul><p>For teams with similar requirements — asynchronous processing, cost sensitivity, need for multilingual support — S3 Vector Search can be good alternative to AWS Knowledge Base.</p><p>We are currently running both systems in parallel before full migration to production. Will share more results and cost data in future updates.</p><h3>Next Steps</h3><p>If you are considering similar migration:</p><ol><li>Start with small test dataset</li><li>Measure accuracy before switching</li><li>Load test with your expected traffic</li><li>Monitor cold starts and adjust memory/timeout settings</li><li>Consider managed embeddings (Bedrock) if cold starts are problem</li></ol><p><em>Have you worked with AWS S3 Vector Search? What has been your experience? Share in comments!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b53b5540705" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/migrating-from-aws-knowledge-base-to-s3-vector-search-for-tool-normalization-in-maintenance-9b53b5540705">Using S3 Vector for RAG</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Budget Astrophotography]]></title>
            <link>https://medium.com/@javaap/budget-astrophotography-2dd30617b2c7?source=rss-95faca73a77f------2</link>
            <guid isPermaLink="false">https://medium.com/p/2dd30617b2c7</guid>
            <category><![CDATA[photography]]></category>
            <category><![CDATA[space]]></category>
            <category><![CDATA[astrophotography]]></category>
            <category><![CDATA[art]]></category>
            <category><![CDATA[astronomy]]></category>
            <dc:creator><![CDATA[Pavel Bernshtam]]></dc:creator>
            <pubDate>Fri, 31 Oct 2025 07:57:08 GMT</pubDate>
            <atom:updated>2025-10-31T07:57:08.003Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>In last 10–15 years astrophotography, thanks to progress in software and electronics, became from narrow, expensive and difficult hobby into something accessible and beautiful.</strong></p><p>If you spend 500–600 dollars you can shoot hundreds of deep sky objects, and if you spend 2–3 thousand (and much time) you can get pictures that 30 years ago were possible only for multimillion observatory telescopes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sOqrbua0yXKz1GuuJ1Jbbg.jpeg" /><figcaption>Orion nebula shoot from my city, under polluted skies using UHC filter</figcaption></figure><p>I will try to explain how it works, without going too deep in technical details.<br> All photos, except mobile ones, are mine. More photos you can see on my <a href="https://www.paveltravelphoto.com/">website</a>.</p><h3>Level One — only mobile phone</h3><p>Take your mobile, manual mode, focus to infinity, exposure 30 seconds, aperture as wide as possible, timer 10 seconds and put it on a stone so it looks at Milky Way.<br> Some phones have night mode or even astro mode.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*783LvxY_1Bi5MWFsAFjoCA.jpeg" /><figcaption>Shot by mobile phone, author Max Kiwa</figcaption></figure><p>Boom! You have your first astrophoto!</p><p>Of course, you must go to place where Milky Way is visible — far from city, without Moon or clouds, better in summer when brightest part of Milky Way is visible.</p><h3>Level Two — same but with camera</h3><p>Better use tripod, but can also put on stone. Lens should be wide.</p><p>What means “wide”? Not more than 24 mm focal length (in 35 mm equivalent).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*0Y1FR9to-ATxOxPrmGT4Ew.jpeg" /><figcaption>Milky Way wide angle</figcaption></figure><p>Here is one small trick — Earth is rotating.<br> During exposure, stars turn into small lines.<br> There is rule of 500: exposure = 500 divided by focal length (in mm), to keep stars round.</p><p>For example, with 20 mm lens you can safely make 25 sec exposure.</p><p>Try ISO 1600, then adjust up or down depending result (depends from lens aperture, sky light pollution etc).</p><p>You can also use Earth rotation to make art.<br> Take time-lapse, 100 or even 300 shots 30 seconds each, and merge them in Photoshop to make star trails.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NxQWAHju5SCDK0EqOva-hg.jpeg" /><figcaption>More than 600 shots × 30 sec merged to one image</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*1LFP8FC2s5QughpX8okC3Q.jpeg" /><figcaption>Star trails with ruins — beautiful. Shivta National Park</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*WQoeeitbI2RIE0p_x0Ms1A.jpeg" /><figcaption>Same trails but direction not to north (not to Polar star), but to east</figcaption></figure><p>Important that interval between shots equals exposure time (both about 30 sec).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*ejB-ewfILkoD7UBFRls5zA.jpeg" /><figcaption>Comet C/2023 A3 — one frame, no stacking, no tracking. You see stars are stretched — Earth rotates!<br> Also many digital noise — high ISO, no stacking.</figcaption></figure><p>I use some terms meaning you must know your gear — focal length, how to change ISO, how to make time-lapse.<br> Astrophotography is not point-and-shoot — you must be little bit technical.</p><h3>Next step — nebulas and galaxies with more zoom</h3><p>Take lens 50 mm or 100 mm and point by eye to bright part of Milky Way.<br> Problem: only short exposures possible.<br> Not big issue — raise ISO until image becomes bright.<br> Shoot 20–30 frames by time-lapse before object leaves frame because of Earth rotation.</p><p>Then combine them in special program, for example <strong>Deep Sky Stacker</strong>, which removes noise by averaging frames.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/1*Xb5JMG109jZqlwNe2mvS6A.jpeg" /><figcaption>Sony A7II, lens Jupiter-37, 135/3.5 (actually with tracking, but without would be same), series of 30 frames, ISO 25600, exposure 4–13 sec. Visible Lagoon, Trifid, cluster M25</figcaption></figure><p>Quite real to shoot Andromeda or bright nebulas like Lagoon without telescope or tracking mount.</p><h3>Want something more cool?</h3><p>Buy star tracker — device that rotates together with Earth.<br> For example <strong>iOptron SkyTracker Pro</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*HvuaC4gZV_MOrt0kgP2d4w.jpeg" /><figcaption>Old version of SkyTracker, new one is white and more nice</figcaption></figure><p>It mounts on tripod instead of head, camera head goes on it, and camera on top.<br> Tracker points to Polaris and rotates same as Earth.<br> So we can use long exposures without blur.</p><p>I also added laser pointer instead of flash for aiming.</p><p>If image not moves, you can take hundreds of frames (by time-lapse, not manually!) that Deep Sky Stacker or <strong>Siril</strong> will merge. Both are free and excellent programs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*149O-dgrw3XgwfhozjxqVw.jpeg" /><figcaption>Andromeda, Sony A7II, Canon FD 200/2.8 at 3.5, iOptron Skytracker, 50×30s, ISO 3200 + 4 flats, 10 darks, 4 bias, stacked in DeepSkyStacker, curves in Photoshop</figcaption></figure><p>For better result use <strong>dark</strong>, <strong>bias</strong>, and <strong>flat</strong> frames.</p><ul><li><strong>Bias:</strong> zero-exposure frame with lens cap, records read noise.</li><li><strong>Dark:</strong> same exposure and temperature as main shots but with lens cap, records hot pixels and thermal noise.</li><li><strong>Flat:</strong> evenly illuminated frame with same optics, removes vignetting and dust.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*z7X3C6WLONsbu8uDlwgO3w.jpeg" /><figcaption>Orion Nebula, Sony A7II + Minolta 70–200/2.8, iOptron SkyGuider, 100 × 30s ISO 6400, 30 × 30s ISO 3200</figcaption></figure><p>With such setup and dark sky (not from city!!) you can capture hundreds of deep sky objects — nebulas, galaxies, clusters — without big expensive telescope.</p><p>Later you can add telescope, which is basically just big lens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*ddRo2KxKB03_X6vyGXJNUA.jpeg" /><figcaption>Trifid Nebula, also with telescope Celestron SLT 102</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*edwTxqu6DCHNKkZiLNAf7A.jpeg" /><figcaption>Lagoon Nebula, refractor telescope Celestron SLT 102, 23 frames × 30 s ISO 6400</figcaption></figure><h3>Next level — guiding</h3><p>Small second telescope with camera looks at star and sends signal to computer.<br> Computer checks tracking accuracy and corrects mount motor.<br> Then you can make 2–3 minutes exposures, catch faint objects with low noise.</p><p>You can also replace camera by special astro-camera and get much better result.</p><h3>Few important notes</h3><p>I not wrote about Moon and planets — it is another topic.<br> They are bright, so sensitivity not important, but resolution and zoom yes.<br> For them people use <strong>video (lucky imaging)</strong>, later analyze each frame.</p><p>I also not wrote details about software — it makes real magic.<br> Ask ChatGPT if you want details.<br> Stacking of hundreds frames is main thing for quality.<br> Programs like <strong>Siril</strong> can:</p><ul><li>find what object you shot,</li><li>fix white balance to real star colors,</li><li>stretch histogram,</li><li>stack comet moving frames so comet and stars both sharp,<br> and more.</li></ul><p>I also not wrote how to plan — what and when to shoot.<br> Summer sky (Lagoon, Orion Nebula) richer by nebulas,<br> winter sky (Orion, Pleiades, Andromeda) — by galaxies and clusters.</p><h3>About telescopes</h3><p>Big topic.<br> Only say: do <strong>not</strong> buy telescope just for visual observing.<br> From city you will see only Moon and planets — will get bored.<br> From dark place you will see little grey cotton instead of color nebulas — disappointment.<br> Do not buy cheap “500× zoom” telescopes for kids — they shake, unstable, useless.<br> Main thing in telescope is stable mount and tripod.</p><h3>And one more — dark sky</h3><p>Dark sky is critical for success.<br> Light pollution filters (UHC etc) can help little in city but nothing replaces going out.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*smEumAGv1ritil8EGa0dlg.jpeg" /><figcaption>Comet C/2020 F3 NEOWISE</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*Pt-NNxoLz2yjLt6H5sWiiQ.jpeg" /><figcaption>Antares, cluster M4 and Rho Ophiuchi nebula complex, no telescope, Canon FD 200/2.8 at 5.6</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*yQyfqlJxVvhmNzejojExQg.jpeg" /><figcaption>Comet Lemmon, 90 × 4 s frames ISO 12800, Sony A6400 + Celestron 102 SLT</figcaption></figure><p>Good shooting!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2dd30617b2c7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Repeated Failures Report at AnyMaint: A Technical Deep Dive]]></title>
            <link>https://itnext.io/repeated-failures-report-at-anymaint-a-technical-deep-dive-5c9aed1604f5?source=rss-95faca73a77f------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c9aed1604f5</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machinery]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[cmms]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Pavel Bernshtam]]></dc:creator>
            <pubDate>Wed, 23 Jul 2025 11:52:26 GMT</pubDate>
            <atom:updated>2025-07-23T14:37:42.916Z</atom:updated>
            <content:encoded><![CDATA[<p>At <a href="https://anymaint.com/">AnyMaint</a> CMMS, we specialize in predictive maintenance and failure analysis for industrial machinery. One of our key innovations is the automated generation of repeated failures reports, which distill thousands of maintenance events into actionable insights. This article outlines our technical approach, focusing on event filtering, clustering, cluster description generation, and report creation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*tmSlpaU--YpFQtdNO6OfzQ.png" /><figcaption>Alexandr Samokhvalov | The Weavers (1929)</figcaption></figure><h3>1. Event Filtering During Data Retrieval</h3><p>The foundation of our pipeline is robust event filtering. Raw event logs often contain noise, irrelevant entries, or generic descriptions that dilute the value of clustering. We apply several filters:</p><ul><li><strong>Minimum description length:</strong> Events with problem or solution descriptions shorter than 5 characters are excluded.</li><li><strong>Keyword exclusion:</strong> We remove events containing terms like test, dummy, unknown, or irrelevant.</li><li><strong>Preventive maintenance exclusion:</strong> We exclude events related to preventive maintenance, focusing solely on failure events.</li></ul><p><em>Example of filtered event:</em></p><ul><li>Problem: Does not work</li><li>Solution: Fixed, Thank you</li></ul><p>This ensures that only meaningful, technical failures are passed into the clustering phase.</p><h3>2. Clustering: Embeddings and Parameters</h3><h3>Embeddings with Local LLM</h3><p>To represent each event, we generate sentence embeddings using a local LLM. We concatenate the problem description, solution description and normalized tool name into a single text string. This string is then embedded into a vector using the sentence-transformers library with the all-MiniLM-L6-v2 model.</p><p><strong>Why local?</strong><br> Using a local model gives us:</p><ul><li><strong>Reduced cost:</strong> No per-call API charges.</li><li><strong>Lower latency:</strong> Embeddings are generated in milliseconds on local hardware.</li><li><strong>Data security:</strong> No sensitive event data leaves the client infrastructure.</li></ul><p>This approach ensures fast, secure, and affordable large-scale processing.</p><h3>Clustering Algorithm and Tuning</h3><p>We use DBSCAN, a density-based clustering algorithm that handles noise well and detects clusters of varying shape and size.</p><p>Our default parameters:</p><ul><li><strong>eps:</strong> 1.2 — Distance threshold for forming a cluster.</li><li><strong>min_samples:</strong> 4 — Minimum number of events per cluster.</li></ul><p>These parameters are tuned based on data density and granularity requirements. Each client may require different settings, as description styles vary across organizations.</p><h3>3. Cluster Description Generation</h3><p>After clustering, we summarize each cluster using AWS Bedrock (Anthropic Claude 3.5 Sonnet). All events in a cluster are sent as input to the LLM, which is instructed to summarize the cluster in a single sentence, highlighting common problems, tools, and technical patterns.</p><p><em>Example cluster description:</em></p><blockquote><em>“A recurring issue with the crusher where the blade isn’t properly positioned.”</em></blockquote><p>This step transforms dense event logs into clear, human-readable insights that engineers and managers can quickly act on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/911/1*6jEhFjqUoV2uyTiVYtI-zQ.png" /></figure><h3>4. Filtering During Report Creation</h3><p>Once descriptions are generated, we apply final filtering steps to maintain report quality:</p><ul><li><strong>Exclude noise clusters:</strong> DBSCAN marks some data as noise (i.e., not part of any cluster); these are removed.</li><li><strong>Remove outdated clusters:</strong> Clusters where the most recent failure occurred over two years ago are excluded.</li></ul><p>We then group failures by tool within each cluster, remove tools with very few events, and sort the clusters in descending order by number of failures.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*3-akffyn8dG8b88I88an7A.png" /></figure><h3>5. Statistical Insights</h3><p>Each report entry includes the cluster description followed by relevant tools. Although clustering is performed on individual failure events, the report is organized by tool for easier consumption.</p><p>For each tool we display:</p><ul><li><strong>Data period</strong> (range of dates across the cluster’s events)</li><li><strong>MTTR: Average repair time</strong> (from event start to resolution)</li><li><strong>Total downtime</strong> (if mentioned in the event logs)</li><li><strong>MTBF: Average time between failures</strong></li></ul><p>This gives a high-level but actionable summary of repeated issues and their operational impact.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*-EGXS9fXlXoF--NkyTso0Q.png" /></figure><h3>Conclusion</h3><p>By combining rigorous event filtering, safe data handling local LLM-based embeddings, tuned clustering parameters, and prompt-driven cluster summaries, <a href="https://anymaint.com/">AnyMaint </a>delivers high-quality, automated repeated failures reports for machinery and tools. This pipeline helps our clients identify systemic issues faster and reduce both downtime and maintenance costs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c9aed1604f5" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/repeated-failures-report-at-anymaint-a-technical-deep-dive-5c9aed1604f5">Repeated Failures Report at AnyMaint: A Technical Deep Dive</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How, Where, and When to Watch Meteor Showers in Israel]]></title>
            <link>https://medium.com/@javaap/how-where-and-when-to-watch-meteor-showers-in-israel-1a739f6fb41e?source=rss-95faca73a77f------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a739f6fb41e</guid>
            <category><![CDATA[photography]]></category>
            <category><![CDATA[tourism]]></category>
            <category><![CDATA[astronomy]]></category>
            <category><![CDATA[israel]]></category>
            <category><![CDATA[astrophotography]]></category>
            <dc:creator><![CDATA[Pavel Bernshtam]]></dc:creator>
            <pubDate>Mon, 21 Jul 2025 11:56:02 GMT</pubDate>
            <atom:updated>2025-07-21T11:56:02.451Z</atom:updated>
            <content:encoded><![CDATA[<p>Every year, around August, people become interested in meteor showers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*nCnX3z_ZjUq7pTedyy9T3Q.jpeg" /></figure><p>There are two relatively strong meteor showers each year: the Perseids in August and the Geminids in December.</p><p>You can see meteors on regular nights too, but it’s a matter of luck. However, you’ll definitely see a lot of satellites.</p><p>For both, you need to go to the desert. In my bestseller, <a href="https://medium.com/@javaap/when-where-and-how-to-watch-milky-way-in-israel-ad9edc3cb7de">“How, Where, and When to Watch the Milky Way in Israel”</a> , you can read about where to go for dark skies. In short — go South. Preferably south of Mitzpe Ramon, to dark areas by the Dead Sea, or the closest option is Shivta.</p><p><strong>How to observe:</strong></p><ol><li>Choose a dark place — away from city lights and without the Moon.</li><li>Check the Moon phase: <a href="https://www.timeanddate.com/moon/israel/jerusalem">https://www.timeanddate.com/moon/israel/jerusalem</a> It’s better to go a week before the peak and without the Moon, rather than at the peak with a bright Moon.</li><li>Monitor the weather (especially for the Geminids): <a href="https://www.windy.com/">https://www.windy.com</a></li><li>Don’t shine lights in your eyes — neither flashlights nor campfires. It’s better to eat, drink, lie down on a mat, turn off all lights, and just look at the sky. You can use a red flashlight; it’s less blinding.</li><li>Direction doesn’t matter — meteors can appear anywhere in the sky. No need to find the radiant point.</li></ol><p><strong>Most importantly — lower your expectations</strong>. The way meteors fall one after another like in movies happens, but very rarely. Much more often, you’ll see a couple of meteors per night, even if you lie and watch the sky the whole time instead of searching for hummus with a flashlight.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*I8xqAugfNJaIPnjl6tRHYg.jpeg" /></figure><p><strong>What to bring with you:</strong></p><ol><li>A mat or chair</li><li>Warm clothes (even in summer, it can be cool at night)</li><li>Water, food, a thermos with tea, wine, cognac</li><li>A red flashlight or a flashlight with a red filter</li><li>A power bank</li><li>A sleeping bag or blanket</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*eIEiNkx79FZ-NPjT0OMS9A.jpeg" /></figure><p><strong>Perseids (August)</strong></p><p>The peak is every year around August 11–13. Theoretically, it’s a strong shower — up to 100 meteors per hour are promised. In practice, even in the desert, without the Moon, you often only see a few meteors per hour. Details here (<a href="https://www.timeanddate.com/astronomy/meteor-shower/perseid.html">https://www.timeanddate.com/astronomy/meteor-shower/perseid.html</a>); just ignore the meaningless information about the peak radiant’s rise and set times.</p><p>This year, due to the Moon, I recommend observing in late July. Until, say, July 30, when the Moon sets around 11 PM (and for the next 1–2 days if you plan to stay up late), and after August 14, when the Moon rises at 10:30 PM, and even later on subsequent days.</p><p>Pros — the Milky Way is beautiful in August. Cons— crowds. On weekends near the Perseid peak, everyone rushes south. There will be terrible traffic jams. At the best night parking spots — lots of idiots with flashlights. What to do? Don’t go on Friday evening. Choose any other day of the week. If Friday is your only option — it’s better not to go at all. I’ve led tours myself — on Fridays, highways 6 and 40 are jammed. You’ll sit in traffic for 5 hours and see 2 meteors. Is it worth it?</p><p><strong>Geminids (December)</strong></p><p>The peak is every year around December 13–14. Details here (<a href="https://www.timeanddate.com/astronomy/meteor-shower/geminids.html">https://www.timeanddate.com/astronomy/meteor-shower/geminids.html</a>); just ignore the meaningless information about the peak radiant’s rise and set times.</p><p>A much more interesting shower. More meteors, and they are brighter. But:</p><ul><li>High chance of clouds — check the forecast.</li><li>It will be very cold in the desert — you’ll definitely freeze.</li></ul><p>However: there will be no crowds, and a chance to see many bright meteors.</p><p>In 2001, we saw an incredible number of Geminid meteors from a wasteland near Re’em Junction — an unforgettable sight. But, of course, every year is different.</p><p>It’s better to go to the desert.</p><p>And don’t forget about the Moon.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a739f6fb41e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hacker Screen Builder]]></title>
            <link>https://itnext.io/hacker-screen-builder-29ef8700ee14?source=rss-95faca73a77f------2</link>
            <guid isPermaLink="false">https://medium.com/p/29ef8700ee14</guid>
            <category><![CDATA[copilot-programming]]></category>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[funny]]></category>
            <dc:creator><![CDATA[Pavel Bernshtam]]></dc:creator>
            <pubDate>Mon, 30 Jun 2025 13:06:13 GMT</pubDate>
            <atom:updated>2025-06-30T13:06:13.849Z</atom:updated>
            <content:encoded><![CDATA[<p>The Hacker Screen Builder is a web-based tool designed to create cinematic hacker-style interfaces, as seen in films like The Matrix or Mr. Robot. This application allows users to construct dynamic, customizable screens by dragging and dropping various widgets, testing the result with a “Run” button, and saving the creation to generate a unique, shareable link. Optimized for desktop use, it also functions on mobile devices, offering flexibility for a range of creative applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UQolURvuzuRQ7bBn4_z2uw.png" /></figure><h3>Features and Functionality</h3><p><a href="https://hacker.iaf-bomber.com/">The Hacker Screen Builder</a> provides a collection of widgets to craft authentic-looking hacker interfaces. Users can arrange and configure these elements to achieve a desired aesthetic. Available widgets include:</p><ul><li>Satellite map with infinite zoom/enhance: Simulates zooming into locations from a satellite view.</li><li>3D spinning globe: Displays data points or global connections for a high-tech effect.</li><li>Rapid scrolling source code or command-line text: Mimics fast-paced coding or terminal output.</li><li>Progress bars: Animated bars labeled “Downloading” or “Decrypting” for dramatic effect.</li><li>Facial recognition match animation: Shows a face scan with a “MATCH FOUND” popup.</li><li>Grid of security camera feeds: Displays fake surveillance footage.</li><li>Heatmaps of activity/movement: Visualizes data patterns or activity hot spots.</li><li>Real-time signal/wire trace: Tracks signals across a map with animated lines.</li><li>Database query screens: Shows photos and personal data, resembling a police database.</li><li>Wireframe blueprints rotating in 3D: Presents rotating technical schematics.</li><li>Pulsing radar sweeps: Simulates radar tracking with sweeping animations.</li><li>Dynamic network graphs: Features nodes connecting and disconnecting dynamically.</li><li>DNA sequence or biometric scan overlays: Displays futuristic biometric visuals.</li><li>“Access granted/denied” popups: Adds dramatic authorization messages.</li><li>Red “ALERT” or flashing warnings: Creates urgency with bold warning visuals.</li></ul><p>Many widgets support customization, such as adding user-provided images or URLs. Once the screen is designed, users can test it with the “Run” feature and save it to receive a unique link for sharing or later access.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*anzY0g2GhmyMpXSCCV2agA.png" /></figure><h3>Development Process</h3><p>The creation of the Hacker Screen Builder leveraged modern AI tools to streamline development, particularly for the frontend, which was outside the core expertise of the project’s backend-focused development</p><p><strong>Step 1: Ideation with AI Assistance</strong></p><p>The initial concept involved compiling a list of widgets inspired by Hollywood hacker interfaces. Using ChatGPT, a comprehensive set of elements was brainstormed, including features like 3D globes, radar sweeps, and facial recognition animations. ChatGPT provided detailed descriptions of how each widget should function and appear, forming a solid foundation for the project.</p><p><strong>Step 2: Frontend Generation with Google AI Studio</strong></p><p>To build the user interface, Google AI Studio was used to generate the frontend code, including HTML, CSS, and basic JavaScript. The goal was a drag-and-drop interface with a “Run” button for testing and a “Save” button for generating unique links. Google AI Studio successfully produced a functional frontend, enabling widget placement and interaction. However, it lacked the capability to generate backend logic for saving configurations or managing links.</p><p><strong>Step 3: Backend Development and Frontend Refinement</strong></p><p>Upon downloading the source code from Google AI Studio, it was discovered that the frontend was built using the Vite framework, which provided a modern and efficient foundation for the application. To incorporate backend functionality, GitHub Copilot was utilized to develop server-side endpoints. Instructions were given to create endpoints for saving widget configurations, and Copilot generated Node.js code to handle the storage of screen layouts and the generation of unique, shareable links.</p><p>The frontend was further improved with GitHub Copilot’s assistance. Support was added for configuring certain widgets, such as allowing users to upload custom images or specify URLs. Additionally, functionality was implemented to load entire screens from saved configurations, enabling users to retrieve and edit their designs via unique links. These enhancements required iterative adjustments to the Vite-based frontend code, with Copilot providing JavaScript snippets that were tested and refined to ensure smooth operation across all widgets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DE2kvFzg1jIUZ1vzwiqkpA.png" /></figure><h3>Try It Out</h3><p>The Hacker Screen Builder is available at this <a href="https://hacker.iaf-bomber.com/">link</a>. You can see an example of saved screen layout <a href="https://hacker.iaf-bomber.com/screen/0790692b-565c-443c-8f4d-483c7a4d5780">here</a>. Users are invited to explore its features, create their own hacker screens, and share their designs. Feedback and suggestions for new widgets or improvements are welcome to help shape the tool’s future.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29ef8700ee14" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/hacker-screen-builder-29ef8700ee14">Hacker Screen Builder</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI Code Reviewer: Automate Your Code Reviews]]></title>
            <link>https://itnext.io/ai-code-reviewer-automate-your-code-reviews-137bfaa20e8b?source=rss-95faca73a77f------2</link>
            <guid isPermaLink="false">https://medium.com/p/137bfaa20e8b</guid>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[code-review]]></category>
            <category><![CDATA[llm-applications]]></category>
            <category><![CDATA[github]]></category>
            <dc:creator><![CDATA[Pavel Bernshtam]]></dc:creator>
            <pubDate>Mon, 31 Mar 2025 19:50:25 GMT</pubDate>
            <atom:updated>2025-04-01T08:37:48.655Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*anihmGAg6_pY4rv5OZgG0Q.jpeg" /></figure><p>Imagine a tool that scans your pull requests, spots potential issues, and even posts comments — all powered by AI. That’s what AI Code Reviewer, an open-source Python script from AnyMaint, delivers. It leverages large language models (LLMs) like ChatGPT and Gemini to analyze GitHub PRs, offering summaries, issue detection, or automated comments. Whether you’re polishing code solo or streamlining team reviews, this script brings AI smarts to your workflow — freely available under the BSD 3-Clause License at <a href="https://github.com/AnyMaint/code-reviewer">github.com/AnyMaint/code-reviewer</a>.</p><h3>How Do I Start Quickly?</h3><p>Ready to try it? Here’s what you need:</p><ul><li>Prerequisites:<br>- A GitHub repo with a PR (open or closed).<br>- A GitHub token: Generate one at <a href="https://github.com/settings/tokens">github.com/settings/tokens</a> with repo scope — takes 30 seconds.<br>- An API key: Get an OpenAI key (costs money) at <a href="https://platform.openai.com/api-keys">platform.openai.com/api-keys</a> or a free Google Gemini key at <a href="https://makersuite.google.com/">makersuite.google.com</a> — both quick sign-ups.<br>- Your repo is a pet project or you’ve got company permission to send code to LLMs.</li><li><strong>Install It:<br>- </strong>Clone the repo: git clone <a href="https://github.com/AnyMaint/code-reviewer.git">https://github.com/AnyMaint/code-reviewer.git</a> &amp;&amp; cd code-reviewer.<br>- Set up Python 3.10+: pip install -r requirements.txt.</li><li>Run It:<br>- Set env vars: export GITHUB_TOKEN=”your-token” &amp;&amp; export OPENAI_API_KEY=”your-key”.<br>-General mode: python review.py YourUser/repo 1 — mode general — llm chatgpt<br>- Output: “General PR Review: This PR adds a new feature to handle X, looks solid but could use Y.”<br>- Issues mode: python review.py YourUser/repo 1 — mode issues — llm chatgpt<br>-Output: “Code Issues: Line 10 might overflow; consider bounds checking.”</li></ul><h3>Now let’s dive deeper</h3><h3>A Quick Word on AnyMaint</h3><p><a href="https://anymaint.com/">AnyMaint</a> is behind this tool — a startup crafting a web-based Computerized Maintenance Management System (CMMS) that blends machine learning with modular design. Focused on industries like pharmaceuticals and medical devices, AnyMaint simplifies equipment monitoring, calibration scheduling, and workflow optimization for production floors — making maintenance smarter and data-driven.</p><h3>Why Run It Standalone?</h3><p>While AI Code Reviewer can automate reviews via GitHub Actions, most users will likely prefer running it standalone. Why? First, developers often want to catch mistakes in their own code before colleagues see it in a PR — think of it as a pre-review sanity check. Second, automation might scare some due to false positives — AI isn’t perfect, and errant comments could clutter a PR or mislead reviewers. Running it manually lets you control what gets shared.</p><h3>Get It from GitHub</h3><p>The script lives at <a href="https://github.com/AnyMaint/code-reviewer">github.com/AnyMaint/code-reviewer</a>, licensed under BSD 3-Clause — free to use, modify, and share. Clone it, tweak it, or just try it out!</p><h3>Script Usage Examples</h3><p>Here’s how to wield AI Code Reviewer with its various switches, each serving a distinct purpose. Don’t forget to setup GITHUB_TOKEN and OPENAI_API_KEY (or GOOGLE_API_KEY) environment variables.</p><ol><li><strong>General Mode: Understand the PR</strong></li></ol><p>Use Case: Get a high-level summary of what PR #42 does, based on its title, description, and diffs. Perfect for quickly grasping intent without diving into code — ideal for getting general picture before code review.</p><pre>python review.py AnyMaint/repo 42 --mode general --llm chatgpt</pre><p>2. <strong>Issues Mode: Manual Review Control</strong></p><p>Use Case: Lists potential code issues (e.g., bugs, style flaws) without posting them. You review the output and decide which to fix or escalate to GitHub comments manually.</p><pre>python review.py AnyMaint/repo 42 --mode issues --llm gemini</pre><p>3. <strong>Comments Mode: Automate Feedback</strong></p><p>Use Case: Automatically posts AI-detected issues as inline PR comments on changed lines. Use this when you’re ready to let AI speak directly to your team — handy for fast-paced projects trusting the LLM’s judgment.</p><pre>python review.py AnyMaint/repo 42 --mode comments --llm chatgpt</pre><p>4. <strong>Full Context: Deeper Analysis</strong></p><p>Use Case: Sends entire file contents (not just diffs) to the LLM for richer context — better for complex PRs where diffs alone miss the big picture. This switch can work with any of previously listed modes. Downside? It costs more in ChatGPT tokens and risks off-topic comments.</p><pre>python review.py AnyMaint/repo 42 --mode general --full-context --llm chatgpt</pre><h3>Watch the Costs and Policies</h3><p>We don’t cap token usage, so big PRs or — full-context can rack up ChatGPT costs — keep an eye on your OpenAI bill! Also, using this on company code hinges on your firm’s LLM and IP policies. Exposing proprietary diffs to external APIs might need approval — check with your legal team.</p><h3>Going Automatic with GitHub Actions</h3><p>Want hands-off reviews? Here’s how to install AI Code Reviewer in your repo (e.g., AnyMaint/anymaint_backend) using GitHub Actions:</p><ol><li><strong>Create the Workflow:</strong></li></ol><p>Add this to .github/workflows/code-review.yml in your target repo:</p><pre>name: AI Code Review<br><br>on:<br>  pull_request:<br>    types: [opened, synchronize]<br><br>jobs:<br>  review:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - name: Checkout Repository<br>        uses: actions/checkout@v4<br><br>      - name: Checkout Code Reviewer Repository<br>        uses: actions/checkout@v4<br>        with:<br>          repository: AnyMaint/code-reviewer<br>          path: code-reviewer<br><br>      - name: Set up Python<br>        uses: actions/setup-python@v5<br>        with:<br>          python-version: &#39;3.10&#39;<br><br>      - name: Install Dependencies<br>        run: |<br>          python -m pip install --upgrade pip<br>          pip install -r code-reviewer/requirements.txt<br><br>      - name: Run AI Code Review<br>        env:<br>          GITHUB_TOKEN: ${{ secrets.TOKEN }}<br>          OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}<br>        run: |<br>          cd code-reviewer<br>          python review.py ${{ github.repository }} ${{ github.event.pull_request.number }} --mode comments --llm chatgpt</pre><p>2.<strong> Set Secrets:</strong></p><p>In your repo’s Settings &gt; Secrets and variables &gt; Actions &gt; Secrets, add:</p><pre>TOKEN: A GitHub Personal Access Token with repo read and write scope.<br>OPENAI_API_KEY: Your OpenAI API key.</pre><p>3. <strong>Run It</strong></p><p>Open a PR — ChatGPT will comment on changes automatically.</p><h3>Choose Your Source</h3><ul><li>Live Updates: Use AnyMaint/code-reviewer directly in the YAML to always get the latest version.</li><li>Static Copy: Worried about unverified updates? Copy the repo locally:<br>- Clone it: git clone <a href="https://github.com/AnyMaint/code-reviewer.git.">https://github.com/AnyMaint/code-reviewer.git.</a><br>- Move files (e.g., review.py, chatgpt_llm.py, gemini_llm.py, requirements.txt) to your repo’s root or a subfolder (e.g., tools/).<br>- Update the YAML:</li></ul><pre># Remove the second checkout step<br>- name: Checkout Repository<br>  uses: actions/checkout@v4<br><br>- name: Set up Python<br>  uses: actions/setup-python@v5<br>  with:<br>    python-version: &#39;3.10&#39;<br><br>- name: Install Dependencies<br>  run: |<br>    python -m pip install --upgrade pip<br>    pip install -r requirements.txt  # Adjust path if in subfolder, e.g., tools/requirements.txt<br><br>- name: Run AI Code Review<br>  env:<br>    GITHUB_TOKEN: ${{ secrets.TOKEN }}<br>    OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}<br>  run: |<br>    python review.py ${{ github.repository }} ${{ github.event.pull_request.number }} --mode comments --llm chatgpt  # Adjust path if needed, e.g., tools/review.py</pre><h3>Join the Fun</h3><p>AI Code Reviewer is open-source — your ideas can shape it! Fork it, fix bugs, or add features at <a href="https://github.com/AnyMaint/code-reviewer">github.com/AnyMaint/code-reviewer</a>. Check <a href="https://github.com/AnyMaint/code-reviewer/blob/main/CONTRIBUTING.md">CONTRIBUTING.md</a> and jump in — let’s make code reviews smarter together!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=137bfaa20e8b" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/ai-code-reviewer-automate-your-code-reviews-137bfaa20e8b">AI Code Reviewer: Automate Your Code Reviews</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Keep Multiline Logs as Single Records in CloudWatch with Node.js]]></title>
            <link>https://itnext.io/how-to-keep-multiline-logs-as-single-records-in-cloudwatch-with-node-js-8a9285c83800?source=rss-95faca73a77f------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a9285c83800</guid>
            <category><![CDATA[cloudwatch]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[cloudwatch-logs]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Pavel Bernshtam]]></dc:creator>
            <pubDate>Fri, 28 Mar 2025 11:21:09 GMT</pubDate>
            <atom:updated>2025-03-28T13:03:54.521Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JS6Sk5czGry2WBzTTGIW_g.jpeg" /></figure><p><strong>Introduction: Making CloudWatch Logs Work with Multiline Console.log</strong></p><p>If you’re running a Node.js app on AWS ECS and sending logs to CloudWatch, you might notice a problem: multiline logs, like a pretty-printed JSON object from console.log, get split into separate records. For example, if you log { foo: “bar”, baz: “qux” } with newlines, CloudWatch treats each line as its own entry. This makes logs hard to read and debug. Our goal was to fix this so each console.log — even with multiple lines — shows up as one complete record in CloudWatch, while still keeping things readable. We also had to tackle HTTP request logs from Morgan, which added another twist. Here’s how we solved it step-by-step.</p><p><strong>Step 1: Adding a Prefix to Group Logs</strong></p><p>The trick to keeping multiline logs together is to give every log a consistent starting point that CloudWatch can recognize. We decided to add a timestamp prefix, like [03/27/2025 08:34:56], to every console.log and console.error in our Node.js app. This way, CloudWatch knows where one log starts and ends. To do this, we overrode the default console.log function in our app:</p><pre>const originalConsoleLog = console.log;<br>const originalConsoleError = console.error;<br>const originalConsoleInfo = console.info;<br><br>// Helper function to prepend a timestamp in local timezone<br>function withTimestamp(...args: any[]) {<br>  const timestamp = new Date().toLocaleString(&#39;en-US&#39;, {<br>    timeZone: &#39;Asia/Jerusalem&#39;, // Always print timestamp in israeli time<br>    year: &#39;numeric&#39;,<br>    month: &#39;2-digit&#39;,<br>    day: &#39;2-digit&#39;,<br>    hour: &#39;2-digit&#39;,<br>    minute: &#39;2-digit&#39;,<br>    second: &#39;2-digit&#39;,<br>    hour12: false, // 24-hour format<br>  });<br>  let message;<br>  try {<br>    message = args.map(arg =&gt; {<br>      if (typeof arg === &#39;object&#39; &amp;&amp; arg !== null) {<br>        // Pretty-print objects with newlines, handle circular refs<br>        try {<br>          return JSON.stringify(arg, null, 2);<br>        } catch (stringifyError) {<br>          return `[Unstringifiable Object] ${String(arg)}`;<br>        }<br>      }<br>      // Convert non-objects to string safely<br>      return String(arg);<br>    }).join(&#39; &#39;);<br>  } catch (e) {<br>    // Fallback if mapping fails<br>    message = `[Error Processing Args] ${args.join(&#39; &#39;)}`;<br>    originalConsoleError(`[Fallback Message] Error processing log arguments: ${e.message}`);<br>  }<br><br>  return `[${timestamp}] ${message}`;<br>}<br><br>// Override console.log<br>console.log = (...args) =&gt; {<br>    originalConsoleLog(withTimestamp(...args));<br>};<br><br>// Override console.error<br>console.error = (...args) =&gt; {<br>    originalConsoleError(withTimestamp(...args));<br>};<br><br>// Override <a href="http://console.info/">console.info</a><br>console.info = (...args) =&gt; {<br>    originalConsoleInfo(withTimestamp(...args));<br>};</pre><p>Now, a log like console.log(“Hello\nWorld”, { foo: “bar” }) becomes:</p><pre>[03/27/2025 08:34:56] Hello<br>World {<br>  &quot;foo&quot;: &quot;bar&quot;<br>}</pre><p><strong>Step 2: Fixing Morgan HTTP Request Logs</strong></p><p>This worked great for console.log, but we hit a snag with Morgan, a middleware we used to log HTTP requests in Express. Morgan was outputting lines like GET /api/users 200 without timestamps. Since these didn’t match our timestamp pattern, CloudWatch lumped them into the previous log, mixing things up. To fix this, we customized Morgan to add the same timestamp prefix:</p><pre>const express = require(&#39;express&#39;);<br>const morgan = require(&#39;morgan&#39;);<br>const app = express();<br><br>morgan.token(&#39;timestamp&#39;, () =&gt; {<br>    return new Date().toLocaleString(&#39;en-US&#39;, {<br>        timeZone: &#39;Asia/Jerusalem&#39;, // Your timezone<br>        year: &#39;numeric&#39;,<br>        month: &#39;2-digit&#39;,<br>        day: &#39;2-digit&#39;,<br>        hour: &#39;2-digit&#39;,<br>        minute: &#39;2-digit&#39;,<br>        second: &#39;2-digit&#39;,<br>        hour12: false<br>    });<br>});<br><br>app.use(morgan(&#39;[:timestamp] :method :url :status :res[content-length] - :response-time ms&#39;, {<br>    skip: (req) =&gt; req.url === &#39;/api/health&#39; // Skip health checks<br>}));</pre><p>Now, Morgan logs look like:</p><pre>[03/27/2025, 08:34:56] GET /api/users 200 5 - 2.345 ms</pre><p>Each request gets its own timestamp, so it’s a separate record in CloudWatch, not tangled with other logs.</p><p><strong>Step 3: Setting Up Terraform for CloudWatch</strong></p><p>To make this all work in AWS, we configured our ECS service in Terraform to use the awslogs driver with a special setting called awslogs-multiline-pattern. This tells CloudWatch to group all lines after a timestamp into one record until it sees the next timestamp. Here’s the key part of our Terraform code:</p><pre>module &quot;ecs_service&quot; {<br>  source = &quot;terraform-aws-modules/ecs/aws//modules/service&quot;<br><br>  name        = &quot;my-app&quot;<br>  cluster_arn = &quot;my-cluster-arn&quot;<br>  cpu         = 256<br>  memory      = 512<br><br>  container_definitions = {<br>    &quot;my-app-container&quot; = {<br>      cpu       = 256<br>      memory    = 512<br>      essential = true<br>      image     = &quot;my-app-image&quot;<br><br>      port_mappings = [<br>        {<br>          containerPort = 3000<br>          protocol      = &quot;tcp&quot;<br>        }<br>      ]<br><br>      log_configuration = {<br>        log_driver = &quot;awslogs&quot;<br>        options = {<br>          &quot;awslogs-group&quot;         = &quot;/ecs/my-app-logs&quot;<br>          &quot;awslogs-region&quot;        = &quot;us-east-1&quot;<br>          &quot;awslogs-stream-prefix&quot; = &quot;ecs&quot;<br>          &quot;awslogs-multiline-pattern&quot; = &quot;^\\[[0-1][0-9]/[0-3][0-9]/[0-9]{4} [0-2][0-9]:[0-5][0-9]:[0-5][0-9]\\]&quot;<br>        }<br>      }<br>    }<br>  }<br>}</pre><p>The awslogs-multiline-pattern regex (^\[[0–1][0–9]/[0–3][0–9]/[0–9]{4} [0–2][0–9]:[0–5][0–9]:[0–5][0–9]\]) matches our timestamp format, ensuring CloudWatch groups multiline logs correctly.</p><p><strong>Wrapping Up</strong></p><p>With these changes, our Node.js app now logs everything — HTTP requests from Morgan and custom console.log messages — as single, readable records in CloudWatch, even with multiple lines. It took a bit of tweaking: adding timestamps in the app, fixing Morgan, and setting up Terraform just right. A huge thank you to Grok, my AI helper, for guiding me through this step-by-step!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a9285c83800" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/how-to-keep-multiline-logs-as-single-records-in-cloudwatch-with-node-js-8a9285c83800">How to Keep Multiline Logs as Single Records in CloudWatch with Node.js</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Generic Reporting Service]]></title>
            <link>https://itnext.io/a-generic-reporting-service-51b0373c3437?source=rss-95faca73a77f------2</link>
            <guid isPermaLink="false">https://medium.com/p/51b0373c3437</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[reporting]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Pavel Bernshtam]]></dc:creator>
            <pubDate>Sun, 16 Mar 2025 11:49:43 GMT</pubDate>
            <atom:updated>2025-03-16T15:01:36.210Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-HrRY8vfii81IFwPZBT3lQ.jpeg" /></figure><p>While working at an OSU startup, my talented colleague Sergei Erenburg and I created a generic reporting service. This experience might be useful to many people. I must say from the start: we designed it together, but Sergei did most of the implementation. The credit belongs to him. I am writing this article only because I enjoy writing, and he does not.</p><p>OSU was an Israeli startup company that built a platform for freelancers and self-employed people. It allowed them to accept and manage payments through an app with no transaction fees, so users kept 100% of their sales. The app aimed to solve problems like hidden costs, delays, and errors in bank transfers — especially during the Coronavirus pandemic. In 2022, OSU was sold to PayPal.</p><p><strong>What Problem Did We Solve?</strong></p><p>At OSU, we had to produce many types of reports. Each used different tables, filters, and sorting rules. However, most of the code for these reports was very similar. This repetition wasted time and effort. To fix this, we developed a generic reporting service.</p><p><strong>Why Does It Matter?</strong></p><p>Reports are often a burden in companies. Writing new code for each report takes hours, and mistakes are common. Our service removed this problem. Instead of creating new code every time, we used one system for all reports. This saved us much time and reduced errors.</p><p><strong>How Does It Work?</strong></p><p>Here is how the service operates:</p><p>It runs as a separate microservice (though it could work in a single application too).</p><p>It reads its datasource configuration from a JSON file stored on S3. (See placeholder below for datasource config example.)</p><pre>{<br>  &quot;datasources&quot;: [<br>    {<br>      &quot;name&quot;: &quot;gateway&quot;,<br>      &quot;url&quot;: &quot;jdbc:postgresql://localhost:5432/transactions&quot;,<br>      &quot;driver&quot;: &quot;org.postgresql.Driver&quot;,<br>      &quot;maxPoolSize&quot;: 10,<br>      &quot;user&quot;: &quot;osu&quot;,<br>      &quot;password&quot;: &quot;superosu&quot;<br>    }]<br>}</pre><p>It connects to read replicas of databases to reduce pressure on the main databases. <em>(This is not required for the service to work, but it lowered the load on our main SQL database and ensured users did not notice delays when heavy reports were running.)</em></p><p>It takes a list of reports configs from another JSON file on S3.</p><p>It provides one endpoint. You send a JSON with the report name and input parameters, and it returns the results.</p><p>Each report’s JSON includes:</p><ul><li>A list of input parameters (such as filters).</li><li>Output fields (the data to show) and ability to sort on those fields.</li><li>An SQL query for a retrieving a page of results.</li><li>An SQL query for counting rows.</li></ul><p><strong>The Key: Configuration JSON</strong></p><p>The configuration JSON is the most important part. It lists input parameters, each with a type (e.g., string, integer), so the service can validate their input types. The SQL queries are stored in the JSON with placeholders for parameters.</p><pre>{<br>  &quot;reports&quot;: [<br>    {<br>      &quot;name&quot;: &quot;billing-usage&quot;,<br>      &quot;dataSource&quot;: &quot;billing&quot;,<br>      &quot;params&quot;: [<br>        {<br>          &quot;name&quot;: &quot;merchantId&quot;,<br>          &quot;nullable&quot;: false,<br>          &quot;type&quot;: &quot;INTEGER&quot;<br>        }<br>      ],<br>      &quot;query&quot;: {<br>        &quot;ASC&quot;: &quot;SELECT (CASE WHEN NOT bp.is_active THEN 0 ELSE (bp.number_of_reminders_per_month - mpu.number_of_reminders) END) AS \&quot;remindersLeft\&quot; FROM (SELECT mpu.is_active, <a href="http://mp.plan_id/">mp.plan_id</a>, sum_paid_this_period_in_cents, number_of_payment_requests, number_of_reminders, number_of_invoices, number_of_crm_users FROM merchant_plan_usage mpu JOIN merchant_plans mp ON mp.id = mpu.merchant_plan_id WHERE merchant_id = :merchantId ORDER BY mpu.time_created DESC LIMIT 1) mpu JOIN billing_plans bp ON bp.id = <a href="http://mpu.plan_id;/">mpu.plan_id;&quot;</a><br>      }<br>    }]<br>}</pre><p>All filters are optional, using the COALESCE function in SQL. For example:</p><blockquote>… AND name = COALESCE(:name_param, name) …</blockquote><p>If no name_param is provided, the filter is skipped (the condition becomes name = name, which is always true). You must write COALESCE in your SQL query — the service does not add it for you.</p><pre>{<br>  &quot;reports&quot;: [<br>    {<br>      &quot;name&quot;: &quot;fraud-merchant-to-payer-phone&quot;,<br>      &quot;dataSource&quot;: &quot;paymentrequests&quot;,<br>      &quot;params&quot;: [<br>        {<br>          &quot;name&quot;: &quot;payerPhone&quot;,<br>          &quot;nullable&quot;: false,<br>          &quot;type&quot;: &quot;STRING&quot;<br>        },<br>        {<br>          &quot;name&quot;: &quot;startDate&quot;,<br>          &quot;nullable&quot;: true,<br>          &quot;type&quot;: &quot;LOCAL_DATE_TIME&quot;<br>        },<br>        {<br>          &quot;name&quot;: &quot;endDate&quot;,<br>          &quot;nullable&quot;: true,<br>          &quot;type&quot;: &quot;LOCAL_DATE_TIME&quot;<br>        }<br>      ],<br>      &quot;query&quot;: {<br>        &quot;ASC&quot;: &quot;SELECT merchant_id as merchantId, count(*) as count from payment_requests pr where pr.payer_phone_number = :payerPhone and pr.time_created BETWEEN COALESCE(TO_TIMESTAMP(:startDate, &#39;yyyy-MM-dd HH24:mi:ss&#39;),pr.time_created) AND COALESCE(TO_TIMESTAMP(:endDate, &#39;yyyy-MM-dd HH24:mi:ss&#39;),pr.time_created) and pr.status &lt;&gt; &#39;DELETED&#39;  group by merchant_id&quot;<br>      }<br>    }]<br>}</pre><p>For MongoDB, a similar idea works:</p><blockquote>name: { $eq: nameParam || ‘$name’ }</blockquote><p><strong>Sorting in Reports</strong></p><p>We enabled sorting by a single field. In the report configuration JSON, you list the output fields that can be sorted. In the SQL query, we used <strong>ORDER BY :sortField</strong>, where<strong> :sortField</strong> is an integer — the position number of a field in the output fields list. When a request includes a sorting field, we find its number in the list. The configuration also requires two separate items: one query for ascending order and one for descending order. You must provide both. (This could perhaps be improved in the future.) (See placeholders below for sorting fields and query examples.)</p><pre>{<br>  &quot;reports&quot;: [<br>    {<br>      &quot;name&quot;: &quot;accountants&quot;,<br>      &quot;dataSource&quot;: &quot;accountants&quot;,<br>      &quot;fields&quot;: [<br>        {<br>          &quot;name&quot;: &quot;timeCreated&quot;,<br>          &quot;orderName&quot;: &quot;DATE&quot;<br>        }<br>      ],<br>      &quot;params&quot;: [<br>        {<br>          &quot;name&quot;: &quot;startDate&quot;,<br>          &quot;nullable&quot;: false,<br>          &quot;type&quot;: &quot;LOCAL_DATE&quot;<br>        },<br>        {<br>          &quot;name&quot;: &quot;endDate&quot;,<br>          &quot;nullable&quot;: false,<br>          &quot;type&quot;: &quot;LOCAL_DATE&quot;<br>        },<br>        {<br>          &quot;name&quot;: &quot;pageNum&quot;,<br>          &quot;nullable&quot;: false,<br>          &quot;type&quot;: &quot;INTEGER&quot;,<br>          &quot;skipIfCountQuery&quot;: true,<br>          &quot;excludeFromQuery&quot;: true<br>        },<br>        {<br>          &quot;name&quot;: &quot;sortField&quot;,<br>          &quot;nullable&quot;: false,<br>          &quot;type&quot;: &quot;ENUM&quot;,<br>          &quot;validationClass&quot;: &quot;SortField&quot;,<br>          &quot;excludeFromQuery&quot;: true<br>        },<br>        {<br>          &quot;name&quot;: &quot;sortDirection&quot;,<br>          &quot;nullable&quot;: false,<br>          &quot;type&quot;: &quot;ENUM&quot;,<br>          &quot;validationClass&quot;: &quot;SortDirection&quot;,<br>          &quot;excludeFromQuery&quot;: true<br>        },<br>        {<br>          &quot;name&quot;: &quot;fullResult&quot;,<br>          &quot;nullable&quot;: true,<br>          &quot;type&quot;: &quot;BOOLEAN&quot;,<br>          &quot;excludeFromQuery&quot;: true<br>        }<br>      ],<br>      &quot;query&quot;: {<br>        &quot;ASC&quot;: &quot;SELECT a.time_created as \&quot;timeCreated\&quot;,  (select lh.time_created as \&quot;lastLoginTime\&quot; from  login_history lh where a.email = lh.email order by lh.time_created desc  limit 1), a.status, a.email as \&quot;accountantEmail\&quot;, a.name as \&quot;accountantName\&quot;, o.name as \&quot;organizationName\&quot; from  accountants a  join organizations o on o.id = <a href="http://a.org_id/">a.org_id</a>  WHERE  a.time_created BETWEEN TO_TIMESTAMP(:startDate, &#39;yyyy-MM-dd HH24:mi:ss&#39;) AND TO_TIMESTAMP(:endDate, &#39;yyyy-MM-dd HH24:mi:ss&#39;) ORDER BY :sortField ASC LIMIT :pageSize OFFSET CAST(:pageNum as integer) * :pageSize;&quot;,<br>        &quot;DESC&quot;: &quot;SELECT a.time_created as \&quot;timeCreated\&quot;,  (select lh.time_created as \&quot;lastLoginTime\&quot; from  login_history lh where a.email = lh.email order by lh.time_created desc limit 1), a.status, a.email as \&quot;accountantEmail\&quot;, a.name as \&quot;accountantName\&quot;, o.name as \&quot;organizationName\&quot; from  accountants a  join organizations o on o.id = <a href="http://a.org_id/">a.org_id</a>  WHERE  a.time_created BETWEEN TO_TIMESTAMP(:startDate, &#39;yyyy-MM-dd HH24:mi:ss&#39;) AND TO_TIMESTAMP(:endDate, &#39;yyyy-MM-dd HH24:mi:ss&#39;) ORDER BY :sortField DESC LIMIT :pageSize OFFSET CAST(:pageNum as integer) * :pageSize;&quot;,<br>        &quot;COUNT&quot;: &quot;SELECT COUNT(id) FROM accountants WHERE time_created BETWEEN TO_TIMESTAMP(:startDate, &#39;yyyy-MM-dd HH24:mi:ss&#39;) AND TO_TIMESTAMP(:endDate, &#39;yyyy-MM-dd HH24:mi:ss&#39;)&quot;,<br>        &quot;ASC_FULL&quot;: &quot;SELECT a.time_created as \&quot;timeCreated\&quot;,  (select lh.time_created as \&quot;lastLoginTime\&quot; from  login_history lh where a.email = lh.email order by lh.time_created desc limit 1), a.status, a.email as \&quot;accountantEmail\&quot;, a.name as \&quot;accountantName\&quot;, o.name as \&quot;organizationName\&quot; from  accountants a  join organizations o on o.id = <a href="http://a.org_id/">a.org_id</a>  WHERE  a.time_created BETWEEN TO_TIMESTAMP(:startDate, &#39;yyyy-MM-dd HH24:mi:ss&#39;) AND TO_TIMESTAMP(:endDate, &#39;yyyy-MM-dd HH24:mi:ss&#39;) ORDER BY :sortField ASC OFFSET CAST(:pageNum as integer) * 0;&quot;,<br>        &quot;DESC_FULL&quot;: &quot;SELECT a.time_created as \&quot;timeCreated\&quot;,  (select lh.time_created as \&quot;lastLoginTime\&quot; from  login_history lh where a.email = lh.email order by lh.time_created desc limit 1), a.status, a.email as \&quot;accountantEmail\&quot;, a.name as \&quot;accountantName\&quot;, o.name as \&quot;organizationName\&quot; from  accountants a  join organizations o on o.id = <a href="http://a.org_id/">a.org_id</a>  WHERE a.time_created BETWEEN TO_TIMESTAMP(:startDate, &#39;yyyy-MM-dd HH24:mi:ss&#39;) AND TO_TIMESTAMP(:endDate, &#39;yyyy-MM-dd HH24:mi:ss&#39;)  ORDER BY :sortField DESC OFFSET CAST(:pageNum as integer) * 0;&quot;<br>      },<br>      &quot;pageSize&quot;: 500<br>    }]<br>}</pre><p><strong>Input validation</strong></p><p>For input validation was implemented a function that dynamically validates input based on an application’s JSON configuration. This approach provides flexibility and scalability while keeping the code clean and reusable. Instead of writing separate validation methods for each endpoint and their request body properties, multiple types can be handled in a single place. Adding new types is as simple as updating the DataType enum and implementing the corresponding validation function.</p><pre>fun validData(type: DataType, name: String, value: Any, validationClassName: String?): Boolean {<br> return when (type) {<br>   DataType.UUID -&gt; validUUID(name, value.toString())<br>   DataType.UUID_LIST -&gt; value.toString().split(&quot;,&quot;).all { validUUID(name, it) }<br>   DataType.TIMESTAMP -&gt; validTimeStamp(name, value.toString())<br>   DataType.ENUM -&gt; validEnum(name, value.toString(), validationClassName)<br>   DataType.ENUM_LIST -&gt; value.toString().split(&quot;,&quot;).all { validEnum(name, it, validationClassName) }<br>   <a href="http://datatype.integer/">DataType.INTEGER</a> -&gt; validInteger(name, value.toString())<br>   DataType.BOOLEAN -&gt; validBoolean(name, value.toString())<br>   DataType.STRING -&gt; true<br>   DataType.DOUBLE -&gt; validDouble(name, value.toString())<br> }<br>}</pre><p>In an example below a validTimeStamp validation function will be used when validating startDate parameter on exampleReport request</p><pre>{<br>  &quot;name&quot;: &quot;exampleReport&quot;,<br>  &quot;fields&quot;: [<br>    {<br>      &quot;name&quot;: &quot;exampleFieldDate&quot;<br>    }<br>  ],<br>  &quot;params&quot;: [<br>    {<br>      &quot;name&quot;: &quot;startDate&quot;,<br>      &quot;nullable&quot;: false,<br>      &quot;type&quot;: &quot;TIMESTAMP&quot;<br>    }<br>  ]<br>}</pre><p><strong>Pagination Implementation in the Service</strong></p><p>Besides sorting the service implements pagination using SQL queries with LIMIT and OFFSET to efficiently fetch a subset of records based on the requested page number and page size. This approach ensures that only the necessary data is retrieved, improving performance and reducing the load on the database.</p><pre>SELECT * FROM example <br>ORDER BY :sortField ASC <br>LIMIT :pageSize <br>OFFSET CAST(:pageNum AS INTEGER) * :pageSize;</pre><p><strong>No Need to Redeploy</strong></p><p>When you add or change a report, you do not need to rebuild or redeploy the service. We used CI/CD for the JSON files. When the CI/CD server detects changes in the reports’ Git repository, it:</p><ul><li>Checks the JSON for errors.</li><li>Uploads it to S3.</li><li>Restarts the service to load the new configuration.</li></ul><p>This way, configurations are stored in Git. You can use pull requests and reviews, moving changes from development to staging to production, just like with code — but without altering the service itself.</p><p><strong>General Idea, Not Specific Code</strong></p><p>We provide here the general idea of how it worked, with configuration examples, but without the service code. Everyone can write the service in a way that fits their needs. The concept is flexible and can be adapted to different systems or languages.</p><p><strong>SQL Queries Still Required</strong></p><p>Of course, this service does not write SQL queries for you. Writing SQL remains part of this approach and is the only heavy task you need to do. The service handles the rest — configuration, validation, and execution.</p><p><strong>Implementation Details</strong></p><p>When the service starts, it parses the report configuration JSON files and prepares them in internal data structures. When it receives an HTTP call with a report request, it:</p><ol><li>Validates the input parameters for the report, checking their types and values.</li><li>Parses the parameter values.</li><li>Substitutes these values into the SQL query text. In practice, we used prepared SQL statements (via the JDBC API) to prevent SQL injection, ensuring security.</li></ol><p><strong>Results</strong></p><p>The service worked well. We reduced the time to set up a new report from days to minutes. Heavy reports no longer slowed down the main database, thanks to the read replicas, and users felt no delays. The team made fewer mistakes, and our work became much smoother.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51b0373c3437" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/a-generic-reporting-service-51b0373c3437">A Generic Reporting Service</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>