id
int64
0
755k
file_name
stringlengths
3
109
file_path
stringlengths
13
185
content
stringlengths
31
9.38M
size
int64
31
9.38M
language
stringclasses
1 value
extension
stringclasses
11 values
total_lines
int64
1
340k
avg_line_length
float64
2.18
149k
max_line_length
int64
7
2.22M
alphanum_fraction
float64
0
1
repo_name
stringlengths
6
65
repo_stars
int64
100
47.3k
repo_forks
int64
0
12k
repo_open_issues
int64
0
3.4k
repo_license
stringclasses
9 values
repo_extraction_date
stringclasses
92 values
exact_duplicates_redpajama
bool
2 classes
near_duplicates_redpajama
bool
2 classes
exact_duplicates_githubcode
bool
2 classes
exact_duplicates_stackv2
bool
1 class
exact_duplicates_stackv1
bool
2 classes
near_duplicates_githubcode
bool
2 classes
near_duplicates_stackv1
bool
2 classes
near_duplicates_stackv2
bool
1 class
17,122
searchdsql.h
manticoresoftware_manticoresearch/src/searchdsql.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #ifndef _searchdsql_ #define _searchdsql_ #include "sphinx.h" /// refcounted vector template < typename T > class RefcountedVector_c : public CSphVector<T>, public ISphRefcountedMT {}; struct AttrValue_t { int64_t m_iValue; float m_fValue; bool m_bFloat; bool operator == ( const AttrValue_t & rhs ) const { return m_iValue==rhs.m_iValue && m_fValue==rhs.m_fValue && m_bFloat==rhs.m_bFloat; } bool operator < ( const AttrValue_t & rhs ) const { return m_iValue<rhs.m_iValue; } }; using AttrValues_p = CSphRefcountedPtr < RefcountedVector_c<AttrValue_t> >; /// parser view on a generic node /// CAUTION, nodes get copied in the parser all the time, must keep assignment slim struct SqlNode_t { int m_iStart = 0; ///< first byte relative to m_pBuf, inclusive int m_iEnd = 0; ///< last byte relative to m_pBuf, exclusive! thus length = end - start int m_iType = 0; ///< TOK_xxx type for insert values; SPHINXQL_TOK_xxx code for special idents float m_fValue = 0.0; AttrValues_p m_pValues { nullptr }; ///< filter values vector (FIXME? replace with numeric handles into parser state?) uint64_t m_uValue = 0; int m_iParsedOp = -1; bool m_bNegative = false; // this flag means that '-' was explicitly specified before the integer const SqlNode_t() = default; void SetValueInt ( int64_t iValue ); void SetValueInt ( uint64_t uValue, bool bNegative ); void SetValueFloat ( float fValue ); int64_t GetValueInt() const; uint64_t GetValueUint() const; float GetValueFloat() const { return m_fValue; } void CopyValueInt ( const SqlNode_t & tRhs ); }; /// types of string-list filters. enum class StrList_e { // string matching: assume attr is a whole solid string // attr MUST match any of variants provided, assuming collation applied STR_IN, // tags matching: assume attr is string of space-separated tags, no collation // any separate tag of attr MUST match any of variants provided STR_ANY, /// 'hello world' OP ('hello', 'foo') true, OP ('foo', 'fee' ) false // every separate tag of attr MUST match any of variants provided STR_ALL /// 'hello world' OP ('world', 'hello') true, OP ('a','world','hello') false }; /// magic codes passed via SqlNode_t::m_iStart to handle certain special tokens /// for instance, to fixup "count(*)" as "@count" easily enum { SPHINXQL_TOK_COUNT = -1, SPHINXQL_TOK_GROUPBY = -2, SPHINXQL_TOK_WEIGHT = -3, }; enum SqlStmt_e { STMT_PARSE_ERROR = 0, STMT_DUMMY, STMT_SELECT, STMT_INSERT, STMT_REPLACE, STMT_DELETE, STMT_SHOW_WARNINGS, STMT_SHOW_STATUS, STMT_SHOW_META, STMT_SET, STMT_BEGIN, STMT_COMMIT, STMT_ROLLBACK, STMT_CALL, // check.pl STMT_CALL_SNIPPETS STMT_CALL_KEYWORDS STMT_DESCRIBE, STMT_SHOW_TABLES, STMT_CREATE_TABLE, STMT_CREATE_TABLE_LIKE, STMT_DROP_TABLE, STMT_SHOW_CREATE_TABLE, STMT_UPDATE, STMT_CREATE_FUNCTION, STMT_DROP_FUNCTION, STMT_ATTACH_INDEX, STMT_FLUSH_RTINDEX, STMT_FLUSH_RAMCHUNK, STMT_SHOW_VARIABLES, STMT_TRUNCATE_RTINDEX, STMT_SELECT_COLUMNS, // was STMT_SELECT_SYSVAR STMT_SHOW_COLLATION, STMT_SHOW_CHARACTER_SET, STMT_OPTIMIZE_INDEX, STMT_SHOW_AGENT_STATUS, STMT_SHOW_INDEX_STATUS, STMT_SHOW_FEDERATED_INDEX_STATUS, STMT_SHOW_PROFILE, STMT_ALTER_ADD, STMT_ALTER_DROP, STMT_ALTER_MODIFY, STMT_SHOW_PLAN, // STMT_SELECT_DUAL, // deprecated to STMT_SELECT_COLUMNS as more general STMT_SHOW_DATABASES, STMT_CREATE_PLUGIN, STMT_DROP_PLUGIN, STMT_SHOW_PLUGINS, STMT_SHOW_THREADS, STMT_FACET, STMT_ALTER_RECONFIGURE, STMT_SHOW_INDEX_SETTINGS, STMT_FLUSH_INDEX, STMT_RELOAD_PLUGINS, STMT_RELOAD_INDEX, STMT_FLUSH_HOSTNAMES, STMT_FLUSH_LOGS, STMT_RELOAD_INDEXES, STMT_SYSFILTERS, STMT_DEBUG, STMT_ALTER_KLIST_TARGET, STMT_ALTER_INDEX_SETTINGS, STMT_JOIN_CLUSTER, STMT_CLUSTER_CREATE, STMT_CLUSTER_DELETE, STMT_CLUSTER_ALTER_ADD, STMT_CLUSTER_ALTER_DROP, STMT_CLUSTER_ALTER_UPDATE, STMT_EXPLAIN, STMT_IMPORT_TABLE, STMT_FREEZE, STMT_UNFREEZE, STMT_SHOW_SETTINGS, STMT_ALTER_REBUILD_SI, STMT_KILL, STMT_SHOW_LOCKS, STMT_TOTAL }; enum SqlSet_e { SET_LOCAL, SET_GLOBAL_UVAR, SET_GLOBAL_SVAR, SET_INDEX_UVAR, SET_CLUSTER_UVAR, SET_EXTRA }; /// insert value struct SqlInsert_t { // some internal tokens for bison grammar parser. // originaly we fetched values from parser itself, but it is more convenient to push own values instead. // in order to make it most seamless way, let's follow this manual: // To add new value XXX (if necessary) look into generated bissphinxql.h for TOK_XXX value, // then add the number BOTH into sphinxql.y (to fix this value forever), and into this enum (without TOK_ prefix), // as: for TOK_SYSVAR which is now 268 - change '%token TOK_SYSVAR' to '%token TOK_SYSVAR 268' in bison file, // then add SYSVAR = 268 here. enum Tokens_e { CONST_INT = 260, CONST_FLOAT = 261, CONST_MVA = 262, QUOTED_STRING = 263, CONST_STRINGS = 269, TABLE = 378, TOK_NULL = 473, // NULL is already reserved using TOK_NULL }; int m_iType = 0; float m_fVal = 0.0; CSphString m_sVal; // OPTIMIZE? use char* and point to node? AttrValues_p m_pVals; void SetValueInt ( uint64_t uValue, bool bNegative ); void SetValueInt ( int64_t iValue ); int64_t GetValueInt() const; uint64_t GetValueUint() const; bool IsNegativeInt() const { return m_bNegative; } void CopyValueInt ( const SqlNode_t & tRhs ); private: uint64_t m_uValue = 0; bool m_bNegative = false; }; namespace DebugCmd { struct DebugCommand_t; } /// parsing result /// one day, we will start subclassing this struct SqlStmt_t { SqlStmt_e m_eStmt = STMT_PARSE_ERROR; int m_iRowsAffected = 0; const char * m_sStmt = nullptr; // for error reporting // SELECT specific CSphQuery m_tQuery; std::unique_ptr<ISphTableFunc> m_pTableFunc; CSphString m_sTableFunc; StrVec_t m_dTableFuncArgs; // used by INSERT, DELETE, CALL, DESC, ATTACH, ALTER, RELOAD INDEX CSphString m_sIndex; CSphString m_sCluster; bool m_bClusterUpdateNodes = false; // INSERT (and CALL) specific CSphVector<SqlInsert_t> m_dInsertValues; // reused by CALL StrVec_t m_dInsertSchema; int m_iSchemaSz = 0; // SET specific CSphString m_sSetName; // reused by ATTACH SqlSet_e m_eSet = SET_LOCAL; int64_t m_iSetValue = 0; CSphString m_sSetValue; CSphVector<SphAttr_t> m_dSetValues; // CALL specific CSphString m_sCallProc; StrVec_t m_dCallOptNames; CSphVector<SqlInsert_t> m_dCallOptValues; StrVec_t m_dCallStrings; // UPDATE specific private: mutable AttrUpdateSharedPtr_t m_pUpdate { nullptr }; // made private for lazy initialization public: int m_iListStart = -1; // < the position of start and end of index's definition in original query. int m_iListEnd = -1; // CREATE/DROP FUNCTION, INSTALL PLUGIN specific CSphString m_sUdfName; // FIXME! move to arg1? CSphString m_sUdfLib; ESphAttr m_eUdfType = SPH_ATTR_NONE; // ALTER specific CSphString m_sAlterAttr; CSphString m_sAlterOption; ESphAttr m_eAlterColType = SPH_ATTR_NONE; AttrEngine_e m_eEngine = AttrEngine_e::DEFAULT; DWORD m_uFieldFlags = 0; DWORD m_uAttrFlags = 0; int m_iBits = -1; knn::IndexSettings_t m_tAlterKNN; // CREATE TABLE specific CreateTableSettings_t m_tCreateTable; // DROP TABLE specific bool m_bIfExists = false; // SHOW THREADS specific int m_iThreadsCols = -1; CSphString m_sThreadFormat; // generic parameter, different meanings in different statements // filter pattern in DESCRIBE, SHOW TABLES / META / VARIABLES // target index name in ATTACH // token filter options in INSERT // plugin type in INSTALL PLUGIN // path in RELOAD INDEX CSphString m_sStringParam; // generic integer parameter, used in SHOW SETTINGS, default value -1 // for opt_scope TOK_GLOBAL = 0, TOK_SESSION = 1. int m_iIntParam = -1; bool m_bJson = false; CSphString m_sEndpoint; CSphVector<CSphString> m_dStringSubkeys; CSphVector<int64_t> m_dIntSubkeys; std::unique_ptr<DebugCmd::DebugCommand_t> m_pDebugCmd; SqlStmt_t (); ~SqlStmt_t(); SqlStmt_t ( SqlStmt_t&& ) = default; SqlStmt_t& operator= ( SqlStmt_t&& ) = default; bool AddSchemaItem ( const char * psName ); // check if the number of fields which would be inserted is in accordance to the given schema bool CheckInsertIntegrity(); CSphAttrUpdate& AttrUpdate() const { if ( !m_pUpdate ) m_pUpdate = new CSphAttrUpdate; return *m_pUpdate; } AttrUpdateSharedPtr_t AttrUpdatePtr() const { if ( !m_pUpdate ) m_pUpdate = new CSphAttrUpdate; return m_pUpdate; } }; enum class Option_e : BYTE; class SqlParserTraits_c : ISphNoncopyable { bool m_bWrongParserSyntaxError = false; public: const char * m_pBuf; CSphString * m_pParseError; void * m_pScanner = nullptr; const char * m_pLastTokenStart = nullptr; CSphQuery * m_pQuery = nullptr; SqlStmt_t * m_pStmt = nullptr; CSphString m_sErrorHeader = "PER:"; void PushQuery(); CSphString & ToString ( CSphString & sRes, const SqlNode_t & tNode ) const; CSphString ToStringUnescape ( const SqlNode_t & tNode ) const; float ToFloat ( const SqlNode_t & tNode ) const { return (float) strtod ( m_pBuf+tNode.m_iStart, nullptr ); } void ProcessParsingError ( const char* szMessage ); bool IsWrongSyntaxError() const noexcept; bool AddOption ( const SqlNode_t & tIdent, const SqlNode_t & tValue ); bool AddOption ( const SqlNode_t & tIdent, const SqlNode_t & tValue, const SqlNode_t & sArg ); bool AddOption ( const SqlNode_t & tIdent, CSphVector<CSphNamedInt> & dNamed ); void DefaultOk ( std::initializer_list<const char*> sList = {} ); void SetIndex ( const SqlNode_t& tNode ) const; void SetIndex ( const CSphString& sIndex ) const; void Comment ( const SqlNode_t& tNode ) const; protected: CSphVector<SqlStmt_t> & m_dStmt; SqlParserTraits_c ( CSphVector<SqlStmt_t> & dStmt, const char* szQuery, CSphString* pError ); bool CheckInteger ( const CSphString& sOpt, const CSphString& sVal ) const; virtual bool CheckOption ( Option_e eOption ) const; }; bool sphParseSqlQuery ( Str_t sQuery, CSphVector<SqlStmt_t> & dStmt, CSphString & sError, ESphCollation eCollation ); bool PercolateParseFilters ( const char * sFilters, ESphCollation eCollation, const CSphSchema & tSchema, CSphVector<CSphFilterSettings> & dFilters, CSphVector<FilterTreeItem_t> & dFilterTree, CSphString & sError ); void SqlParser_SplitClusterIndex ( CSphString & sIndex, CSphString * pCluster ); void InitParserOption(); enum class AddOption_e { NOT_FOUND, ADDED, FAILED }; AddOption_e AddOption ( CSphQuery & tQuery, const CSphString & sOpt, const CSphString & sVal, const std::function<CSphString ()> & fnGetUnescaped, SqlStmt_e eStmt, CSphString & sError ); AddOption_e AddOption ( CSphQuery & tQuery, const CSphString & sOpt, const CSphString & sValue, int64_t iValue, SqlStmt_e eStmt, CSphString & sError ); AddOption_e AddOption ( CSphQuery & tQuery, const CSphString & sOpt, CSphVector<CSphNamedInt> & dNamed, SqlStmt_e eStmt, CSphString & sError ); AddOption_e AddOptionRanker ( CSphQuery & tQuery, const CSphString & sOpt, const CSphString & sVal, const std::function<CSphString ()> & fnGetUnescaped, SqlStmt_e eStmt, CSphString & sError ); enum class ParseResult_e { PARSE_OK, PARSE_ERROR, PARSE_SYNTAX_ERROR }; struct ParsedOption_t { int64_t m_iValue = 0; float m_fValue = 0.0; bool m_bValue = false; CSphString m_sValue; }; #endif // _searchdsql_
12,055
C++
.h
335
33.904478
215
0.731056
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,123
knnmisc.h
manticoresoftware_manticoresearch/src/knnmisc.h
// // Copyright (c) 2023-2024, Manticore Software LTD (https://manticoresearch.com) // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #pragma once #include "sphinxstd.h" #include "sphinxdefs.h" #include "columnarmisc.h" #include "indexsettings.h" #include "secondaryindex.h" const char * GetKnnDistAttrName(); ISphExpr * CreateExpr_KNNDist ( const CSphVector<float> & dAnchor, const CSphColumnInfo & tAttr ); void operator << ( JsonEscapedBuilder & tOut, const knn::IndexSettings_t & tSettings ); void AddKNNSettings ( StringBuilder_c & sRes, const CSphColumnInfo & tAttr ); knn::IndexSettings_t ReadKNNJson ( bson::Bson_c tRoot ); CSphString FormatKNNConfigStr ( const CSphVector<NamedKNNSettings_t> & dAttrs ); bool ParseKNNConfigStr ( const CSphString & sStr, CSphVector<NamedKNNSettings_t> & dParsed, CSphString & sError ); std::unique_ptr<knn::Builder_i> BuildCreateKNN ( const ISphSchema & tSchema, int64_t iNumElements, CSphVector<PlainOrColumnar_t> & dAttrs, CSphString & sError ); bool BuildStoreKNN ( RowID_t tRowID, const CSphRowitem * pRow, const BYTE * pPool, CSphVector<ScopedTypedIterator_t> & dIterators, const CSphVector<PlainOrColumnar_t> & dAttrs, knn::Builder_i & tBuilder ); std::pair<RowidIterator_i *, bool> CreateKNNIterator ( knn::KNN_i * pKNN, const CSphQuery & tQuery, const ISphSchema & tIndexSchema, const ISphSchema & tSorterSchema, CSphString & sError ); RowIteratorsWithEstimates_t CreateKNNIterators ( knn::KNN_i * pKNN, const CSphQuery & tQuery, const ISphSchema & tIndexSchema, const ISphSchema & tSorterSchema, bool & bError, CSphString & sError );
1,876
C++
.h
26
70.961538
211
0.755556
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,124
snippetpassage.h
manticoresoftware_manticoresearch/src/snippetpassage.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #ifndef _snippetpassage_ #define _snippetpassage_ #include "sphinxstd.h" struct StoredExcerptToken_t { int m_iLengthCP; BYTE m_iWordFlag; }; struct Passage_t { int m_iStart; ///< start token index int m_iTokens; ///< token count int m_iCodes; ///< codepoints count int m_iWords; ///< words count DWORD m_uQwords; ///< matching query words mask int m_iQwordsWeight; ///< passage weight factor int m_iQwordCount; ///< passage weight factor int m_iUniqQwords; ///< passage weight factor int m_iMaxLCS; ///< passage weight factor int m_iMinGap; ///< passage weight factor int m_iStartLimit; ///< start of match in passage int m_iEndLimit; ///< end of match in passage int m_iAroundBefore; ///< words before first matched words int m_iAroundAfter; ///< words after last matched words int m_iCodesBetweenKeywords; ///< codepoints between m_iStartLimit and m_iEndLimit int m_iWordsBetweenKeywords; ///< words between m_iStartLimit and m_iEndLimit int m_iField; ///< field id CSphVector<StoredExcerptToken_t> m_dBeforeTokens; ///< stored tokens before match CSphVector<StoredExcerptToken_t> m_dAfterTokens; ///< stored tokens after match void Reset(); void CopyData ( Passage_t & tPassage ); int GetWeight () const; }; struct SnippetQuerySettings_t; struct SnippetLimits_t; class SnippetsDocIndex_c; struct PassageContext_t { DWORD m_uPassagesQwords = 0; int m_dQwordWeights[32]; CSphVector<int> m_dTopPassageWeights; CSphVector<Passage_t> m_dPassages; PassageContext_t(); CSphVector<Passage_t> SelectBest ( const SnippetLimits_t & tLimits, const SnippetQuerySettings_t & tSettings, const SnippetsDocIndex_c & tContainer, DWORD uFoundWords ) const; }; #endif // _snippetpassage_
2,252
C++
.h
57
37.614035
176
0.739908
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,125
coro_waker.h
manticoresoftware_manticoresearch/src/coro_waker.h
// // Copyright (c) 2021-2024, Manticore Software LTD (https://manticoresearch.com) // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org // #pragma once #include "std/spinlock.h" #include <boost/intrusive/slist.hpp> namespace Threads { namespace Coro { class Worker_c; namespace detail { using waker_queue_hook_t = boost::intrusive::slist_member_hook<> ; } class Waker_c { Worker_c* m_pCtx {}; size_t m_iEpoch {}; friend class AtomicWaker_c; public: Waker_c() = default; Waker_c ( Worker_c* pCtx, const size_t iEpoch ) : m_pCtx { pCtx } , m_iEpoch { iEpoch } {} bool Wake ( bool bVip = false ) const noexcept; }; class AtomicWaker_c { std::atomic<Worker_c*> m_pCtx {nullptr}; size_t m_iEpoch {}; public: AtomicWaker_c() = default; void Assign ( Waker_c&& tWaker ) { m_iEpoch = tWaker.m_iEpoch; m_pCtx.store ( tWaker.m_pCtx, std::memory_order_relaxed ); } bool WakeOnce ( bool bVip = false ) noexcept; }; class WakerInQueue_c: public Waker_c { public: explicit WakerInQueue_c ( Waker_c&& w ) : Waker_c { w } {} bool is_linked() const noexcept { return m_tWakerQueueHook.is_linked(); } friend bool operator== ( Waker_c const& lhs, Waker_c const& rhs ) noexcept { return &lhs == &rhs; } public: detail::waker_queue_hook_t m_tWakerQueueHook {}; }; namespace detail { using WakerSlist_t = boost::intrusive::slist< WakerInQueue_c, boost::intrusive::member_hook< WakerInQueue_c, detail::waker_queue_hook_t, &WakerInQueue_c::m_tWakerQueueHook>, boost::intrusive::constant_time_size<false>, boost::intrusive::cache_last<true>>; } class WaitQueue_c { private: detail::WakerSlist_t m_Slist {}; public: void SuspendAndWait ( sph::Spinlock_lock& l, Worker_c* ) REQUIRES (l); bool SuspendAndWaitUntil ( sph::Spinlock_lock& l, Worker_c*, int64_t ) REQUIRES (l); bool SuspendAndWaitForMS ( sph::Spinlock_lock& l, Worker_c*, int64_t ) REQUIRES (l); void NotifyOne(); void NotifyAll(); bool Empty() const; }; } // namespace Coro } // namespace Threads
2,259
C++
.h
89
23.404494
85
0.718677
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,126
netreceive_api.h
manticoresoftware_manticoresearch/src/netreceive_api.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #pragma once #include "networking_daemon.h" // serve active (legacy) and passive sphinx proto void ApiServe ( std::unique_ptr<AsyncNetBuffer_c> pBuf );
631
C++
.h
15
40.866667
80
0.755302
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,127
searchdha.h
manticoresoftware_manticoresearch/src/searchdha.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // /// @file searchdha.h /// Declarations for the stuff specifically needed by searchd to work with remote agents /// and high availability funcs #ifndef _searchdha_ #define _searchdha_ #include <utility> #if _WIN32 bool LoadExFunctions (); #endif #include "sphinxutils.h" #include "searchdaemon.h" #include "timeout_queue.h" ///////////////////////////////////////////////////////////////////////////// // SOME SHARED GLOBAL VARIABLES ///////////////////////////////////////////////////////////////////////////// extern int64_t g_iPingIntervalUs; extern DWORD g_uHAPeriodKarmaS; // by default use the last 1 minute statistic to determine the best HA agent extern int g_iPersistentPoolSize; extern int g_iAgentConnectTimeoutMs; extern int g_iAgentQueryTimeoutMs; // global (default). May be override by index-scope values, if one specified extern bool g_bHostnameLookup; const int STATS_DASH_PERIODS = 15; ///< store the history for last periods ///////////////////////////////////////////////////////////////////////////// // MISC GLOBALS ///////////////////////////////////////////////////////////////////////////// /// known default sphinx ports /// (assigned by IANA, see http://www.iana.org/assignments/port-numbers for details) enum IanaPorts_e { IANA_PORT_SPHINXQL = 9306, IANA_PORT_SPHINXAPI = 9312 }; /// known status return codes enum SearchdStatus_e : WORD { SEARCHD_OK = 0, ///< general success, command-specific reply follows SEARCHD_ERROR = 1, ///< general failure, error message follows SEARCHD_RETRY = 2, ///< temporary failure, error message follows, client should retry later SEARCHD_WARNING = 3 ///< general success, warning message and command-specific reply follow }; /// remote agent state enum class Agent_e { HEALTHY, ///< agent is in normal state CONNECTING, ///< connecting to agent in progress, write handshake on socket ready RETRY, ///< should retry, but after scheduled timeout }; const char * Agent_e_Name ( Agent_e eState ); /// per-agent query stats (raw, filled atomically on-the-fly) enum AgentStats_e { eTimeoutsQuery = 0, ///< number of time-outed queries eTimeoutsConnect, ///< number of time-outed connections eConnectFailures, ///< failed to connect eNetworkErrors, ///< network error eWrongReplies, ///< incomplete reply eUnexpectedClose, ///< agent closed the connection eNetworkCritical, ///< agent answered, but with warnings eNetworkNonCritical, ///< successful queries, no errors eMaxAgentStat }; /// per-host query stats (calculated) enum HostStats_e { ehTotalMsecs=0, ///< number of microseconds in queries, total ehConnTries, ///< total number of connect tries ehAverageMsecs, ///< average connect time ehMaxMsecs, ///< maximal connect time ehMaxStat }; enum HAStrategies_e { HA_RANDOM, HA_ROUNDROBIN, HA_AVOIDDEAD, HA_AVOIDERRORS, HA_DEFAULT = HA_RANDOM }; // manages persistent connections to a host // serves a FIFO queue. // I.e. if we have 2 connections to a host, and one task rent the connection, // we will return 1-st socket. And the next rent request will definitely 2-nd socket // whenever 1-st socket already released or not. // (previous code used LIFO strategy) class PersistentConnectionsPool_c { mutable CSphMutex m_dDataLock; bool m_bShutdown = false; // will cause ReturnConnection to close the socket instead of returning it CSphTightVector<int> m_dSockets GUARDED_BY ( m_dDataLock ); int m_iRit GUARDED_BY ( m_dDataLock ) = 0; // pos where we take the next socket to rent. int m_iWit GUARDED_BY ( m_dDataLock ) = 0; // pos where we will put returned socket. int m_iFreeWindow GUARDED_BY ( m_dDataLock ) = 0; // # of free sockets in the existing ring int m_iLimit GUARDED_BY ( m_dDataLock ) = 0; // exact limit (embedded vector's limit is not exact) int Step ( int* ) REQUIRES ( m_dDataLock ); // step over the ring public: ~PersistentConnectionsPool_c () { Shutdown (); } void ReInit ( int iPoolSize ) REQUIRES ( !m_dDataLock ); int RentConnection () REQUIRES ( !m_dDataLock ); void ReturnConnection ( int iSocket ) REQUIRES ( !m_dDataLock ); void Shutdown () REQUIRES ( !m_dDataLock ); }; void ClosePersistentSockets(); struct MetricsAndCounters_t final : ISphRefcountedMT { // was uint64_t, but for atomic it creates extra tmpl instantiation without practical difference std::atomic<int64_t> m_dCounters[eMaxAgentStat]; // event counters uint64_t m_dMetrics[ehMaxStat]; // calculated metrics MetricsAndCounters_t () { Reset(); } void Reset () { for ( auto &iCounter : m_dCounters ) iCounter = 0; for ( auto &uMetric : m_dMetrics ) uMetric = 0; } void Add ( const MetricsAndCounters_t &rhs ) { for ( int i = 0; i<eMaxAgentStat; ++i ) m_dCounters[i].fetch_add ( rhs.m_dCounters[i].load ( std::memory_order_relaxed ), std::memory_order_relaxed ); if ( m_dMetrics[ehConnTries] ) m_dMetrics[ehAverageMsecs] = ( m_dMetrics[ehAverageMsecs] * m_dMetrics[ehConnTries] + rhs.m_dMetrics[ehAverageMsecs] * rhs.m_dMetrics[ehConnTries] ) / ( m_dMetrics[ehConnTries] + rhs.m_dMetrics[ehConnTries] ); else m_dMetrics[ehAverageMsecs] = rhs.m_dMetrics[ehAverageMsecs]; m_dMetrics[ehMaxMsecs] = Max ( m_dMetrics[ehMaxMsecs], rhs.m_dMetrics[ehMaxMsecs] ); m_dMetrics[ehConnTries] += rhs.m_dMetrics[ehConnTries]; } private: ~MetricsAndCounters_t () final = default; friend struct HostDashboard_t; // the only struct allowed to directly declare/destroy me. }; using MetricsAndCountersRefPtr_t = CSphRefcountedPtr<MetricsAndCounters_t>; struct HostDashboard_t; using HostDashboardRefPtr_t = CSphRefcountedPtr<HostDashboard_t>; using cHostDashboardRefPtr_t = CSphRefcountedPtr<const HostDashboard_t>; /// generic descriptor of remote host struct HostDesc_t { int m_iFamily = AF_INET; ///< TCP or UNIX socket CSphString m_sAddr; ///< remote searchd host (used to update m_uAddr with resolver) int m_iPort = -1; ///< remote searchd port, 0 if local DWORD m_uAddr = 0; ///< IP address bool m_bNeedResolve = false; ///< whether we keep m_uAddr, or call GetAddrInfo each time. bool m_bBlackhole = false; ///< blackhole agent flag bool m_bPersistent = false; ///< whether to keep the persistent connection to the agent. mutable HostDashboardRefPtr_t m_pDash; ///< ha dashboard of the host HostDesc_t &CloneFromHost ( const HostDesc_t &tOther ); CSphString GetMyUrl () const; }; /// generic descriptor of the mirror: host + indexes. struct AgentDesc_t : HostDesc_t { CSphString m_sIndexes; ///< remote index names to query mutable MetricsAndCountersRefPtr_t m_pMetrics; ///< source for ShowStatus (one copy shared over all clones, refcounted). AgentDesc_t &CloneFrom ( const AgentDesc_t &tOther ); }; // set of options which are applied to every agent line // and come partially from global config, partially m.b. set immediately in agent line as an option. struct AgentOptions_t { bool m_bBlackhole; bool m_bPersistent; HAStrategies_e m_eStrategy; int m_iRetryCount; int m_iRetryCountMultiplier; }; extern const char * sAgentStatsNames[(int)eMaxAgentStat + (int)ehMaxStat]; using HostMetricsSnapshot_t = uint64_t[(int)eMaxAgentStat + (int)ehMaxStat]; /// per-host dashboard struct HostDashboard_t : public ISphRefcountedMT { HostDesc_t m_tHost; // only host info, no indices. Used for ping. volatile int m_iNeedPing = 0; // we'll ping only HA agents, not everyone PersistentConnectionsPool_c * m_pPersPool = nullptr; // persistence pool also lives here, one per dashboard mutable RwLock_t m_dMetricsLock; // guards everything essential (see thread annotations) int64_t m_iLastAnswerTime GUARDED_BY ( m_dMetricsLock ) = sphMicroTimer(); // updated when we get an answer from the host int64_t m_iLastQueryTime GUARDED_BY ( m_dMetricsLock ) = sphMicroTimer(); // updated when we send a query to a host int64_t m_iErrorsARow GUARDED_BY ( m_dMetricsLock ) = 0; // num of errors a row, updated when we update the general statistic. DWORD m_uPingTripUS = 0; // round-trip in uS. We send ping with current time, on receive answer compare with current time and fix that difference public: explicit HostDashboard_t ( const HostDesc_t &tAgent = {}); int64_t EngageTime () const; MetricsAndCounters_t &GetCurrentMetrics () REQUIRES ( m_dMetricsLock ); void GetCollectedMetrics ( HostMetricsSnapshot_t &dResult, int iPeriods = 1 ) const REQUIRES ( !m_dMetricsLock ); static DWORD GetCurSeconds (); static bool IsHalfPeriodChanged ( DWORD * pLast ); private: struct { MetricsAndCounters_t m_dMetrics; DWORD m_uPeriod = 0xFFFFFFFF; } m_dPeriodicMetrics[STATS_DASH_PERIODS] GUARDED_BY ( m_dMetricsLock ); ~HostDashboard_t() override; }; class IPinger { public: virtual void Subscribe ( HostDashboardRefPtr_t pHost ) = 0; virtual ~IPinger() {} }; void SetGlobalPinger ( IPinger* pPinger ); /// context which keeps name of the index and agent /// (mainly for error-reporting) class WarnInfo_c { public: const char * m_szIndexName = nullptr; const char * m_szAgent = nullptr; WarnInfo_c ( const char * szIndexName, const char * szAgent, CSphString & sError, StrVec_t * pWarnings=nullptr ); void Warn ( const char * szFmt, ... ) const; /// format an error message using idx and agent names from own context /// \return always false, to simplify statements bool ErrSkip ( const char * szFmt, ... ) const; private: StrVec_t * m_pWarnings = nullptr; CSphString & m_sError; }; /// descriptor for set of agents (mirrors) (stored in a global hash) class MultiAgentDesc_c; using MultiAgentDescRefPtr_c = CSphRefcountedPtr<MultiAgentDesc_c>; using cMultiAgentDescRefPtr_c = CSphRefcountedPtr<const MultiAgentDesc_c>; class MultiAgentDesc_c final : public ISphRefcountedMT, public CSphFixedVector<AgentDesc_t> { std::atomic<int> m_iRRCounter {0}; /// round-robin counter mutable RwLock_t m_dWeightLock; /// manages access to m_pWeights CSphFixedVector<float> m_dWeights /// the weights of the hosts GUARDED_BY ( m_dWeightLock ) { 0 }; DWORD m_uTimestamp { HostDashboard_t::GetCurSeconds () }; /// timestamp of last weight's actualization HAStrategies_e m_eStrategy { HA_DEFAULT }; int m_iMultiRetryCount = 0; bool m_bNeedPing = false; /// ping need to hosts if we're HA and NOT bl. CSphString m_sConfigStr; /// agent configuration string, straight from .conf ~MultiAgentDesc_c () final; public: MultiAgentDesc_c () : CSphFixedVector<AgentDesc_t> { 0 } {} // configure using dTemplateHosts as source of urls/indexes static MultiAgentDescRefPtr_c GetAgent ( const CSphVector<AgentDesc_t *> & dTemplateHosts, const AgentOptions_t & tOpt, const WarnInfo_c & tWarn ); // housekeeping: walk throw global hash and finally release all 1-refs agents static void CleanupOrphaned(); const AgentDesc_t & ChooseAgent() REQUIRES ( !m_dWeightLock ); inline bool IsHA () const { return GetLength ()>1; } inline int GetRetryLimit () const { return m_iMultiRetryCount; } const CSphString & GetConfigStr() const { return m_sConfigStr; } CSphFixedVector<float> GetWeights () const REQUIRES ( !m_dWeightLock ) { ScRL_t tRguard ( m_dWeightLock ); CSphFixedVector<float> dResult { 0 }; dResult.CopyFrom ( m_dWeights ); return dResult; } private: const AgentDesc_t &RRAgent (); const AgentDesc_t &RandAgent (); const AgentDesc_t &StDiscardDead () REQUIRES ( !m_dWeightLock ); const AgentDesc_t &StLowErrors () REQUIRES ( !m_dWeightLock ); void ChooseWeightedRandAgent ( int * pBestAgent, CSphVector<int> &dCandidates ) REQUIRES ( !m_dWeightLock ); void CheckRecalculateWeights ( const CSphFixedVector<int64_t> &dTimers ) REQUIRES ( !m_dWeightLock ); static CSphString GetKey( const CSphVector<AgentDesc_t *> &dTemplateHosts, const AgentOptions_t &tOpt ); bool Init ( const CSphVector<AgentDesc_t *> &dTemplateHosts, const AgentOptions_t &tOpt, const WarnInfo_c & tWarn ); }; extern int g_iAgentRetryCount; extern int g_iAgentRetryDelayMs; class Reporter_i : public ISphRefcountedMT { public: // called by netloop - initially feeds reporter with tasks // For every task just before start querying it calls FeedTask(true). // If task is not to be traced (blackhole), it then calls FeedTask(false). virtual void FeedTask ( bool bAdd ) = 0; // called by netloop - when one of the task is finished (and tells, success or not). Good point for callback! // false returned in case of permanent error (dead; retries limit exceeded) and when aborting due to shutdown. virtual void Report ( bool bSuccess ) = 0; // called by outline observer, or by netloop checking for orphaned // must return 'true' if reporter is abandoned - i.e. if all expected connections are finished. virtual bool IsDone () const = 0; }; #if _WIN32 struct SingleOverlapped_t : public OVERLAPPED { ULONG_PTR m_uParentOffset; // how many bytes add to this to take pointer to parent volatile bool m_bInUse = false; inline void Zero () { ZeroMemory ( this, sizeof ( OVERLAPPED ) ); } }; struct DoubleOverlapped_t { SingleOverlapped_t m_dWrite; SingleOverlapped_t m_dRead; CSphFixedVector<BYTE> m_dReadBuf { 0 }; // used for canceling recv operation CSphVector<ISphOutputBuffer *> m_dWriteBuf; // used for canceling send operation CSphVector<sphIovec> m_dOutIO; // used for canceling send operation inline bool IsInUse() { return m_dWrite.m_bInUse || m_dRead.m_bInUse; } DoubleOverlapped_t() { m_dWrite.Zero(); m_dRead.Zero(); m_dWrite.m_uParentOffset = (LPBYTE) &m_dWrite-(LPBYTE) this; m_dRead.m_uParentOffset = (LPBYTE) &m_dRead-(LPBYTE) this; } ~DoubleOverlapped_t() { for ( auto* pWriteBuf : m_dWriteBuf ) SafeDelete (pWriteBuf); } }; using LPKEY = DoubleOverlapped_t *; #else using LPKEY = void *; #endif class IOVec_c { CSphVector<sphIovec> m_dIOVec; size_t m_iIOChunks = 0; public: void BuildFrom ( const SmartOutputBuffer_t& tSource ); /// take data from linked source void Reset (); /// consume received chunk void StepForward ( size_t uStep ); inline bool HasUnsent () const noexcept { return m_iIOChunks!=0; } /// if we have data (despite it is sent or not) inline bool IsEmpty () const noexcept { return m_dIOVec.IsEmpty (); } /// buf for sendmsg/WSAsend inline sphIovec * IOPtr () const noexcept { if ( !m_iIOChunks ) return nullptr; return m_dIOVec.end () - m_iIOChunks; } /// num of io vecs for sendmsg/WSAsend inline size_t IOSize () const noexcept { return m_iIOChunks; } #if _WIN32 inline void LeakTo ( CSphVector<sphIovec>& dIOVec ) { m_dIOVec.SwapData ( dIOVec ); } #endif }; struct iQueryResult { virtual ~iQueryResult() = default; virtual void Reset() = 0; [[nodiscard]] virtual bool HasWarnings() const = 0; }; struct DefaultQueryResult_t : public iQueryResult { void Reset() final {} [[nodiscard]] bool HasWarnings() const final { return false; } }; /// remote agent connection (local per-query state) struct AgentConn_t : public ISphRefcountedMT { enum ETimeoutKind { TIMEOUT_UNKNOWN, TIMEOUT_RETRY, TIMEOUT_HARD, }; public: AgentDesc_t m_tDesc; ///< desc of my host // fixme! turn to ref to MultiAgent mirror? int m_iSock = -1; // time-tracking and timeout settings int m_iMyConnectTimeoutMs { g_iAgentConnectTimeoutMs }; ///< populated from parent distr int64_t m_iMyQueryTimeoutMs { g_iAgentQueryTimeoutMs }; ///< in msec int64_t m_iStartQuery = 0; ///< the timestamp of the latest request // actualized int64_t m_iEndQuery = 0; ///< the timestamp of the end of the latest operation // actual int64_t m_iWall = 0; ///< wall time spent vs this agent // actualized int64_t m_iWaited = 0; ///< statistics of waited // some external stuff std::unique_ptr<iQueryResult> m_pResult; ///< multi-query results CSphString m_sFailure; ///< failure message (both network and logical) mutable int m_iStoreTag = -1; ///< cookie, m.b. used to 'glue' to concrete connection int m_iWeight = -1; ///< weight of the index, will be send with query to remote host CSphRefcountedPtr<Reporter_i> m_pReporter { nullptr }; ///< used to report back when we're finished LPKEY m_pPollerTask = nullptr; ///< internal for poller. fixme! privatize? volatile bool m_bSuccess {false}; ///< agent got processed, no need to retry public: AgentConn_t () = default; void SetMultiAgent ( MultiAgentDescRefPtr_c pMirror ); inline bool IsBlackhole () const { return m_tDesc.m_bBlackhole; } inline bool InNetLoop() const { return m_bInNetLoop; } inline void SetNetLoop ( bool bInNetLoop = true ) { m_bInNetLoop = bInNetLoop; } inline bool FireKick () { bool bRes = m_bNeedKick; m_bNeedKick = false; return bRes; } void GenericInit ( RequestBuilder_i * pQuery, ReplyParser_i * pParser, Reporter_i * pReporter, int iQueryRetry, int iQueryDelay ); void StartRemoteLoopTry (); void ErrorCallback ( int64_t iWaited ); void SendCallback ( int64_t iWaited, DWORD uSent ); void RecvCallback ( int64_t iWaited, DWORD uReceived ); void TimeoutCallback (); void AbortCallback(); bool CheckOrphaned(); void SetNoLimitReplySize(); #if _WIN32 // move recv buffer to dOut, reinit mine. void LeakRecvTo ( CSphFixedVector<BYTE>& dOut ); void LeakSendTo ( CSphVector <ISphOutputBuffer* >& dOut, CSphVector<sphIovec>& dOutIO ); #endif // helper for beautiful logging inline const char * StateName () const { return Agent_e_Name ( m_eConnState ); } private: // prepare buf, parse result RequestBuilder_i * m_pBuilder = nullptr; ///< fixme! check if it is ok to have as the member, or we don't need it actually ReplyParser_i * m_pParser = nullptr; // working with mirrors MultiAgentDescRefPtr_c m_pMultiAgent { nullptr }; ///< my manager, could turn me into another mirror int m_iRetries = 0; ///< initialized to max num of tries. 0 mean 1 try, no re-tries. int m_iMirrorsCount = 1; int m_iDelay { g_iAgentRetryDelayMs }; ///< delay between retries // active timeout (directly used by poller) int64_t m_iPoolerTimeoutPeriodUS = -1; int64_t m_iPoolerTimeoutUS = -1; ///< m.b. query, or connect+query when TCP_FASTOPEN ETimeoutKind m_eTimeoutKind { TIMEOUT_UNKNOWN }; // receiving buffer stuff CSphFixedVector<BYTE> m_dReplyBuf { 0 }; int m_iReplySize = -1; ///< how many reply bytes are there static const size_t REPLY_HEADER_SIZE = 12; CSphFixedVector<BYTE> m_dReplyHeader { REPLY_HEADER_SIZE }; BYTE * m_pReplyCur = nullptr; bool m_bReplyLimitSize = true; // sending buffer stuff SmartOutputBuffer_t m_tOutput; ///< chain of blobs we're sending to a host IOVec_c m_dIOVec; // states and flags bool m_bConnectHandshake = false; ///< if we need to establish new connection, and so, wait back handshake version bool m_bInNetLoop = false; ///< if we're inside netloop (1-thread work with schedule) bool m_bNeedKick = false; ///< if we've installed callback from outside th and need to kick netloop bool m_bManyTries = false; ///< to avoid report 'retries limit esceeded' if we have ONLY one retry Agent_e m_eConnState { Agent_e::HEALTHY }; ///< current state SearchdStatus_e m_eReplyStatus { SEARCHD_ERROR }; ///< reply status code private: ~AgentConn_t () override; // switch/check internal state inline bool StateIs ( Agent_e eState ) const { return eState==m_eConnState; } void State ( Agent_e eState ); bool IsPersistent(); void ReturnPersist (); bool Fail ( const char * sFmt, ... ) __attribute__ ( ( format ( printf, 2, 3 ) ) ); bool Fatal ( AgentStats_e eStat, const char * sMessage, ... ) __attribute__ ( ( format ( printf, 3, 4 ) ) ); void Finish ( bool bFailed = false ); /// finish the task, stat time. bool BadResult ( int iError = 0 ); /// always return false void ReportFinish ( bool bSuccess = true ); void SendingState (); ///< from CONNECTING state go to HEALTHY and switch timer to QUERY timeout. bool StartNextRetry (); void LazyTask ( int64_t iTimeoutMS, int64_t iTimeoutPeriodUS, bool bHardTimeout = false, BYTE ActivateIO = 0 ); // 1=RW, 2=RO. void LazyDeleteOrChange ( int64_t iTimeoutMS = -1, int64_t iTimeoutPeriodUS = -1 ); void ScheduleCallbacks (); void DisableWrite(); void BuildData (); size_t ReplyBufPlace () const; void InitReplyBuf ( int iSize = 0 ); inline bool IsReplyHeader() const { return m_iReplySize<0; } SSIZE_T SendChunk (); // low-level (platform specific) send SSIZE_T RecvChunk (); // low-level (platform specific) recv int DoTFO ( struct sockaddr * pSs, int iLen ); bool DoQuery (); bool EstablishConnection (); bool SendQuery (DWORD uSent = 0); bool ReceiveAnswer (DWORD uReceived = 0); bool CommitResult (); bool SwitchBlackhole (); }; using VectorAgentConn_t = CSphVector<AgentConn_t *>; using VecRefPtrsAgentConn_t = VecRefPtrs_t<AgentConn_t *>; class RemoteAgentsObserver_i : public Reporter_i { public: // get num of succeeded agents virtual long GetSucceeded () const = 0; // get num of succeeded agents virtual long GetFinished () const = 0; // block execution while there are works to do virtual void Finish () = 0; // block execution while some works finished virtual void WaitChanges () = 0; }; RemoteAgentsObserver_i * GetObserver (); void ScheduleDistrJobs ( VectorAgentConn_t &dRemotes, RequestBuilder_i * pQuery, ReplyParser_i * pParser, Reporter_i * pReporter, int iQueryRetry = -1, int iQueryDelay = -1 ); // schedule one job. Returns false if connection s blackhole (and so, will not report anything using Deffered_f = std::function<void ( bool )>; bool RunRemoteTask ( AgentConn_t* pConnection, RequestBuilder_i* pQuery, ReplyParser_i* pParser, Deffered_f && pAction, int iQueryRetry = -1, int iQueryDelay = -1 ); bool RunRemoteTask ( AgentConn_t* pConnection, RequestBuilder_i* pQuery, ReplyParser_i* pParser, Deffered_f & pAction, int iQueryRetry = -1, int iQueryDelay = -1 ); // simplified full task - schedule jobs, wait for complete, report num of succeeded // uses cooperated wait - i.e. yield instead of pause int PerformRemoteTasks ( VectorAgentConn_t &dRemotes, RequestBuilder_i * pQuery, ReplyParser_i * pParser, int iQueryRetry = -1, int iQueryDelay = -1 ); ///////////////////////////////////////////////////////////////////////////// // DISTRIBUTED QUERIES ///////////////////////////////////////////////////////////////////////////// /// distributed index struct DistributedIndex_t : public ISphRefcountedMT { CSphVector<MultiAgentDescRefPtr_c> m_dAgents; ///< remote agents StrVec_t m_dLocal; ///< local indexes int m_iAgentRetryCount = 0; ///< overrides global one bool m_bDivideRemoteRanges = false; ///< whether we divide big range onto agents or not HAStrategies_e m_eHaStrategy = HA_DEFAULT; ///< how to select the best of my agents mutable ServedStats_c m_tStats; CSphString m_sCluster; // get hive of all index'es hosts (not agents, but hosts, i.e. all mirrors as simple vector) void GetAllHosts ( VectorAgentConn_t &dTarget ) const; inline bool IsEmpty() const { return m_dAgents.IsEmpty() && m_dLocal.IsEmpty(); } template<typename FUNC> void ForEveryHost ( FUNC&& pFunc ) { for ( auto& pAgent : m_dAgents ) for ( auto& dHost : *pAgent ) pFunc ( dHost ); } template<typename FUNC> void ForEveryHost ( FUNC&& pFunc ) const { for ( auto& pAgent : m_dAgents ) for ( auto& dHost : *pAgent ) pFunc ( dHost ); } int GetAgentConnectTimeoutMs ( bool bRaw=false ) const; int GetAgentQueryTimeoutMs ( bool bRaw=false ) const; void SetAgentConnectTimeoutMs ( int iAgentConnectTimeoutMs ); void SetAgentQueryTimeoutMs ( int iAgentQueryTimeoutMs ); DistributedIndex_t * Clone() const; private: ~DistributedIndex_t() override; int m_iAgentConnectTimeoutMs = 0; ///< in msec, 0 means g_iAgentConnectTimeoutMs int m_iAgentQueryTimeoutMs = 0; ///< in msec, 0 means g_iAgentQueryTimeoutMs }; using DistributedIndexRefPtr_t = CSphRefcountedPtr<DistributedIndex_t>; using cDistributedIndexRefPtr_t = CSphRefcountedPtr<const DistributedIndex_t>; using ReadOnlyDistrHash_c = ReadOnlyHash_T<DistributedIndex_t>; using WriteableDistrHash_c = WriteableHash_T<DistributedIndex_t>; extern std::unique_ptr<ReadOnlyDistrHash_c> g_pDistIndexes; // distributed indexes hash inline cDistributedIndexRefPtr_t GetDistr ( const CSphString& sName ) { assert ( g_pDistIndexes ); return g_pDistIndexes->Get ( sName ); } struct GuardedQueryStatContainer_t { mutable RwLock_t m_tStatsLock; std::unique_ptr<QueryStatContainer_i> m_tStats GUARDED_BY ( m_tStatsLock ); }; struct SearchdStats_t { DWORD m_uStarted; std::atomic<int64_t> m_iConnections; std::atomic<int64_t> m_iMaxedOut; std::array<std::atomic<int64_t>, SEARCHD_COMMAND_TOTAL> m_iCommandCount; std::atomic<int64_t> m_iAgentConnect; std::atomic<int64_t> m_iAgentConnectTFO; std::atomic<int64_t> m_iAgentRetry; std::atomic<int64_t> m_iQueries; ///< search queries count (differs from search commands count because of multi-queries) std::atomic<int64_t> m_iQueryTime; ///< wall time spent (including network wait time) std::atomic<int64_t> m_iQueryCpuTime; ///< CPU time spent std::atomic<int64_t> m_iDistQueries; ///< distributed queries count std::atomic<int64_t> m_iDistWallTime; ///< wall time spent on distributed queries std::atomic<int64_t> m_iDistLocalTime; ///< wall time spent searching local indexes in distributed queries std::atomic<int64_t> m_iDistWaitTime; ///< time spent waiting for remote agents in distributed queries std::atomic<int64_t> m_iDiskReads; ///< total read IO calls (fired by search queries) std::atomic<int64_t> m_iDiskReadBytes; ///< total read IO traffic std::atomic<int64_t> m_iDiskReadTime; ///< total read IO time std::atomic<int64_t> m_iPredictedTime; ///< total agent predicted query time std::atomic<int64_t> m_iAgentPredictedTime; ///< total agent predicted query time enum EDETAILS : BYTE { eUpdate, eReplace, eSearch, eTotal }; std::array<GuardedQueryStatContainer_t, eTotal> m_dDetailedStats; }; void InitSearchdStats (); void StatCountCommandDetails ( SearchdStats_t::EDETAILS eCmd, uint64_t uFoundRows, uint64_t tmStart ); void FormatCmdStats ( VectorLike & dStatus, const char * szPrefix, SearchdStats_t::EDETAILS eCmd ); SearchdStats_t& gStats(); namespace Dashboard { void LinkHost ( HostDesc_t& dHost ); ///< put host into global dashboard and init link to it HostDashboardRefPtr_t FindAgent ( const CSphString& sAgent ); CSphVector<HostDashboardRefPtr_t> GetActiveHosts (); void CleanupOrphaned (); } // parse strategy name into enum value bool ParseStrategyHA ( const char * sName, HAStrategies_e & eStrategy ); CSphString HAStrategyToStr ( HAStrategies_e eStrategy ); // parse ','-delimited list of indexes void ParseIndexList ( const CSphString &sIndexes, StrVec_t &dOut ); // try to parse hostname/ip/port or unixsocket on current pConfigLine. // fill pAgent fields on success and move ppLine pointer next after parsed instance // if :port is skipped in the line, IANA 9312 will be used in the case bool ParseAddressPort ( HostDesc_t & pAgent, const char ** ppLine, const WarnInfo_c & tInfo ); //! Parse line with agent definition and return addreffed pointer to multiagent (new or from global cache) //! \param szAgent - line with agent definition from config //! \param szIndexName - index we apply to //! \param tOptions - global options affecting agent //! \return configured multiagent, or null if failed MultiAgentDescRefPtr_c ConfigureMultiAgent ( const char * szAgent, const char * szIndexName, AgentOptions_t tOptions, CSphString & sError, StrVec_t * pWarnings=nullptr ); class RequestBuilder_i : public ISphNoncopyable { public: virtual ~RequestBuilder_i () {} // to avoid gcc4 warns virtual void BuildRequest ( const AgentConn_t &tAgent, ISphOutputBuffer &tOut ) const = 0; }; class ReplyParser_i { public: virtual ~ReplyParser_i () {} // to avoid gcc4 warns virtual bool ParseReply ( MemInputBuffer_c &tReq, AgentConn_t &tAgent ) const = 0; }; /// check if a non-blocked socket is still connected bool sphNBSockEof ( int iSock ); class SphinxqlRequestBuilder_c : public RequestBuilder_i { public: SphinxqlRequestBuilder_c ( Str_t sQuery, const SqlStmt_t & tStmt ); void BuildRequest ( const AgentConn_t & tAgent, ISphOutputBuffer & tOut ) const final; protected: const Str_t m_sBegin; const Str_t m_sEnd; }; class SphinxqlReplyParser_c : public ReplyParser_i { public: explicit SphinxqlReplyParser_c ( int * pUpd, int * pWarns ); bool ParseReply ( MemInputBuffer_c & tReq, AgentConn_t & ) const final; protected: int * m_pUpdated; int * m_pWarns; }; void RemotesGetField ( AggrResult_t & tRes, const CSphQuery & tQuery ); void HandleCommandGetField ( ISphOutputBuffer & tOut, WORD uVer, InputBuffer_c & tReq ); #endif // _searchdha_
29,323
C++
.h
662
42.265861
170
0.730714
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,128
client_task_info.h
manticoresoftware_manticoresearch/src/client_task_info.h
// // Copyright (c) 2021-2024, Manticore Software LTD (https://manticoresearch.com) // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org // #pragma once #include "sphinxstd.h" #include "task_info.h" #include "task_dispatcher.h" #include <boost/intrusive/slist.hpp> enum Profile_e { NONE, PLAIN, DOT, DOTEXPR, DOTEXPRURL, }; class ClientSession_c; class RowBuffer_i; using ClientTaskHook_t = boost::intrusive::slist_member_hook<>; // client connection (session). Includes both state and settings. struct ClientTaskInfo_t : public MiniTaskInfo_t { DECLARE_RENDER( ClientTaskInfo_t ); private: TaskState_e m_eTaskState = TaskState_e::UNKNOWN; Proto_e m_eProto = Proto_e::UNKNOWN; int m_iConnID = -1; int m_iSocket = -1; CSphString m_sClientName; // set once before info is published and never changes. So, assume always mt-safe bool m_bSsl = false; bool m_bVip = false; bool m_bReadOnly = false; bool m_bKilled = false; bool m_bBuddy = false; // session variables - doesn't participate in render, used as connection-wide globals public: int m_iThrottlingPeriodMS = -1; int m_iDistThreads = 0; int m_iDesiredStack = -1; int m_iTimeoutS = -1; int m_iWTimeoutS = -1; int64_t m_iMaxStackSize = Threads::GetMaxCoroStackSize(); bool m_bSqlQuoteShowCreate = false; bool m_bQueryDisableLog = false; ESphCollation m_eCollation { GlobalCollation () }; Profile_e m_eProfile { Profile_e::NONE }; bool m_bPersistent = false; RowBuffer_i * m_pSqlRowBuffer = nullptr; void* m_pSessionOpaque1 = nullptr; void* m_pSessionOpaque2 = nullptr; static std::atomic<int> m_iClients; static std::atomic<int> m_iVips; static std::atomic<int> m_iBuddy; Dispatcher::Template_t m_tBaseDispatcherTemplate; Dispatcher::Template_t m_tPseudoShardingDispatcherTemplate; ClientTaskHook_t m_tLink; private: ClientSession_c* m_pSession = nullptr; public: // generic setters/getters. They're defined just to help keep multi-threading clean. void SetTaskState ( TaskState_e eState ); TaskState_e GetTaskState() const { return m_eTaskState; } void SetProto ( Proto_e eProto ) { m_eProto = eProto; } Proto_e GetProto() const { return m_eProto; } void SetConnID ( int iConnID ) { m_iConnID = iConnID; } int GetConnID() const { return m_iConnID; } void SetSocket ( int iSocket ) { m_iSocket = iSocket; } int GetSocket() const { return m_iSocket; } void SetClientName ( const char* szName ) { m_sClientName = szName; } const char* szClientName() const { return m_sClientName.cstr(); } void SetSsl ( bool bSsl ) { m_bSsl = bSsl; } bool GetSsl() const { return m_bSsl; } void SetVip ( bool bVip ) { m_bVip = bVip; } bool GetVip() const { return m_bVip; } inline static int GetVips() { return m_iVips.load ( std::memory_order_relaxed ); } inline static int GetClients() { return m_iClients.load ( std::memory_order_relaxed ); } void SetBuddy ( bool bBuddy ); bool GetBuddy() const { return m_bBuddy; } inline static int GetBuddyCount() { return m_iBuddy.load ( std::memory_order_relaxed ); } void SetReadOnly ( bool bReadOnly ) { m_bReadOnly = bReadOnly; } bool GetReadOnly() const { return m_bReadOnly; } void SetKilled ( bool bKilled ) { m_bKilled = bKilled; } bool GetKilled() const { return m_bKilled; } public: void SetThrottlingPeriodMS ( int iThrottlingPeriodMS ) { m_iThrottlingPeriodMS = iThrottlingPeriodMS; } int GetThrottlingPeriodMS () const { return m_iThrottlingPeriodMS; } void SetDistThreads (int iDistThreads) { m_iDistThreads = iDistThreads; } int GetDistThreads () const { return m_iDistThreads; } void ExpandDesiredStack ( int iDesiredStack ) { m_iDesiredStack = Max ( iDesiredStack, m_iDesiredStack ); } int GetDesiredStack() const { return m_iDesiredStack; } void SetTimeoutS ( int iTimeoutS ) { m_iTimeoutS = iTimeoutS; } int GetTimeoutS() const { return m_iTimeoutS;} void SetWTimeoutS ( int iTimeoutS ) { m_iWTimeoutS = iTimeoutS; } int GetWTimeoutS() const { return m_iWTimeoutS; } void SetSqlQuoteShowCreate ( bool bSqlQuoreShowCreate ) { m_bSqlQuoteShowCreate = bSqlQuoreShowCreate; } int GetSqlQuoteShowCreate() const { return m_bSqlQuoteShowCreate; } void SetCollation ( ESphCollation eCollation ) { m_eCollation = eCollation; } ESphCollation GetCollation() const { return m_eCollation; } void SetProfile ( Profile_e eProfile ) { m_eProfile = eProfile; } Profile_e GetProfile() const { return m_eProfile; } bool IsProfile () const { return m_eProfile!=Profile_e::NONE; } bool IsDot () const { return m_eProfile==Profile_e::DOT; } void SetPersistent ( bool bPersistent ) { m_bPersistent = bPersistent; } bool GetPersistent () const { return m_bPersistent; } void SetBaseDispatcherTemplate ( Dispatcher::Template_t tDispatcherTemplate ) { m_tBaseDispatcherTemplate = tDispatcherTemplate; } Dispatcher::Template_t GetBaseDispatcherTemplate() const { return m_tBaseDispatcherTemplate; } void SetPseudoShardingDispatcherTemplate ( Dispatcher::Template_t tDispatcherTemplate ) { m_tPseudoShardingDispatcherTemplate = tDispatcherTemplate; } Dispatcher::Template_t GetPseudoShardingDispatcherTemplate() const { return m_tPseudoShardingDispatcherTemplate; } void SetClientSession ( ClientSession_c* ); ClientSession_c* GetClientSession(); public: static ClientTaskInfo_t& Info ( bool bStrict = false ) noexcept; }; inline bool operator== ( const ClientTaskInfo_t& lhs, const ClientTaskInfo_t& rhs ) { return &lhs==&rhs; } using TaskIteratorFn = std::function<void ( ClientTaskInfo_t* )>; void IterateTasks ( TaskIteratorFn&& ); namespace session { inline ClientTaskInfo_t & Info (bool bStrict=false){ return ClientTaskInfo_t::Info(bStrict); } inline ClientSession_c* GetClientSession() { return ClientTaskInfo_t::Info().GetClientSession(); } // generic getters. If more than one assumed, consider to call Info() once and use ref instead of these 'globals' inline void SetTaskState ( TaskState_e eState ) { ClientTaskInfo_t::Info().SetTaskState ( eState ); } inline TaskState_e GetTaskState() { return ClientTaskInfo_t::Info().GetTaskState(); } inline void SetProto ( Proto_e eProto ) { ClientTaskInfo_t::Info().SetProto (eProto); } inline Proto_e GetProto() { return ClientTaskInfo_t::Info().GetProto(); } inline void SetConnID ( int iConnID ) { ClientTaskInfo_t::Info().SetConnID (iConnID); } inline int GetConnID() { return ClientTaskInfo_t::Info().GetConnID(); } inline void SetClientName ( const char* szName ) { ClientTaskInfo_t::Info().SetClientName (szName); } inline const char* szClientName() { return ClientTaskInfo_t::Info().szClientName(); } inline void SetSsl ( bool bSsl ) { ClientTaskInfo_t::Info().SetSsl (bSsl); } inline bool GetSsl() { return ClientTaskInfo_t::Info().GetSsl(); } inline bool GetVip() { return ClientTaskInfo_t::Info().GetVip(); } inline int GetVips() { return ClientTaskInfo_t::GetVips(); } inline int GetClients() { return ClientTaskInfo_t::GetClients(); } inline bool GetBuddy() { return ClientTaskInfo_t::Info().GetBuddy(); } inline int GetBuddyCount() { return ClientTaskInfo_t::GetBuddyCount(); } inline void SetReadOnly ( bool bReadOnly ) { ClientTaskInfo_t::Info().SetReadOnly (bReadOnly); } inline bool GetReadOnly() { return ClientTaskInfo_t::Info().GetReadOnly(); } inline bool GetKilled() { return ClientTaskInfo_t::Info().GetKilled(); } inline void SetKilled ( bool bKilled ) { ClientTaskInfo_t::Info().SetKilled(bKilled); } inline void SetThrottlingPeriodMS ( int iThrottlingPeriodMS ) { ClientTaskInfo_t::Info().SetThrottlingPeriodMS ( iThrottlingPeriodMS ); } inline int GetThrottlingPeriodMS () { return ClientTaskInfo_t::Info().GetThrottlingPeriodMS(); } inline void SetDistThreads (int iDistThreads) { ClientTaskInfo_t::Info().SetDistThreads ( iDistThreads); } inline int GetDistThreads () { return ClientTaskInfo_t::Info().GetDistThreads(); } inline void ExpandDesiredStack ( int iDesiredStack ) { ClientTaskInfo_t::Info().ExpandDesiredStack ( iDesiredStack ); } inline int GetDesiredStack() { return ClientTaskInfo_t::Info().GetDesiredStack(); } inline void SetTimeoutS ( int iTimeoutS ) { ClientTaskInfo_t::Info().SetTimeoutS ( iTimeoutS ); } inline int GetTimeoutS() { return ClientTaskInfo_t::Info().GetTimeoutS(); } inline void SetWTimeoutS ( int iTimeoutS ) { ClientTaskInfo_t::Info().SetWTimeoutS ( iTimeoutS ); } inline int GetWTimeoutS() { return ClientTaskInfo_t::Info().GetWTimeoutS(); } inline void SetCollation ( ESphCollation eCollation ) { ClientTaskInfo_t::Info().SetCollation ( eCollation ); } inline ESphCollation GetCollation() { return ClientTaskInfo_t::Info().GetCollation(); } inline void SetProfile ( Profile_e eProfile ) { ClientTaskInfo_t::Info().SetProfile ( eProfile ); } inline Profile_e GetProfile() { return ClientTaskInfo_t::Info().GetProfile(); } inline bool IsProfile () { return ClientTaskInfo_t::Info().IsProfile(); } inline bool IsDot () { return ClientTaskInfo_t::Info().IsDot(); } inline void SetPersistent ( bool bPersistent ) { ClientTaskInfo_t::Info().SetPersistent(bPersistent); } inline bool GetPersistent () { return ClientTaskInfo_t::Info().GetPersistent(); } inline void SetMaxStackSize ( int64_t iStackSize ) { ClientTaskInfo_t::Info().m_iMaxStackSize = iStackSize; } inline int64_t GetMaxStackSize() noexcept { return ClientTaskInfo_t::Info().m_iMaxStackSize; } inline void SetQueryDisableLog () { ClientTaskInfo_t::Info().m_bQueryDisableLog = true; } inline bool IsQueryLogDisabled () { return ClientTaskInfo_t::Info().m_bQueryDisableLog; } } // namespace session namespace myinfo { // num of client tasks, not including vips inline int CountClients () { return session::GetClients() - ( session::GetVips() + session::GetBuddyCount() ); } // num of real tasks (that is mini-info + client-info) inline int CountTasks() { return Count ( MiniTaskInfo_t::Task() ) + Count ( ClientTaskInfo_t::Task() ); } } // namespace myinfo volatile int &getDistThreads (); // provides daemon-wide global dist-threads, or task-local, if any exists, or 0 if none int GetEffectiveDistThreads (); // provides unified dispatcher of global and local Dispatcher::Template_t GetEffectiveBaseDispatcherTemplate(); Dispatcher::Template_t GetEffectivePseudoShardingDispatcherTemplate();
10,501
C++
.h
188
53.728723
151
0.752611
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,129
sphinxpq.h
manticoresoftware_manticoresearch/src/sphinxpq.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // // This header shares some structs and methods related to Percolate indexes // in order to acces them in unit-tests #ifndef MANTICORE_SPHINXPQ_H #define MANTICORE_SPHINXPQ_H #include "sphinxsearch.h" #include "sphinxrt.h" #include "searchdha.h" #include "accumulator.h" #include "querycontext.h" // stuff moved here from sphinxrt.h struct PercolateQueryDesc { int64_t m_iQUID; CSphString m_sQuery; CSphString m_sTags; CSphString m_sFilters; bool m_bQL; void Swap ( PercolateQueryDesc & tOther ); }; struct PercolateMatchResult_t : ISphNoncopyable { bool m_bGetDocs = false; bool m_bGetQuery = false; bool m_bGetFilters = true; int m_iQueriesMatched = 0; int m_iQueriesFailed = 0; int m_iDocsMatched = 0; int64_t m_tmTotal = 0; // verbose data bool m_bVerbose = false; int m_iEarlyOutQueries = 0; int m_iTotalQueries = 0; int m_iOnlyTerms = 0; int64_t m_tmSetup = 0; Warner_c m_sMessages; CSphFixedVector<PercolateQueryDesc> m_dQueryDesc { 0 }; CSphFixedVector<int> m_dDocs { 0 }; CSphFixedVector<int> m_dQueryDT { 0 }; // microsecond time per query PercolateMatchResult_t() = default; PercolateMatchResult_t ( PercolateMatchResult_t&& rhs ) noexcept; PercolateMatchResult_t& operator = ( PercolateMatchResult_t rhs ) noexcept; void Swap ( PercolateMatchResult_t& rhs ) noexcept; void Reset (); }; struct PercolateQueryArgs_t { const char * m_sQuery = nullptr; const char * m_sTags = nullptr; const VecTraits_T<CSphFilterSettings> & m_dFilters; const VecTraits_T<FilterTreeItem_t> & m_dFilterTree; int64_t m_iQUID = 0; bool m_bQL = true; bool m_bReplace = false; PercolateQueryArgs_t ( const VecTraits_T<CSphFilterSettings> & dFilters, const VecTraits_T<FilterTreeItem_t> & dFilterTree ); explicit PercolateQueryArgs_t ( const StoredQueryDesc_t & tDesc ); }; class StoredQuery_i; class PercolateIndex_i : public RtIndex_i { public: PercolateIndex_i ( CSphString sIndexName, CSphString sPath ) : RtIndex_i { std::move ( sIndexName ), std::move ( sPath ) } {} virtual bool MatchDocuments ( RtAccum_t * pAccExt, PercolateMatchResult_t & tResult ) = 0; virtual std::unique_ptr<StoredQuery_i> CreateQuery ( PercolateQueryArgs_t & tArgs, CSphString & sError ) = 0; bool IsPQ() const override { return true; } }; /// percolate query index factory std::unique_ptr<PercolateIndex_i> CreateIndexPercolate ( CSphString sIndexName, CSphString sPath, CSphSchema tSchema ); void FixPercolateSchema ( CSphSchema & tSchema ); using CreateQueryParser_fn = std::unique_ptr<QueryParser_i> ( bool bJson ); void SetPercolateQueryParserFactory ( CreateQueryParser_fn * pCall ); static const int PQ_META_VERSION_MAX = 255; void LoadStoredQuery ( ByteBlob_t tData, StoredQueryDesc_t& tQuery ); void LoadStoredQuery ( DWORD uVersion, StoredQueryDesc_t & tQuery, CSphReader & tReader ); void LoadStoredQueryV6 ( DWORD uVersion, StoredQueryDesc_t & tQuery, CSphReader & tReader ); void SaveStoredQuery ( const StoredQueryDesc_t & tQuery, MemoryWriter_c& tWriter ); void SaveStoredQuery ( const StoredQueryDesc_t & tQuery, CSphWriter & tWriter ); void LoadDeleteQuery ( ByteBlob_t tData, CSphVector<int64_t>& dQueries, CSphString& sTags ); void LoadDeleteQuery ( CSphVector<int64_t> & dQueries, CSphString & sTags, CSphReader & tReader ); void SaveDeleteQuery ( const VecTraits_T<int64_t>& dQueries, const char * sTags, MemoryWriter_c& tWriter ); void SaveDeleteQuery ( const VecTraits_T<int64_t>& dQueries, const char * sTags, CSphWriter & tWriter ); ////////////////////////////////////////////////////////////////////////// struct DictTerm_t { SphWordID_t m_uWordID = 0; int m_iWordOff = 0; int m_iWordLen = 0; }; struct DictMap_t { OpenHashTable_T<int64_t, DictTerm_t> m_hTerms { 0 }; CSphFixedVector<BYTE> m_dKeywords { 0 }; SphWordID_t GetTerm ( BYTE * pWord ) const; }; struct StoredQuery_t; struct SegmentReject_t { CSphVector<uint64_t> m_dTerms; CSphFixedVector<uint64_t> m_dWilds { 0 }; CSphFixedVector<CSphVector<uint64_t> > m_dPerDocTerms { 0 }; CSphFixedVector<uint64_t> m_dPerDocWilds { 0 }; int m_iRows = 0; bool Filter ( const StoredQuery_t * pStored, bool bUtf8 ) const; }; class PercolateQwordSetup_c : public ISphQwordSetup { public: PercolateQwordSetup_c ( const RtSegment_t * pSeg, int iMaxCodepointLength, ESphHitless eHitless ) : m_pSeg ( pSeg ) , m_iMaxCodepointLength ( iMaxCodepointLength ) , m_eHitless ( eHitless ) {} ISphQword * QwordSpawn ( const XQKeyword_t & ) const final; bool QwordSetup ( ISphQword * pQword ) const final; ISphQword * ScanSpawn() const final; private: const RtSegment_t * m_pSeg; int m_iMaxCodepointLength; ESphHitless m_eHitless = SPH_HITLESS_NONE; }; class PercolateDictProxy_c : public DictStub_c { const DictMap_t * m_pDict = nullptr; const bool m_bHasMorph = false; DictRefPtr_c m_pDictMorph; public: explicit PercolateDictProxy_c ( bool bHasMorph, DictRefPtr_c pDictMorph ) : m_bHasMorph ( bHasMorph ) , m_pDictMorph ( std::move (pDictMorph) ) { } void SetMap ( const DictMap_t &hDict ) { m_pDict = &hDict; } // these only got called actually SphWordID_t GetWordID ( BYTE * pWord ) final; SphWordID_t GetWordIDNonStemmed ( BYTE * pWord ) final { assert ( m_pDict ); return const_cast<DictMap_t *>(m_pDict)->GetTerm ( pWord ); } bool HasMorphology () const final { return m_bHasMorph; } void Setup ( const CSphDictSettings &tSettings ) final {} }; struct PQMatchContextResult_t { CSphVector<PercolateQueryDesc> m_dQueryMatched; CSphVector<int> m_dDocsMatched; CSphVector<int> m_dDt; int m_iDocsMatched = 0; int m_iEarlyPassed = 0; int m_iOnlyTerms = 0; int m_iQueriesFailed = 0; Warner_c m_dMsg; }; struct PercolateMatchContext_t : public PQMatchContextResult_t { bool m_bGetDocs = false; bool m_bGetQuery = false; bool m_bGetFilters = false; bool m_bVerbose = false; CSphRefcountedPtr<PercolateDictProxy_c> m_pDictMap; CSphQuery m_tDummyQuery; std::unique_ptr<CSphQueryContext> m_pCtx; std::unique_ptr<PercolateQwordSetup_c> m_pTermSetup; // const actually shared between all workers const ISphSchema &m_tSchema; const SegmentReject_t &m_tReject; const bool m_bUtf8 = false; int64_t m_iMaxStackSize = session::GetMaxStackSize(); PercolateMatchContext_t ( const RtSegment_t * pSeg, int iMaxCodepointLength, bool bHasMorph, DictRefPtr_c pDictMorph, const PercolateIndex_i * pIndex, const ISphSchema & tSchema, const SegmentReject_t & tReject, ESphHitless eHitless, bool bHasWideFields ) : m_pDictMap { new PercolateDictProxy_c ( bHasMorph, std::move (pDictMorph) ) } , m_tSchema ( tSchema ) , m_tReject ( tReject ) , m_bUtf8 ( iMaxCodepointLength>1 ) { m_tDummyQuery.m_eRanker = SPH_RANK_NONE; m_pCtx = std::make_unique<CSphQueryContext> ( m_tDummyQuery ); m_pCtx->m_bSkipQCache = true; // for lookups to work m_pCtx->m_pIndexData = pSeg; // setup search terms m_pTermSetup = std::make_unique<PercolateQwordSetup_c> ( pSeg, iMaxCodepointLength, eHitless ); m_pTermSetup->SetDict ( (DictRefPtr_c)m_pDictMap ); m_pTermSetup->m_pIndex = pIndex; m_pTermSetup->m_pCtx = m_pCtx.get (); m_pTermSetup->m_bHasWideFields = bHasWideFields; } }; void PercolateMergeResults ( const VecTraits_T<PQMatchContextResult_t *> &dMatches, PercolateMatchResult_t &tRes ); struct CPqResult : public iQueryResult { PercolateMatchResult_t m_dResult; CSphFixedVector<DocID_t> m_dDocids { 0 }; // check whether it necessary at all or not CPqResult () = default; CPqResult ( CPqResult &&rhs ) noexcept : m_dResult { std::move ( rhs.m_dResult ) } , m_dDocids { std::move ( rhs.m_dDocids ) } {} CPqResult &operator= ( CPqResult &&rhs ) noexcept { m_dResult = std::move ( rhs.m_dResult ); m_dDocids = std::move ( rhs.m_dDocids ); return *this; } void Reset () final { m_dResult.Reset (); m_dDocids.Reset ( 0 ); } bool HasWarnings () const final { return false; // Stub. fixme! } }; void MergePqResults ( const VecTraits_T<CPqResult *> &dChunks, CPqResult &dRes, bool bSparsed ); #endif //MANTICORE_SPHINXPQ_H
8,520
C++
.h
229
35.161572
179
0.745991
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,130
taskflushattrs.h
manticoresoftware_manticoresearch/src/taskflushattrs.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // /// @file taskflushattrs.h /// Task to check and flush modified attributes by demand and by timeout (if set) #pragma once #include "sphinxstd.h" // set from param `attr_flush_period`, see conf_options_reference/searchd_program_configuration_options.html void SetAttrFlushPeriod ( int64_t iPeriod ); // start periodical check and flush, if necessary void ScheduleFlushAttrs(); //! \brief Pefrorm bulk save attributes for all local indexes, one-by-one //! \returns true, if all indexes was saved. Called on shutdown (scheduler is already stopped there) bool FinallySaveIndexes (); /// Engages SaveIndexes task, and wait until it finished. int CommandFlush ();
1,140
C++
.h
24
46.25
108
0.769369
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,131
skip_cache.h
manticoresoftware_manticoresearch/src/skip_cache.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #pragma once #include "std/ints.h" #include "sphinxdefs.h" struct SkipCacheKey_t { int64_t m_iIndexId; SphWordID_t m_tWordId; }; struct SkipData_t; void InitSkipCache ( int64_t iCacheSize ); void ShutdownSkipCache(); namespace SkipCache { void DeleteAll ( int64_t iIndexId ); void Release ( SkipCacheKey_t tKey ); bool Find ( SkipCacheKey_t tKey, SkipData_t * & pData ); bool Add ( SkipCacheKey_t tKey, SkipData_t* pData ); }
913
C++
.h
29
30.103448
80
0.753129
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,132
task_info.h
manticoresoftware_manticoresearch/src/task_info.h
// // Copyright (c) 2021-2024, Manticore Software LTD (https://manticoresearch.com) // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #pragma once #include "sphinxstd.h" #include "threadutils.h" #include <optional> /* * Lowest info came from thread. It includes low details as thread name, thread ID and basic profile statistic. * * When a task engaged into thread, we also have details about the task, like connection id, proto, etc. * OR, for system task - the name of the action. * * Task may produce subtasks - like parallel processing rt chunks, and they also include details like current chunk N. * It may be any kind of different pieces of data, coming from different subtasks, and each need to be processed * different way, depends on the essence of the data itself. * * When task engaged, it fills its own TaskInfo structure with its essential data, and stores it in the * field m_pTaskInfo of thread descriptor LowThreadDesc_t. Previous value of that field stored in task's m_pNext field. * So, moving deep from task to task we finally have linked list of task infos, starting from one stored in Thread * and moving forward with m_pNext pointers. * * Each piece lives in own context (task) and owned by the task. * For displaying data (in show threads) we have 'public thread descriptor' with plain structure and fixed fields * Filling of that structure from low thread descriptor performed by GatherPublicThreadsInfo. It first copies low thread * attributes, and then walk over task info chains, collecting essential data. * * Each task info has TaskType flag, and provides function which publish essential data into public descriptor. * When unwinding task chain we look for the type and call saved function, if any. * If no 'displaying' func provided, we just skip to the next layer. * */ // snapshot of current thread and tasks, used in 'show threads', etc. and contains flat rendered info. struct PublicThreadDesc_t { int m_iThreadID = -1; ///< OS thread id std::optional<int64_t> m_tmStart; ///< when did the current request start? int64_t m_tmLastJobStartTimeUS = -1;///< time where I've done something useful int64_t m_tmLastJobDoneTimeUS = -1; ///< time where I've done something useful int64_t m_tmTotalWorkedTimeUS = -1; ///< total time I've worked on useful tasks int64_t m_tmTotalWorkedCPUTimeUS = -1; ///< total time I've worked on useful tasks int64_t m_iTotalJobsDone = -1; ///< total jobs I've completed CSphString m_sThreadName; StringBuilder_c m_sChain; StringBuilder_c m_sClientName {" "}; StringBuilder_c m_sDescription {" "}; StringBuilder_c m_sProto {","}; int m_iDescriptionLimit = -1; ///< cb flag when collecting info with columns=N, avoid copy huge descriptions then int64_t m_tmConnect = -1; ///< when did the client connect? std::unique_ptr<CSphQuery> m_pQuery; /// currently running query, if not sphinxql const char* m_szCommand = nullptr; /// simple static SYSTEM, SELECT, UPDATE, etc. Used in show threads, crash dumping int m_iConnID = -1; ///< current conn-id for this thread. For logging and tracking in mysql Proto_e m_eProto = Proto_e::UNKNOWN; /// used in show threads to format or not format query TaskState_e m_eTaskState = TaskState_e::UNKNOWN; /// show threads, crash dumping bool m_bKilled = false; /// informational about if session is killed. PublicThreadDesc_t() = default; void Swap (PublicThreadDesc_t& rhs); MOVE_BYSWAP ( PublicThreadDesc_t ) }; // flatten info from thread. iCols make hint for huge descriptions to avoid full copy PublicThreadDesc_t GatherPublicThreadInfo ( const Threads::LowThreadDesc_t * pSrc, int iCols ); // internal helpers // we don't expect all possible taskinfos being located in this file, // Instead, for each type of info you need to call RegisterRenderer and provide pointer to function which knows how to // fill PublicThreadDesc from given type. Byte returned by registrar is then became ID of that type of info, // and has to be written in m_eType field of each instance of such info using RenderFnPtr = void ( * ) ( const void * pSrc, PublicThreadDesc_t & dDst ); BYTE RegisterRenderer ( RenderFnPtr pFunc ) noexcept; // Declare static member func 'Render', and provide initial registration and storing type ID #define DECLARE_RENDER( TASKINFO ) \ static BYTE Task() { \ static BYTE eTask = RegisterRenderer ( TASKINFO::Render ); \ return eTask; \ } \ TASKINFO () noexcept { \ m_eType = Task(); \ } \ static void Render ( const void * pSrc, PublicThreadDesc_t & dDst ) // Define declared stuff (has to be written in .cpp to avoid multiple definitions) #define DEFINE_RENDER( TASKINFO ) \ void TASKINFO::Render ( const void * pSrc, PublicThreadDesc_t & dDst ) // generic task info struct TaskInfo_t { DECLARE_RENDER ( TaskInfo_t ); std::atomic<void *> m_pPrev { nullptr }; // link to previous (parent) chain. Hazard, NOT owned! BYTE m_eType; }; struct RefCount_t { static void Inc ( BYTE eType ); static void Dec ( BYTE eType ); }; struct NoRefCount_t { static void Inc ( BYTE ) {} static void Dec ( BYTE ) {} }; void GatherPublicTaskInfo ( PublicThreadDesc_t& dDesc, const std::atomic<void*>& pTask ); // RAII task info // Store info to TLS root, stores previous root to the chain // On dtr restores stored chain as root and retire info (uses hazard pointers) // if explicit root provided - uses it instead of TLS root. template<typename TASKINFO, typename REFCOUNT=RefCount_t> class ScopedInfo_T { protected: hazard::ScopedPtr_t<TASKINFO*> m_pInfo; public: explicit ScopedInfo_T ( TASKINFO* pInfo ) : m_pInfo ( pInfo ) { pInfo->m_pPrev = Threads::MyThd().m_pTaskInfo.exchange ( pInfo, std::memory_order_acq_rel ); REFCOUNT::Inc ( TASKINFO::Task() ); } explicit operator TASKINFO*() const noexcept { return m_pInfo.operator TASKINFO*(); }; TASKINFO* operator->() const noexcept { return m_pInfo.operator->(); } ScopedInfo_T ( ScopedInfo_T&& rhs ) = delete; ScopedInfo_T& operator= ( ScopedInfo_T&& rhs) = delete; ~ScopedInfo_T () { Threads::MyThd ().m_pTaskInfo.store ( m_pInfo->m_pPrev, std::memory_order_release ); REFCOUNT::Dec ( TASKINFO::Task() ); } }; // make provided task info (by typed, NOT generic! ptr) displayed in the thread. // when produced RAII obj come out of scope, info will be hidden and retired. template<typename TASKINFO> ScopedInfo_T<TASKINFO> PublishTaskInfo ( TASKINFO* pPtr ) { return ScopedInfo_T<TASKINFO> ( pPtr ); } // wide used task infos (declare them here to be accessed from anywhere, and also as examples) // system task - command and description struct MiniTaskInfo_t : public TaskInfo_t { DECLARE_RENDER( MiniTaskInfo_t ); void RenderWithoutChain ( PublicThreadDesc_t& dDst ); int64_t m_tmStart = sphMicroTimer (); int64_t m_tmLastJobStartTimeUS = -1; int64_t m_tmLastJobDoneTimeUS = -1; const char * m_szCommand = nullptr; // is always mt-safe since always set static const hazard::ScopedPtr_t<const CSphString *> m_pHazardDescription; int m_iDescriptionLen = 0; // len of string in m_pHazardDescription }; using ScopedMiniInfo_t = ScopedInfo_T<MiniTaskInfo_t>; using ScopedMiniInfoNoCount_t = ScopedInfo_T<MiniTaskInfo_t,NoRefCount_t>; // create and publish info about system task (what before did ThreadSystem_t) // command = 'SYSTEM', description = 'SYSTEM sDescription' ScopedMiniInfo_t PublishSystemInfo ( const char * sDescription ); namespace myinfo { // descriptions in m_pHazardDescription bigger than this limit will be retired as soon as possible static const int HazardDescriptionSizeLimit = 256*1024; // thread-local m_pTaskInfo available globally from any thread // it is hazard, since implicitly assume that I own this info and so, it will not be deleted by another thread TaskInfo_t * HazardTaskInfo (); // num of tasks with given type int Count ( BYTE eType ); // sum of all counters. Note, that might be quite useless, as one task may be 'decorated' by another int CountAll(); // first ptr to node with type eType TaskInfo_t * GetHazardTypedNode ( BYTE eType ); // bind current taskinfo content to handler Threads::Handler StickParent ( Threads::Handler fnHandler ); // bind current taskinfo and add new scoped mini info for coro handler Threads::Handler OwnMini ( Threads::Handler fnHandler ); // bind current taskinfo and add new scoped mini info for coro handler, without tracing N of mini // (for example, if you call it as subroutine in the same context and don't want to count it as separate task) Threads::Handler OwnMiniNoCount ( Threads::Handler fnHandler ); // first ptr to node of given type template <typename TASKINFO> TASKINFO* ref() { return (TASKINFO *) GetHazardTypedNode ( TASKINFO::Task() ); } // set MiniTaskInfo_t::m_sCommand void SetCommand ( const char * szCommand ); void SetCommandDone (); // set MiniTaskInfo_t::m_pHazardDescription. and refresh timer // iLen used to select retire policy (lazy, or immediate retire) void SetDescription ( CSphString sDescription, int iLen ); // set MiniTaskInfo_t::m_pHazardDescription and refresh timer void SetTaskInfo ( const char * sTemplate, ... ); // returns non-guarded ref to MiniTaskInfo_t::m_pHazardDescription (to be used in same scope as set functions) Str_t UnsafeDescription (); // expect that we own or live shorter than client info. So, called it 'hazard' because of it. template<typename FILTER> TaskInfo_t* HazardGetNode ( FILTER fnFilter ) { auto pSrc = (TaskInfo_t*)Threads::MyThd().m_pTaskInfo.load ( std::memory_order_relaxed ); for ( ; pSrc; pSrc = (TaskInfo_t*)pSrc->m_pPrev.load ( std::memory_order_relaxed ) ) if ( fnFilter ( pSrc ) ) break; return pSrc; } MiniTaskInfo_t* HazardGetMini(); } // namespace myinfo
10,156
C++
.h
202
48.183168
121
0.739174
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,133
sphinxfilter.h
manticoresoftware_manticoresearch/src/sphinxfilter.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #ifndef _sphinxfilter_ #define _sphinxfilter_ #include "columnarlib.h" #include "sphinx.h" class ISphFilter : public columnar::BlockTester_i { public: ISphFilter() = default; virtual void SetLocator ( const CSphAttrLocator & ) {} virtual void SetRange ( SphAttr_t, SphAttr_t ) {} virtual void SetRangeFloat ( float, float ) {} virtual void SetValues ( const VecTraits_T<SphAttr_t>& ) {} virtual void SetBlobStorage ( const BYTE * ) {} virtual void SetColumnar ( const columnar::Columnar_i * ) {} /// similar to EvalBlock w/pMinDocinfo and pMaxDocinfo, but for filter expressions /// their results are not stored into matches, so no docinfo here bool Test ( const columnar::MinMaxVec_t & dMinMax ) const override { // if filter does not implement block-level evaluation we assume the block will pass return true; } virtual void SetRefString ( const CSphString * , int ) {} virtual std::unique_ptr<ISphFilter> Optimize() { return std::unique_ptr<ISphFilter>(this); } /// evaluate filter for a given match /// returns true if match satisfies the filter critertia (i.e. in range, found in values list etc) virtual bool Eval ( const CSphMatch & tMatch ) const = 0; /// evaluate filter for a given block /// args are pMinDocinfo and pMaxDocinfo /// returns false if no document in block can possibly pass through the filter virtual bool EvalBlock ( const DWORD *, const DWORD * ) const { // if filter does not implement block-level evaluation we assume the block will pass return true; } /// returns true if the filter can handle exclude flag in settings /// otherwise a NOT filter will be spawned on top of this filter virtual bool CanExclude() const { return false; } virtual std::unique_ptr<ISphFilter> Join ( std::unique_ptr<ISphFilter> pFilter ); }; // fwd using UservarIntSetValues_c = CSphVector<SphAttr_t>; using UservarIntSet_c = SharedPtr_t<UservarIntSetValues_c>; class HistogramContainer_c; class SIContainer_c; struct CreateFilterContext_t { const VecTraits_T<CSphFilterSettings> * m_pFilters = nullptr; const VecTraits_T<FilterTreeItem_t> * m_pFilterTree = nullptr; const ISphSchema * m_pMatchSchema = nullptr; const ISphSchema * m_pIndexSchema = nullptr; const BYTE * m_pBlobPool = nullptr; const columnar::Columnar_i * m_pColumnar = nullptr; ESphCollation m_eCollation = SPH_COLLATION_DEFAULT; bool m_bScan = false; std::unique_ptr<ISphFilter> m_pFilter; std::unique_ptr<ISphFilter> m_pWeightFilter; CSphVector<UservarIntSet_c> m_dUserVals; const HistogramContainer_c * m_pHistograms = nullptr; const SIContainer_c * m_pSI = nullptr; int64_t m_iTotalDocs = 0; CSphString m_sJoinIdx; }; std::unique_ptr<ISphFilter> sphCreateFilter ( const CSphFilterSettings &tSettings, const CreateFilterContext_t &tCtx, CSphString &sError, CSphString &sWarning); std::unique_ptr<ISphFilter> sphCreateAggrFilter ( const CSphFilterSettings * pSettings, const CSphString & sAttrName, const ISphSchema & tSchema, CSphString & sError ); std::unique_ptr<ISphFilter> sphJoinFilters ( std::unique_ptr<ISphFilter>, std::unique_ptr<ISphFilter> ); bool sphCreateFilters ( CreateFilterContext_t & tCtx, CSphString & sError, CSphString & sWarning ); void FormatFilterQL ( const CSphFilterSettings & tFilter, StringBuilder_c & tBuf, int iCompactIN ); void FormatFiltersQL ( const VecTraits_T<CSphFilterSettings> & dFilters, const VecTraits_T<FilterTreeItem_t> & dFilterTree, StringBuilder_c & tBuf, int iCompactIN=5 ); void FixupFilterSettings ( const CSphFilterSettings & tSettings, ESphAttr eAttrType, CommonFilterSettings_t & tFixedSettings ); void OptimizeFilters ( CSphVector<CSphFilterSettings> & dFilters ); CSphString FilterType2Str ( ESphFilter eFilterType ); void SetFilterStackItemSize ( std::pair<int,int> ); int GetFilterStackItemSize(); int GetStartFilterStackItemSize(); // fwd template<bool HAS_EQUAL_MIN, bool HAS_EQUAL_MAX, bool OPEN_LEFT = false, bool OPEN_RIGHT = false, typename T = SphAttr_t> inline bool EvalRange ( T tValue, T tMin, T tMax ) { if_const ( OPEN_LEFT ) return HAS_EQUAL_MAX ? ( tValue<=tMax ) : ( tValue<tMax ); if_const ( OPEN_RIGHT ) return HAS_EQUAL_MIN ? ( tValue>=tMin ) : ( tValue>tMin ); auto bMinOk = HAS_EQUAL_MIN ? ( tValue>=tMin ) : ( tValue>tMin ); auto bMaxOk = HAS_EQUAL_MAX ? ( tValue<=tMax ) : ( tValue<tMax ); return bMinOk && bMaxOk; } template<typename T = SphAttr_t> inline bool EvalRange ( T tValue, const CommonFilterSettings_t & tFilter ) { T tMin, tMax; if ( tFilter.m_eType==SPH_FILTER_FLOATRANGE ) { tMin = (T)tFilter.m_fMinValue; tMax = (T)tFilter.m_fMaxValue; } else { tMin = (T)tFilter.m_iMinValue; tMax = (T)tFilter.m_iMaxValue; } if ( tFilter.m_bOpenLeft ) return tFilter.m_bHasEqualMax ? ( tValue<=tMax ) : ( tValue<tMax ); if ( tFilter.m_bOpenRight ) return tFilter.m_bHasEqualMin ? ( tValue>=tMin ) : ( tValue>tMin ); auto bMinOk = tFilter.m_bHasEqualMin ? ( tValue>=tMin ) : ( tValue>tMin ); auto bMaxOk = tFilter.m_bHasEqualMax ? ( tValue<=tMax ) : ( tValue<tMax ); return bMinOk && bMaxOk; } template<bool HAS_EQUAL_MIN, bool HAS_EQUAL_MAX, bool OPEN_LEFT = false, bool OPEN_RIGHT = false, typename T = SphAttr_t> inline bool EvalBlockRangeAny ( T tMin1, T tMax1, T tMin2, T tMax2 ) { if_const ( OPEN_LEFT ) return HAS_EQUAL_MAX ? ( tMin1<=tMax2 ) : ( tMin1<tMax2 ); if_const ( OPEN_RIGHT ) return HAS_EQUAL_MIN ? ( tMax1>=tMin2 ) : ( tMax1>tMin2 ); auto bMinOk = HAS_EQUAL_MIN ? ( tMin1<=tMax2 ) : ( tMin1<tMax2 ); auto bMaxOk = HAS_EQUAL_MAX ? ( tMax1>=tMin2 ) : ( tMax1>tMin2 ); return bMinOk && bMaxOk; } template < typename T > inline bool MvaEval_Any ( const VecTraits_T<T> & dMvas, const VecTraits_T<const SphAttr_t> & dFilters ) { if ( dMvas.IsEmpty() || dFilters.IsEmpty() ) return false; const T * L = dMvas.begin(); for ( const auto & tFilter : dFilters ) { const T * R = &dMvas.Last(); while ( L<=R ) { const T * pVal = L + (R - L) / 2; T iValue = sphUnalignedRead ( *pVal ); if ( tFilter > iValue ) L = pVal + 1; else if ( tFilter < iValue ) R = pVal - 1; else return true; } } return false; } template < typename T > inline bool MvaEval_All ( const VecTraits_T<T> & dMvas, const VecTraits_T<const SphAttr_t> & dFilters ) { if ( dMvas.IsEmpty() || dFilters.IsEmpty() ) return false; for ( const T & tValue : dMvas ) { const SphAttr_t iCheck = sphUnalignedRead(tValue); if ( !dFilters.BinarySearch(iCheck) ) return false; } return true; } template <typename T, bool HAS_EQUAL_MIN, bool HAS_EQUAL_MAX> inline bool MvaEval_RangeAny ( const T * pMva, int nValues, SphAttr_t m_iMinValue, SphAttr_t m_iMaxValue ) { if ( !pMva ) return false; const T * pEnd = pMva+nValues; const T * L = pMva; const T * R = pEnd - 1; while ( L<=R ) { const T * pVal = L + (R - L) / 2; T iMva = sphUnalignedRead ( *pVal ); if ( m_iMinValue>iMva ) L = pVal + 1; else if ( m_iMinValue<iMva ) R = pVal - 1; else return ( HAS_EQUAL_MIN || pVal+1<pEnd ); } if ( L==pEnd ) return false; T iMvaL = sphUnalignedRead ( *L ); if_const ( HAS_EQUAL_MAX ) return iMvaL<=m_iMaxValue; else return iMvaL<m_iMaxValue; } template<bool HAS_EQUAL_MIN, bool HAS_EQUAL_MAX, typename T = SphAttr_t> inline bool EvalBlockRangeAll ( T tMin1, T tMax1, T tMin2, T tMax2 ) { auto bMinOk = HAS_EQUAL_MIN ? ( tMin1>=tMin2 ) : ( tMin1>tMin2 ); auto bMaxOk = HAS_EQUAL_MAX ? ( tMax1<=tMax2 ) : ( tMax1<tMax2 ); return bMinOk && bMaxOk; } template <typename T, bool HAS_EQUAL_MIN, bool HAS_EQUAL_MAX> inline bool MvaEval_RangeAll ( const T * pMva, int nValues, SphAttr_t m_iMinValue, SphAttr_t m_iMaxValue ) { if ( !pMva ) return false; const T * L = pMva; const T * R = pMva+nValues-1; return EvalBlockRangeAll<HAS_EQUAL_MIN,HAS_EQUAL_MAX> ( *L, *R, (T)m_iMinValue, (T)m_iMaxValue ); } struct MvaEvalAll_c { template<typename T> static inline bool Eval ( const VecTraits_T<T> & dMvas, const VecTraits_T<SphAttr_t> & dFilters ) { return MvaEval_All ( dMvas, dFilters ); } template<typename T> static inline bool Eval ( const VecTraits_T<T> & dMvas, SphAttr_t tValue ) { for ( T tMVA : dMvas ) if ( tMVA!=tValue ) return false; return true; } template<typename T, bool HAS_EQUAL_MIN, bool HAS_EQUAL_MAX > static inline bool EvalRange ( const VecTraits_T<T> & dMvas, SphAttr_t tMin, SphAttr_t tMax ) { return MvaEval_RangeAll<T, HAS_EQUAL_MIN, HAS_EQUAL_MAX> ( dMvas.Begin(), dMvas.GetLength(), tMin, tMax ); } static inline bool EvalBlock ( const VecTraits_T<SphAttr_t> & dFilters, SphAttr_t tBlockMin, SphAttr_t tBlockMax ) { return dFilters.all_of ( [&]( const SphAttr_t & tFilter ) { return tFilter>=tBlockMin && tFilter<=tBlockMax; } ); } }; struct MvaEvalAny_c { template<typename T> static inline bool Eval ( const VecTraits_T<T> & dMvas, const VecTraits_T<const SphAttr_t> & dFilters ) { return MvaEval_Any ( dMvas, dFilters ); } template<typename T> static inline bool Eval ( const VecTraits_T<T> & dMvas, SphAttr_t tValue ) { return !!dMvas.BinarySearch((T)tValue); } template<typename T, bool HAS_EQUAL_MIN, bool HAS_EQUAL_MAX > static inline bool EvalRange ( const VecTraits_T<T> & dMvas, SphAttr_t tMin, SphAttr_t tMax ) { return MvaEval_RangeAny<T, HAS_EQUAL_MIN, HAS_EQUAL_MAX> ( dMvas.Begin(), dMvas.GetLength(), tMin, tMax ); } static inline bool EvalBlock ( const VecTraits_T<SphAttr_t> & dFilters, SphAttr_t tBlockMin, SphAttr_t tBlockMax ) { return dFilters.any_of ( [&]( const SphAttr_t & tFilter ) { return tFilter>=tBlockMin && tFilter<=tBlockMax; } ); } }; struct RowIdBoundaries_t { RowID_t m_tMinRowID = 0; RowID_t m_tMaxRowID = INVALID_ROWID; }; RowIdBoundaries_t GetFilterRowIdBoundaries ( const CSphFilterSettings & tFilter, RowID_t tTotalDocs ); bool FixupFilterSettings ( const CSphFilterSettings & tSettings, CommonFilterSettings_t & tFixedSettings, const CreateFilterContext_t & tCtx, const CSphString & sAttrName, CSphString & sError ); bool TransformFilters ( const CreateFilterContext_t & tCtx, CSphVector<CSphFilterSettings> & dModified, CSphVector<FilterTreeItem_t> & dModifiedTree, std::unique_ptr<ISphSchema> & pModifiedMatchSchema, const CSphVector<CSphQueryItem> & dItems, CSphString & sError ); int64_t EstimateFilterSelectivity ( const CSphFilterSettings & tSettings, const CreateFilterContext_t & tCtx ); #endif // _sphinxfilter_
10,910
C++
.h
266
38.796992
266
0.726172
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,134
geodist.h
manticoresoftware_manticoresearch/src/geodist.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #ifndef _geodist_ #define _geodist_ #include "sphinxstd.h" enum GeoFunc_e { GEO_HAVERSINE, GEO_ADAPTIVE }; typedef float (*Geofunc_fn)( float, float, float, float ); struct GeoDistSettings_t { Geofunc_fn m_pFunc = nullptr; float m_fScale = 1.0f; float m_fAnchorLat = 0.0f; float m_fAnchorLon = 0.0f; CSphString m_sAttrLat; CSphString m_sAttrLon; }; struct Poly2dBBox_t { float m_fMinX = 0.0f; float m_fMinY = 0.0f; float m_fMaxX = 0.0f; float m_fMaxY = 0.0f; int m_iNumPoints = 0; CSphString m_sAttrLat; CSphString m_sAttrLon; }; Geofunc_fn GetGeodistFn ( GeoFunc_e eFunc, bool bDeg ); float CalcGeodist ( GeoFunc_e eFunc, bool bDeg, float lat1, float lon1, float lat2, float lon2 ); bool GeodistGetSphereBBox ( Geofunc_fn fnFunc, float fLat, float fLon, float fDist, float & fLatMin, float & fLatMax, float & fLonMin, float & fLonMax ); /// init tables used by our geodistance functions void GeodistInit(); void GeoTesselate ( CSphVector<float> & dIn ); /// get geodist conversion coeff bool GeoDistanceUnit ( const char * szUnit, float & fCoeff ); #endif // _geodist_
1,585
C++
.h
48
31.5
154
0.738703
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,135
taskflushmutable.h
manticoresoftware_manticoresearch/src/taskflushmutable.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // /// @file taskflushmutable.h /// Task to check and flush mutable indexes (rt, precloate) when necessary or by timeout #pragma once #include "sphinxstd.h" constexpr int64_t DEFAULT_FLUSH_PERIOD = 10*3600*1000*1000ll; // reschedule in 10h in case planned flush failed // set from param `rt_flush_period`, see conf_options_reference/searchd_program_configuration_options.html void SetRtFlushPeriod ( int64_t iPeriod = DEFAULT_FLUSH_PERIOD ); void ShutdownFlushingMutable(); /* this cb attached to local indexes hash table 'add-or-replace' function. It is called for all new arrived indexes, * and if it suitable for flushing (i.e. if it exists and is mutable), engages flushing task by timer for it.*/ void HookSubscribeMutableFlush ( const CSphString& sName );
1,242
C++
.h
22
55.136364
116
0.771005
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,136
taskflushbinlog.h
manticoresoftware_manticoresearch/src/taskflushbinlog.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // /// @file taskflushbinlog.h /// Task to periodically check and flush rt binlog #pragma once void StartRtBinlogFlushing ();
601
C++
.h
15
38.933333
80
0.756849
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,137
taskping.h
manticoresoftware_manticoresearch/src/taskping.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // /// @file taskping.h /// Periodic ping of HA hosts /* * How async smart pinger works: * 1. We charge oneshot task to be run after host timestamp + g_iPingIntervalUs. * 2. On timeout engaged, the task is REMOVED from scheduler and performed. * 3. We check, whether the last host access timestamp is old enough to run the ping action. * (if nothing, but ping in game, it seems that first check will success. If other queries invokes the host * also, it very often means that timestamp is already refreshed, so, we not need to ping it). * 4a. If host is fresh enough (no need to ping) - go to pp 1. * 4b. If it is time to ping, we push the task to our async netloop with callback. Since networking is async, * we send the task from the same worker (no wait, no need to switch into another thread), and set custom * reporter with callback. * 5. On network callback - go to pp 1. * Removing the host is performed by set it's 'need_ping' flag to 0. The checker, noticing it, will not schedule * next check or perform network task, but just release the host and that's all. * */ #ifndef MANTICORE_TASKPING_H #define MANTICORE_TASKPING_H namespace Ping { void Start(); }; #endif //MANTICORE_TASKPING_H
1,698
C++
.h
34
48.323529
112
0.742461
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,138
match_impl.h
manticoresoftware_manticoresearch/src/match_impl.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #pragma once #include "conversion.h" #include "attribute.h" /// dtor. frees everything inline CSphMatch::~CSphMatch() { ResetDynamic(); } /// reset inline void CSphMatch::Reset ( int iDynamic ) { // check that we're either initializing a new one, or NOT changing the current size assert ( iDynamic >= 0 ); assert ( !m_pDynamic || iDynamic == (int)m_pDynamic[-1] ); m_tRowID = INVALID_ROWID; if ( !m_pDynamic && iDynamic ) { #ifndef NDEBUG m_pDynamic = new CSphRowitem[iDynamic + 1]; *m_pDynamic++ = iDynamic; #else m_pDynamic = new CSphRowitem[iDynamic]; #endif // dynamic stuff might contain pointers now (STRINGPTR type) // so we gotta cleanup memset ( m_pDynamic, 0, iDynamic * sizeof ( CSphRowitem ) ); } } // if mem region reinterpreted as match - ensure d-tr will not do sad things as delete garbaged m_pDynamic inline void CSphMatch::CleanGarbage() { m_pDynamic = nullptr; } inline void CSphMatch::ResetDynamic() { #ifndef NDEBUG if ( m_pDynamic ) --m_pDynamic; #endif SafeDeleteArray ( m_pDynamic ); } /// assignment inline void CSphMatch::Combine ( const CSphMatch& rhs, int iDynamic ) { // check that we're either initializing a new one, or NOT changing the current size assert ( iDynamic >= 0 ); assert ( !m_pDynamic || iDynamic == (int)m_pDynamic[-1] ); if ( this != &rhs ) { m_tRowID = rhs.m_tRowID; m_iWeight = rhs.m_iWeight; m_pStatic = rhs.m_pStatic; m_iTag = rhs.m_iTag; } if ( iDynamic ) { if ( !m_pDynamic ) { #ifndef NDEBUG m_pDynamic = new CSphRowitem[iDynamic + 1]; *m_pDynamic++ = iDynamic; #else m_pDynamic = new CSphRowitem[iDynamic]; #endif } if ( this != &rhs ) { assert ( rhs.m_pDynamic ); assert ( m_pDynamic[-1] == rhs.m_pDynamic[-1] ); // ensure we're not changing X to Y memcpy ( m_pDynamic, rhs.m_pDynamic, iDynamic * sizeof ( CSphRowitem ) ); } } } /// integer getter FORCE_INLINE SphAttr_t CSphMatch::GetAttr ( const CSphAttrLocator& tLoc ) const { // m_pRowpart[tLoc.m_bDynamic] is 30% faster on MSVC 2005 // same time on gcc 4.x though, ~1 msec per 1M calls, so lets avoid the hassle for now if ( tLoc.m_iBitOffset >= 0 ) return sphGetRowAttr ( tLoc.m_bDynamic ? m_pDynamic : m_pStatic, tLoc ); assert ( false && "Unknown negative-bitoffset locator" ); return 0; } /// integer setter FORCE_INLINE void CSphMatch::SetAttr ( const CSphAttrLocator& tLoc, SphAttr_t uValue ) const { assert ( tLoc.m_bDynamic ); assert ( tLoc.GetMaxRowitem() < (int)m_pDynamic[-1] ); sphSetRowAttr ( m_pDynamic, tLoc, uValue ); } FORCE_INLINE SphAttr_t ExchangeAttr ( const CSphMatch& tMatch, const CSphAttrLocator& tLoc, SphAttr_t uNewValue ) { auto uOldValue = tMatch.GetAttr ( tLoc ); tMatch.SetAttr ( tLoc, uNewValue ); return uOldValue; } /// add scalar value to attribute inline void CSphMatch::AddCounterScalar ( const CSphAttrLocator& tLoc, SphAttr_t uValue ) const { assert ( tLoc.m_bDynamic ); assert ( tLoc.GetMaxRowitem() < (int)m_pDynamic[-1] ); sphAddCounterScalar ( m_pDynamic, tLoc, uValue ); } /// add same-located value from another match inline void CSphMatch::AddCounterAttr ( const CSphAttrLocator& tLoc, const CSphMatch& tValue ) const { assert ( tLoc.m_bDynamic ); assert ( tLoc.GetMaxRowitem() < (int)m_pDynamic[-1] ); sphAddCounterAttr ( m_pDynamic, tLoc.m_bDynamic ? tValue.m_pDynamic : tValue.m_pStatic, tLoc ); } inline float CSphMatch::GetAttrFloat ( const CSphAttrLocator& tLoc ) const { return sphDW2F ( (DWORD)sphGetRowAttr ( tLoc.m_bDynamic ? m_pDynamic : m_pStatic, tLoc ) ); } inline double CSphMatch::GetAttrDouble ( const CSphAttrLocator & tLoc ) const { return sphQW2D ( sphGetRowAttr ( tLoc.m_bDynamic ? m_pDynamic : m_pStatic, tLoc ) ); } inline void CSphMatch::SetAttrFloat ( const CSphAttrLocator& tLoc, float fValue ) const { assert ( tLoc.m_bDynamic ); assert ( tLoc.GetMaxRowitem() < (int)m_pDynamic[-1] ); sphSetRowAttr ( m_pDynamic, tLoc, sphF2DW ( fValue ) ); } inline void CSphMatch::SetAttrDouble ( const CSphAttrLocator & tLoc, double fValue ) const { assert ( tLoc.m_bDynamic ); assert ( tLoc.GetMaxRowitem() < (int)m_pDynamic[-1] ); sphSetRowAttr ( m_pDynamic, tLoc, sphD2QW ( fValue ) ); } /// fetches blobs from both data ptr attrs and pooled blob attrs inline ByteBlob_t CSphMatch::FetchAttrData ( const CSphAttrLocator& tLoc, const BYTE* pPool ) const { if ( tLoc.IsBlobAttr() ) return sphGetBlobAttr ( *this, tLoc, pPool ); return sphUnpackPtrAttr ( (const BYTE*)GetAttr ( tLoc ) ); } /// specialized swapper inline void Swap ( CSphMatch& a, CSphMatch& b ) { if ( &a == &b ) return; Swap ( a.m_tRowID, b.m_tRowID ); Swap ( a.m_pStatic, b.m_pStatic ); Swap ( a.m_pDynamic, b.m_pDynamic ); Swap ( a.m_iWeight, b.m_iWeight ); Swap ( a.m_iTag, b.m_iTag ); }
5,240
C++
.h
159
31.09434
113
0.717705
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,139
distinct.h
manticoresoftware_manticoresearch/src/distinct.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #ifndef _distinct_ #define _distinct_ #include "grouper.h" #include "std/openhash.h" #include "hyperloglog.h" struct ValueWithCount_t { SphAttr_t m_tValue; int m_iCount; inline bool operator < ( const ValueWithCount_t & rhs ) const { if ( m_tValue != rhs.m_tValue ) return m_tValue < rhs.m_tValue; return m_iCount > rhs.m_iCount; } inline bool operator== ( const ValueWithCount_t & rhs ) const { return m_tValue == rhs.m_tValue; } }; struct ValueWithGroup_t { public: SphGroupKey_t m_tGroup; SphAttr_t m_tValue; inline bool operator < ( const ValueWithGroup_t & rhs ) const { if ( m_tGroup!=rhs.m_tGroup ) return m_tGroup<rhs.m_tGroup; return m_tValue<rhs.m_tValue; } inline bool operator == ( const ValueWithGroup_t & rhs ) const { return m_tGroup==rhs.m_tGroup && m_tValue==rhs.m_tValue; } }; struct ValueWithGroupCount_t { public: SphGroupKey_t m_tGroup; SphAttr_t m_tValue; int m_iCount; ValueWithGroupCount_t () = default; ValueWithGroupCount_t ( SphGroupKey_t uGroup, SphAttr_t uValue, int iCount ) : m_tGroup ( uGroup ) , m_tValue ( uValue ) , m_iCount ( iCount ) {} inline bool operator < ( const ValueWithGroupCount_t & rhs ) const { if ( m_tGroup!=rhs.m_tGroup ) return m_tGroup<rhs.m_tGroup; if ( m_tValue!=rhs.m_tValue ) return m_tValue<rhs.m_tValue; return m_iCount>rhs.m_iCount; } inline bool operator == ( const ValueWithGroupCount_t & rhs ) const { return m_tGroup==rhs.m_tGroup && m_tValue==rhs.m_tValue; } }; template <typename T> class UniqGrouped_T : public CSphVector<T> { using BASE = CSphVector<T>; public: UniqGrouped_T () { BASE::Reserve ( 16384 ); } void Add ( const ValueWithGroupCount_t & tValue ); void Sort(); int CountStart ( SphGroupKey_t & tOutGroup ); ///< starting counting distinct values, returns count and group key (0 if empty) int CountNext ( SphGroupKey_t & tOutGroup ); ///< continues counting distinct values, returns count and group key (0 if done) void Compact ( VecTraits_T<SphGroupKey_t> & dRemoveGroups ); void CopyTo (UniqGrouped_T & dRhs ) const; void Reset() { BASE::Resize(0); } void SetAccuracy ( int iAccuracy ) {} protected: int m_iCountPos = 0; bool m_bSorted = true; }; template <typename T> inline void UniqGrouped_T<T>::Add ( const ValueWithGroupCount_t & tValue ) { BASE::Add ( { tValue.m_tGroup, tValue.m_tValue } ); m_bSorted = false; } template <> inline void UniqGrouped_T<ValueWithGroupCount_t>::Add ( const ValueWithGroupCount_t & tValue ) { BASE::Add ( tValue ); m_bSorted = false; } template <typename T> void UniqGrouped_T<T>::Sort() { if ( m_bSorted ) return; BASE::Sort(); m_bSorted = true; } template <typename T> int UniqGrouped_T<T>::CountStart ( SphGroupKey_t & tOutGroup ) { m_iCountPos = 0; return CountNext ( tOutGroup ); } template <typename T> int UniqGrouped_T<T>::CountNext ( SphGroupKey_t & tOutGroup ) { assert ( m_bSorted ); if ( m_iCountPos>=BASE::GetLength() ) return 0; constexpr bool bNeedCount = std::is_same<T, ValueWithGroupCount_t>::value; auto tGroup = BASE::m_pData[m_iCountPos].m_tGroup; auto tValue = BASE::m_pData[m_iCountPos].m_tValue; int iCount = 1; if constexpr ( bNeedCount ) iCount = BASE::m_pData[m_iCountPos].m_iCount; tOutGroup = tGroup; m_iCountPos++; while ( m_iCountPos<BASE::GetLength() && BASE::m_pData[m_iCountPos].m_tGroup==tGroup ) { if constexpr ( bNeedCount ) { // if we have similar values in both groups, we can safely assume that we have at least one duplicate int iAdd = BASE::m_pData[m_iCountPos].m_iCount; assert ( iAdd>0 ); if ( BASE::m_pData[m_iCountPos].m_tValue==tValue ) iAdd--; iCount += iAdd; } else { if ( BASE::m_pData[m_iCountPos].m_tValue!=tValue ) iCount++; } tValue = BASE::m_pData[m_iCountPos].m_tValue; ++m_iCountPos; } return iCount; } // works like 'uniq', and also throw away provided values to remove. template <typename T> void UniqGrouped_T<T>::Compact ( VecTraits_T<SphGroupKey_t>& dRemoveGroups ) { assert ( m_bSorted ); if ( !BASE::GetLength() ) return; dRemoveGroups.Sort(); auto * pRemoveGroups = dRemoveGroups.begin (); auto iRemoveGroups = dRemoveGroups.GetLength (); auto pSrc = BASE::Begin(); auto pDst = BASE::Begin(); auto pEnd = BASE::End(); // skip remove-groups which are not in my list while ( iRemoveGroups && (*pRemoveGroups)<pSrc->m_tGroup ) { ++pRemoveGroups; --iRemoveGroups; } for ( ; pSrc<pEnd; ++pSrc ) { // check if this entry needs to be removed while ( iRemoveGroups && (*pRemoveGroups)<pSrc->m_tGroup ) { ++pRemoveGroups; --iRemoveGroups; } if ( iRemoveGroups && pSrc->m_tGroup==*pRemoveGroups ) continue; // check if it's a dupe if ( pDst>BASE::Begin() && pDst[-1]==pSrc[0] ) continue; *pDst++ = *pSrc; } assert ( pDst-BASE::Begin()<=BASE::GetLength() ); BASE::m_iCount = pDst-BASE::Begin(); } template <typename T> void UniqGrouped_T<T>::CopyTo ( UniqGrouped_T & dRhs ) const { if ( m_bSorted && dRhs.m_bSorted ) { UniqGrouped_T dRes; dRes.MergeSorted ( dRhs, *this ); dRes.m_bSorted = true; dRhs = std::move(dRes); } else { auto * pNewValues = dRhs.AddN ( BASE::GetLength() ); memcpy ( pNewValues, BASE::Begin(), BASE::GetLengthBytes64() ); dRhs.m_bSorted = false; } } ///////////////////////////////////////////////////////////////////// template <typename T> class UniqSingle_T : public CSphVector<T> { using BASE = CSphVector<T>; public: UniqSingle_T() { BASE::Reserve ( 16384 ); } void Add ( const ValueWithGroupCount_t & tValue ); void Sort(); void Compact(); void CopyTo ( UniqSingle_T & dRhs ) const; void Reset() { BASE::Resize(0); } int CountDistinct(); protected: bool m_bSorted = true; }; template <typename T> inline void UniqSingle_T<T>::Add ( const ValueWithGroupCount_t & tValue ) { BASE::Add ( tValue.m_tValue ); m_bSorted = false; } template <> inline void UniqSingle_T<ValueWithCount_t>::Add ( const ValueWithGroupCount_t & tValue ) { BASE::Add ( { tValue.m_tValue, tValue.m_iCount } ); m_bSorted = false; } template <typename T> void UniqSingle_T<T>::Sort() { if ( m_bSorted ) return; BASE::Sort(); m_bSorted = true; } template <typename T> void UniqSingle_T<T>::Compact() { BASE::Uniq ( !m_bSorted ); m_bSorted = true; } template <typename T> void UniqSingle_T<T>::CopyTo ( UniqSingle_T & dRhs ) const { if ( m_bSorted && dRhs.m_bSorted ) { UniqSingle_T dRes; dRes.MergeSorted ( dRhs, *this ); dRes.m_bSorted = true; dRhs = std::move(dRes); } else { auto * pNewValues = dRhs.AddN ( BASE::GetLength() ); memcpy ( pNewValues, BASE::Begin(), BASE::GetLengthBytes64() ); dRhs.m_bSorted = false; } } template <typename T> int UniqSingle_T<T>::CountDistinct() { constexpr bool bNeedCount = std::is_same<T, ValueWithCount_t>::value; Sort(); auto & dArray = *this; int iCount = 1; if constexpr ( bNeedCount ) iCount = dArray[0].m_iCount; for ( int i = 1, iLen = BASE::GetLength (); i<iLen; ++i ) { if constexpr ( bNeedCount ) { // if we have similar values in both groups, we can safely assume that we have at least one duplicate int iAdd = dArray[i].m_iCount; assert ( iAdd>0 ); if ( dArray[i-1]==dArray[i] ) iAdd--; iCount += iAdd; } else { if ( dArray[i-1]!=dArray[i] ) iCount++; } } return iCount; } class UniqHLLTraits_c { public: UniqHLLTraits_c(); ~UniqHLLTraits_c() { Reset(); } UniqHLLTraits_c & operator = ( UniqHLLTraits_c && tRhs ); void Reset(); void SetAccuracy ( int iAccuracy ); protected: static const int SMALL_ARRAY_SIZE = 16; static const int MIN_HASH_SIZE = 64; static const int NON_PACKED_HLL_THRESH = 16; using HLLDensePacked_c = HyperLogLogDense_T<>; using HLLDenseNonPacked_c = HyperLogLogDense_T<uint64_t, FarmHash_T<uint64_t>, RegistersNonPacked_c>; using SmallArray_c = LazyVector_T<SphAttr_t, sph::DefaultRelimit, SMALL_ARRAY_SIZE>; using Hash_c = OpenHashSetFastClear_T<SphAttr_t>; enum class ContainterType_e { ARRAY, HASH, HLL_DENSE_PACKED, HLL_DENSE_NONPACKED, }; struct Container_t { union { SmallArray_c * m_pArray = nullptr; Hash_c * m_pHash; HLLDensePacked_c * m_pHLLDensePacked; HLLDenseNonPacked_c * m_pHLLDenseNonPacked; }; ContainterType_e m_eType = ContainterType_e::ARRAY; int m_iHashIdx = 0; Container_t() = default; Container_t ( const Container_t & tRhs ); Container_t & operator = ( Container_t && tRhs ); Container_t & operator = ( const Container_t & tRhs ); int Estimate() const; void Reset(); bool IsEmpty() const; FORCE_INLINE bool FindInArray ( SphAttr_t tValue ) { assert ( m_eType==ContainterType_e::ARRAY ); for ( auto i : *m_pArray ) if ( i==tValue ) return true; return false; } }; int m_iAccuracy = 16; void AddToContainer ( Container_t & tContainer, SphAttr_t tValue ); FORCE_INLINE SmallArray_c * AllocateArray() { if ( m_dUnusedArray.GetLength() ) { SmallArray_c * pNew = m_dUnusedArray.Pop(); pNew->Resize(0); return pNew; } return new SmallArray_c; } FORCE_INLINE void FreeContainer ( Container_t & tContainer ) { switch ( tContainer.m_eType ) { case ContainterType_e::ARRAY: m_dUnusedArray.Add ( tContainer.m_pArray ); break; case ContainterType_e::HASH: m_dUnusedHashes[tContainer.m_iHashIdx].Add ( tContainer.m_pHash ); break; case ContainterType_e::HLL_DENSE_PACKED: m_dUnusedHLLDensePacked.Add ( tContainer.m_pHLLDensePacked ); break; case ContainterType_e::HLL_DENSE_NONPACKED: m_dUnusedHLLDenseNonPacked.Add ( tContainer.m_pHLLDenseNonPacked ); break; default: assert ( 0 && "Unknown container type" ); break; } tContainer.m_pArray = nullptr; } void ConvertToHash ( Container_t & tContainer ); void ConvertToHLLDensePacked ( Container_t & tContainer ); void ConvertToHLLDenseNonPacked ( Container_t & tContainer ); private: CSphVector<SmallArray_c *> m_dUnusedArray; CSphVector<CSphVector<Hash_c *>> m_dUnusedHashes; CSphVector<HLLDensePacked_c *> m_dUnusedHLLDensePacked; CSphVector<HLLDenseNonPacked_c *> m_dUnusedHLLDenseNonPacked; int m_iMaxHashSize = 0; HLLDensePacked_c * AllocateHLLDensePacked(); HLLDenseNonPacked_c * AllocateHLLDenseNonPacked(); Hash_c * AllocateHash ( int iIdx ); void MoveToLargerHash ( Container_t & tContainer ); template <typename T> friend void CopyContainerTo ( SphGroupKey_t tGroup, const UniqHLLTraits_c::Container_t & tFrom, T & tRhs ); }; class UniqHLL_c : public UniqHLLTraits_c { using BASE = UniqHLLTraits_c; public: ~UniqHLL_c() { Reset(); } UniqHLL_c & operator = ( UniqHLL_c && tRhs ); FORCE_INLINE void Add ( const ValueWithGroupCount_t & tValue ); void Sort() {} int CountStart ( SphGroupKey_t & tOutGroup ); int CountNext ( SphGroupKey_t & tOutGroup ); void Compact ( VecTraits_T<SphGroupKey_t>& dRemoveGroups ); void Reset(); void CopyTo ( UniqHLL_c & tRhs ) const; Container_t & Get ( SphGroupKey_t tGroup ); private: OpenHashTable_T<SphGroupKey_t, Container_t> m_hGroups; int64_t m_iHashIterator = 0; }; void UniqHLL_c::Add ( const ValueWithGroupCount_t & tValue ) { Container_t * pContainer = m_hGroups.Find ( tValue.m_tGroup ); if ( pContainer ) AddToContainer ( *pContainer, tValue.m_tValue ); else { Container_t tContainer; tContainer.m_pArray = AllocateArray(); tContainer.m_pArray->Add ( tValue.m_tValue ); m_hGroups.Add ( tValue.m_tGroup, tContainer ); } } class UniqHLLSingle_c : public UniqHLLTraits_c { using BASE = UniqHLLTraits_c; public: UniqHLLSingle_c() { m_tContainer.m_pArray = AllocateArray(); } ~UniqHLLSingle_c() { Reset(); } UniqHLLSingle_c & operator = ( UniqHLLSingle_c && tRhs ); inline void Add ( const ValueWithGroupCount_t & tValue ) { AddToContainer ( m_tContainer, tValue.m_tValue ); } void Compact() {} int CountDistinct() { return m_tContainer.Estimate(); } void CopyTo ( UniqHLLSingle_c & tRhs ) const; void Reset(); Container_t & Get ( SphGroupKey_t tGroup ) { return m_tContainer; } private: Container_t m_tContainer; }; #endif // _distinct_
12,686
C++
.h
427
27.28103
130
0.697139
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,140
pseudosharding.h
manticoresoftware_manticoresearch/src/pseudosharding.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #pragma once #include "sphinxstd.h" struct SplitData_t { int64_t m_iMetric = 0; int m_iThreadCap = 0; }; void DistributeThreadsOverIndexes ( IntVec_t & dThreads, const CSphVector<SplitData_t> & dSplitData, int iConcurrency ); int CalcMaxThreadsPerIndex ( int iConcurrency, int iNumIndexes );
776
C++
.h
20
37.5
120
0.760638
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,141
exprtraits.h
manticoresoftware_manticoresearch/src/exprtraits.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #ifndef _exprtraits_ #define _exprtraits_ #include "sphinxexpr.h" #include "sphinxfilter.h" #include "conversion.h" #include "match.h" #if _WIN32 && !defined(__clang__) #ifndef NDEBUG #define EXPR_CLASS_NAME(name) \ {\ const char * szFuncName = __FUNCTION__; \ const char * szClassNameEnd = strstr ( szFuncName, "::" ); \ assert ( szClassNameEnd ); \ const char * szTemplateNameEnd = strstr ( szFuncName, "<" ); \ if ( szTemplateNameEnd ) szClassNameEnd = szTemplateNameEnd; \ size_t iLen = szClassNameEnd-szFuncName; \ assert ( strlen(name)==iLen && "Wrong expression name specified in ::GetHash" ); \ assert ( !strncmp(name, szFuncName, iLen) && "Wrong expression name specified in ::GetHash" ); \ }\ const char * szClassName = name; \ uint64_t uHash = uPrevHash; #else #define EXPR_CLASS_NAME(name) \ const char * szClassName = name; \ uint64_t uHash = uPrevHash; #endif #else #define EXPR_CLASS_NAME(name) \ const char * szClassName = name; \ uint64_t uHash = uPrevHash; #endif #define EXPR_CLASS_NAME_NOCHECK(name) \ const char * szClassName = name; \ uint64_t uHash = uPrevHash; #define CALC_DEP_HASHES() sphCalcExprDepHash ( szClassName, this, tSorterSchema, uHash, bDisable ); #define CALC_DEP_HASHES_EX(hash) sphCalcExprDepHash ( szClassName, this, tSorterSchema, uHash^hash, bDisable ); #define CALC_PARENT_HASH() CalcHash ( szClassName, tSorterSchema, uHash, bDisable ); #define CALC_PARENT_HASH_EX(hash) CalcHash ( szClassName, tSorterSchema, uHash^hash, bDisable ); #define CALC_POD_HASH(value) uHash = sphFNV64 ( &value, sizeof(value), uHash ); #define CALC_POD_HASHES(values) uHash = sphFNV64 ( values.Begin(), values.GetLength()*sizeof(values[0]), uHash ); #define CALC_STR_HASH(str,len) uHash = sphFNV64 ( str.cstr(), len, uHash ); #define CALC_CHILD_HASH(child) if (child) uHash = child->GetHash ( tSorterSchema, uHash, bDisable ); #define CALC_CHILD_HASHES(children) ARRAY_FOREACH ( i, children ) if (children[i]) uHash = children[i]->GetHash ( tSorterSchema, uHash, bDisable ); bool IsNumeric ( ESphAttr eType ); // check whether the type is numeric ESphAttr GetIntType ( int64_t iValue ); // check for type based on int value ESphAttr WidestType ( ESphAttr a, ESphAttr b ); // get the widest numeric type of the two uint64_t sphCalcLocatorHash ( const CSphAttrLocator & tLoc, uint64_t uPrevHash ); uint64_t sphCalcExprDepHash ( const char * szTag, ISphExpr * pExpr, const ISphSchema & tSorterSchema, uint64_t uPrevHash, bool & bDisable ); uint64_t sphCalcExprDepHash ( ISphExpr * pExpr, const ISphSchema & tSorterSchema, uint64_t uPrevHash, bool & bDisable ); int GetConstStrOffset ( int64_t iValue ); int GetConstStrLength ( int64_t iValue ); /// list of constants class ConstList_c { public: CSphVector<int64_t> m_dInts; ///< dword/int64 storage CSphVector<float> m_dFloats; ///< float storage ESphAttr m_eRetType { SPH_ATTR_INTEGER }; ///< SPH_ATTR_INTEGER, SPH_ATTR_BIGINT, SPH_ATTR_STRING, or SPH_ATTR_FLOAT Str_t m_sExpr; ///< pointer to original whole expr. Not owned. bool m_bPackedStrings = false; // packed string are offset:len from m_dInts over m_sExpr void Add ( int64_t iValue ); void Add ( float fValue ); }; /// arg-vs-set function (currently, IN or INTERVAL) evaluator traits template < typename T > class Expr_ArgVsSet_T : public ISphExpr { public: explicit Expr_ArgVsSet_T ( ISphExpr * pArg ) : m_pArg ( pArg ) { SafeAddRef ( pArg ); } float Eval ( const CSphMatch & tMatch ) const override { return (float) IntEval ( tMatch ); } int64_t Int64Eval ( const CSphMatch & tMatch ) const override { return IntEval ( tMatch ); } void FixupLocator ( const ISphSchema * pOldSchema, const ISphSchema * pNewSchema ) override { if ( m_pArg ) m_pArg->FixupLocator ( pOldSchema, pNewSchema ); } void Command ( ESphExprCommand eCmd, void * pArg ) override { if ( m_pArg ) m_pArg->Command ( eCmd, pArg ); } protected: CSphRefcountedPtr<ISphExpr> m_pArg; /* { nullptr }; */ Expr_ArgVsSet_T ( const Expr_ArgVsSet_T & rhs ) : m_pArg ( SafeClone ( rhs.m_pArg ) ) {} T ExprEval ( ISphExpr * pArg, const CSphMatch & tMatch ) const; uint64_t CalcHash ( const char * szTag, const ISphSchema & tSorterSchema, uint64_t uPrevHash, bool & bDisable ) { EXPR_CLASS_NAME_NOCHECK(szTag); CALC_CHILD_HASH(m_pArg); return CALC_DEP_HASHES(); } }; template<> inline int Expr_ArgVsSet_T<int>::ExprEval ( ISphExpr * pArg, const CSphMatch & tMatch ) const { return pArg->IntEval ( tMatch ); } template<> inline DWORD Expr_ArgVsSet_T<DWORD>::ExprEval ( ISphExpr * pArg, const CSphMatch & tMatch ) const { return (DWORD)pArg->IntEval ( tMatch ); } template<> inline float Expr_ArgVsSet_T<float>::ExprEval ( ISphExpr * pArg, const CSphMatch & tMatch ) const { return pArg->Eval ( tMatch ); } template<> inline int64_t Expr_ArgVsSet_T<int64_t>::ExprEval ( ISphExpr * pArg, const CSphMatch & tMatch ) const { return pArg->Int64Eval ( tMatch ); } /// arg-vs-constant-set template < typename T > class Expr_ArgVsConstSet_T : public Expr_ArgVsSet_T<T> { public: /// pre-evaluate and dismiss turn points Expr_ArgVsConstSet_T ( ISphExpr * pArg, const CSphVector<ISphExpr *> & dArgs, int iSkip ) : Expr_ArgVsSet_T<T> ( pArg ) , m_bFloat ( false ) { CSphMatch tDummy; for ( int i=iSkip; i<dArgs.GetLength(); ++i ) m_dValues.Add ( Expr_ArgVsSet_T<T>::ExprEval ( dArgs[i], tDummy ) ); CalcValueHash(); } /// copy that constlist Expr_ArgVsConstSet_T ( ISphExpr * pArg, ConstList_c * pConsts, bool bKeepFloat ) : Expr_ArgVsSet_T<T> ( pArg ) , m_bFloat ( false ) { assert ( pConsts ); if ( pConsts->m_eRetType==SPH_ATTR_FLOAT ) { m_dValues.Reserve ( pConsts->m_dFloats.GetLength() ); if ( !bKeepFloat ) { for ( float fV : pConsts->m_dFloats ) m_dValues.Add ( (T)fV ); } else { m_bFloat = true; for ( float fV : pConsts->m_dFloats ) m_dValues.Add ( (T) sphF2DW ( fV ) ); } } else { m_dValues.Reserve ( pConsts->m_dInts.GetLength() ); for ( auto iV : pConsts->m_dInts ) m_dValues.Add ( (T)iV ); } CalcValueHash(); } /// copy that uservar Expr_ArgVsConstSet_T ( ISphExpr * pArg, const UservarIntSet_c & pUservar ) : Expr_ArgVsSet_T<T> ( pArg ) , m_bFloat ( false ) { assert ( pUservar ); m_dValues.Reserve ( pUservar->GetLength() ); for ( auto iV : *pUservar ) m_dValues.Add ( (T)iV ); CalcValueHash(); } Expr_ArgVsConstSet_T ( ISphExpr * pArg ) : Expr_ArgVsSet_T<T> ( pArg ) , m_bFloat ( false ) { } uint64_t GetHash ( const ISphSchema & tSorterSchema, uint64_t uPrevHash, bool & bDisable ) override { EXPR_CLASS_NAME("Expr_ArgVsConstSet_T"); return CALC_PARENT_HASH(); } protected: CSphVector<T> m_dValues; uint64_t m_uValueHash=0; bool m_bFloat = false; Expr_ArgVsConstSet_T ( const Expr_ArgVsConstSet_T & rhs ) : Expr_ArgVsSet_T<T> ( rhs ) , m_dValues ( rhs.m_dValues ) , m_uValueHash ( rhs.m_uValueHash ) , m_bFloat ( rhs.m_bFloat ) {} void CalcValueHash() { ARRAY_FOREACH ( i, m_dValues ) m_uValueHash = sphFNV64 ( &m_dValues[i], sizeof(m_dValues[i]), i ? m_uValueHash : SPH_FNV64_SEED ); } uint64_t CalcHash ( const char * szTag, const ISphSchema & tSorterSchema, uint64_t uPrevHash, bool & bDisable ) { return Expr_ArgVsSet_T<T>::CalcHash ( szTag, tSorterSchema, uPrevHash^m_uValueHash, bDisable ); } }; class Expr_Unary_c : public ISphExpr { public: Expr_Unary_c ( const char * szClassName, ISphExpr * pFirst ); void FixupLocator ( const ISphSchema * pOldSchema, const ISphSchema * pNewSchema ) override; void Command ( ESphExprCommand eCmd, void * pArg ) override; uint64_t GetHash ( const ISphSchema & tSorterSchema, uint64_t uPrevHash, bool & bDisable ) override; protected: CSphRefcountedPtr<ISphExpr> m_pFirst; Expr_Unary_c ( const Expr_Unary_c & rhs ); private: const char * m_szExprName = nullptr; }; class Expr_Binary_c : public ISphExpr { public: Expr_Binary_c ( const char * szClassName, ISphExpr * pFirst, ISphExpr * pSecond ); void FixupLocator ( const ISphSchema * pOldSchema, const ISphSchema * pNewSchema ) override; void Command ( ESphExprCommand eCmd, void * pArg ) override; uint64_t GetHash ( const ISphSchema & tSorterSchema, uint64_t uPrevHash, bool & bDisable ) override; protected: CSphRefcountedPtr<ISphExpr> m_pFirst; CSphRefcountedPtr<ISphExpr> m_pSecond; Expr_Binary_c ( const Expr_Binary_c & rhs ); private: const char * m_szExprName = nullptr; }; #endif // _exprtraits_
9,004
C++
.h
230
36.865217
147
0.711289
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,142
sphinxjsonquery.h
manticoresoftware_manticoresearch/src/sphinxjsonquery.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #ifndef _sphinxjsonquery_ #define _sphinxjsonquery_ #include "sphinx.h" #include "sphinxjson.h" #include "aggrexpr.h" class QueryParser_i; class StmtErrorReporter_i; class QueryProfile_c; struct cJSON; struct XQNode_t; struct SqlStmt_t; struct AggrComposite_t { CSphString m_sAlias; CSphString m_sColumn; }; struct JsonAggr_t : public AggrSettings_t { CSphString m_sBucketName; CSphString m_sCol; int m_iSize = 0; CSphString m_sSort; CSphVector<AggrComposite_t> m_dComposite; CSphVector<CSphFilterSettings> m_dCompositeAfterKey; CSphString GetAliasName () const; }; struct JsonDocField_t { CSphString m_sName; bool m_bDateTime = false; }; /// search query. Pure struct, no member functions struct JsonQuery_c : public CSphQuery { StrVec_t m_dSortFields; CSphVector<JsonDocField_t> m_dDocFields; CSphVector<JsonAggr_t> m_dAggs; }; struct ParsedJsonQuery_t { JsonQuery_c m_tQuery; CSphString m_sWarning; bool m_bProfile = false; int m_iPlan = 0; // 0 - no plan, 1 - description, 2 - object, 3 - both }; std::unique_ptr<QueryParser_i> sphCreateJsonQueryParser(); bool sphParseJsonQuery ( Str_t sQuery, ParsedJsonQuery_t & tPJQuery ); bool sphParseJsonQuery ( const JsonObj_c & tRoot, ParsedJsonQuery_t & tPJQuery ); bool sphParseJsonInsert ( const char * szInsert, SqlStmt_t & tStmt, DocID_t & tDocId, bool bReplace, CSphString & sError ); bool sphParseJsonUpdate ( Str_t sUpdate, SqlStmt_t & tStmt, DocID_t & tDocId, CSphString & sError ); bool sphParseJsonDelete ( Str_t sDelete, SqlStmt_t & tStmt, DocID_t & tDocId, CSphString & sError ); bool sphParseJsonStatement ( const char * szStmt, SqlStmt_t & tStmt, CSphString & sStmt, CSphString & sQuery, DocID_t & tDocId, CSphString & sError ); enum class ResultSetFormat_e : bool { ES, MntSearch }; CSphString sphEncodeResultJson ( const VecTraits_T<const AggrResult_t *> & dRes, const JsonQuery_c & tQuery, QueryProfile_c * pProfile, ResultSetFormat_e eFormat ); JsonObj_c sphEncodeInsertResultJson ( const char * szIndex, bool bReplace, DocID_t tDocId, ResultSetFormat_e eFormat ); JsonObj_c sphEncodeUpdateResultJson ( const char * szIndex, DocID_t tDocId, int iAffected, ResultSetFormat_e eFormat ); JsonObj_c sphEncodeDeleteResultJson ( const char * szIndex, DocID_t tDocId, int iAffected, ResultSetFormat_e eFormat ); JsonObj_c sphEncodeInsertErrorJson ( const char * szIndex, const char * szError, ResultSetFormat_e eFormat ); JsonObj_c sphEncodeTxnResultJson ( const char* szIndex, DocID_t tDocId, int iInserts, int iDeletes, int iUpdates, ResultSetFormat_e eFormat ); bool sphGetResultStats ( const char * szResult, int & iAffected, int & iWarnings, bool bUpdate ); bool NonEmptyQuery ( const JsonObj_c & tQuery ); bool CheckRootNode ( const JsonObj_c & tRoot, CSphString & sError ); CSphString JsonEncodeResultError ( const CSphString & sError, const char * sErrorType, int iStatus ); CSphString JsonEncodeResultError ( const CSphString & sError, const char * sErrorType, int iStatus, const char * sIndex ); CSphString JsonEncodeResultError ( const CSphString & sError, int iStatus ); bool ParseJsonInsertSource ( const JsonObj_c & tRoot, SqlStmt_t & tStmt, bool bReplace, CSphString & sError ); bool ParseJsonUpdate ( const JsonObj_c & tRoot, SqlStmt_t & tStmt, DocID_t & tDocId, CSphString & sError ); #endif
3,711
C++
.h
81
44.345679
165
0.770487
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,143
global_idf.h
manticoresoftware_manticoresearch/src/global_idf.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #ifndef MANTICORE_GLOBAL_IDF_H #define MANTICORE_GLOBAL_IDF_H #include "sphinxstd.h" namespace sph { class IDFer_c : public ISphRefcountedMT { protected: ~IDFer_c () override = default; public: virtual float GetIDF ( const CSphString& sWord, int64_t iDocsLocal, bool bPlainIDF ) const = 0; }; using IDFerRefPtr_c = CSphRefcountedPtr<IDFer_c>; IDFerRefPtr_c GetIDFer ( const CSphString& IDFPath ); /// update/clear global IDF cache bool PrereadGlobalIDF ( const CSphString& sPath, CSphString& sError ); void UpdateGlobalIDFs ( const StrVec_t& dFiles ); void ShutdownGlobalIDFs (); } #endif //MANTICORE_GLOBAL_IDF_H
1,113
C++
.h
30
35.366667
97
0.758364
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,144
sphinxjson.h
manticoresoftware_manticoresearch/src/sphinxjson.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2011-2016, Andrew Aksyonoff // Copyright (c) 2011-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #ifndef _sphinxjson_ #define _sphinxjson_ #include "sphinxutils.h" #include "sphinxdefs.h" #include "grouper.h" class ISphExpr; /// supported JSON value types enum ESphJsonType : BYTE { JSON_EOF = 0, JSON_INT32 = 1, JSON_INT64 = 2, JSON_DOUBLE = 3, JSON_STRING = 4, JSON_STRING_VECTOR = 5, JSON_INT32_VECTOR = 6, JSON_INT64_VECTOR = 7, JSON_DOUBLE_VECTOR = 8, JSON_MIXED_VECTOR = 9, JSON_OBJECT = 10, JSON_TRUE = 11, JSON_FALSE = 12, JSON_NULL = 13, JSON_ROOT = 14, JSON_TOTAL }; #if UNALIGNED_RAM_ACCESS && USE_LITTLE_ENDIAN template < typename NUM32 > inline NUM32 GetNUM32LE ( const BYTE * p ) { return *( const NUM32 * ) p; } template < typename NUM32 > inline void StoreNUM32LE ( BYTE * p, NUM32 v ) { *( NUM32 * ) ( p ) = v; } inline void StoreBigintLE ( BYTE * p, int64_t v ) { *( int64_t * ) ( p ) = v; } /// get stored value from SphinxBSON blob inline int64_t sphJsonLoadBigint ( const BYTE ** pp ) { int64_t iRes = *( const int64_t * ) ( *pp ); *pp += 8; return iRes; } #else template < typename NUM32 > inline NUM32 GetNUM32LE ( const BYTE * p ) { return p[0] + ( p[1]<<8 ) + ( p[2]<<16 ) + ( p[3]<<24 ); } template < typename NUM32 > inline void StoreNUM32LE ( BYTE * p, NUM32 v ) { p[0] = BYTE ( DWORD ( v ) ); p[1] = BYTE ( DWORD ( v ) >> 8 ); p[2] = BYTE ( DWORD ( v ) >> 16 ); p[3] = BYTE ( DWORD ( v ) >> 24 ); } inline void StoreBigintLE ( BYTE * p, int64_t v ) { StoreNUM32LE ( p, ( DWORD ) ( v & 0xffffffffUL ) ); StoreNUM32LE ( p + 4, ( int ) ( v >> 32 ) ); } /// get stored value from SphinxBSON blob inline int64_t sphJsonLoadBigint ( const BYTE ** pp ) { uint64_t uRes = GetNUM32LE<DWORD> ( *pp ); uRes += ( uint64_t ) GetNUM32LE<DWORD> ( (*pp)+4 ) << 32; *pp+=8; return uRes; } #endif /// get stored value from SphinxBSON blob inline int sphJsonLoadInt ( const BYTE ** pp ) { auto uRes = GetNUM32LE<int> ( *pp ); *pp += 4; return uRes; } /// unpack value from SphinxBSON blob /// 0..251 == value itself /// 252 == 2 more bytes /// 253 == 3 more bytes /// 254 == 4 more bytes /// 255 == reserved inline DWORD sphJsonUnpackInt ( const BYTE ** pp ) { const BYTE * p = *pp; DWORD uRes = p[0]; switch ( p[0] ) { default: (*pp) += 1; break; case 252: uRes = p[1] + ( p[2]<<8 ); (*pp) += 3; break; case 253: uRes = p[1] + ( p[2]<<8 ) + ( p[3]<<16 ); (*pp) += 4; break; case 254: uRes = GetNUM32LE<DWORD> (&p[1]); (*pp) += 5; break; case 255: assert ( 0 && "unexpected reserved length code 255" ); (*pp) += 1; break; } return uRes; } // lookup table // combo of IsEscapeChar + GetEscapedChar with the table works 25..150 times faster! alignas ( 128 ) constexpr BYTE g_JsonEscapingLookupTable[] = { 0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07, 'b'|0x80, 't'|0x80, 'n'|0x80, 0x0b, 'f'|0x80, 'r'|0x80, 0x0e, 0x0f, 0x10,0x11,0x12,0x13,0x14,0x15,0x16,0x17, 0x18,0x19,0x1a,0x1b,0x1c,0x1d,0x1e,0x1f, 0x20,0x21,'\"'|0x80,0x23,0x24,0x25,0x26,0x27, 0x28,0x29,0x2a,0x2b,0x2c,0x2d,0x2e,0x2f, 0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37, 0x38,0x39,0x3a,0x3b,0x3c,0x3d,0x3e,0x3f, 0x40,0x41,0x42,0x43,0x44,0x45,0x46,0x47, 0x48,0x49,0x4a,0x4b,0x4c,0x4d,0x4e,0x4f, 0x50,0x51,0x52,0x53,0x54,0x55,0x56,0x57, 0x58,0x59,0x5a,0x5b,'\\'|0x80,0x5d,0x5e,0x5f, 0x60,0x61,0x62,0x63,0x64,0x65,0x66,0x67, 0x68,0x69,0x6a,0x6b,0x6c,0x6d,0x6e,0x6f, 0x70,0x71,0x72,0x73,0x74,0x75,0x76,0x77, 0x78,0x79,0x7a,0x7b,0x7c,0x7d,0x7e,0x7f, }; alignas ( 64 ) constexpr BYTE g_JsonEscapeControlTable[] = "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f"; struct EscapeJsonString_t { static const char cQuote = '"'; static constexpr BYTE EscapingSpace ( BYTE c ) { if ( c & 0x80 ) return 0; // high table with charcodes >= 0x80 - no escaping if ( g_JsonEscapingLookupTable[c] & 0x80 ) return 1; // escaping 1 char will add 1 more char return ( c & 0xE0 ) ? 0 : 5; // escaping 1 control char will add 5 more chars. //return strchr ( "\"\\\b\f\n\r\t", c )!=nullptr; // \ is \x5C, " is \x22 } static void EscapeChar ( BYTE*& pOut, BYTE c ) { // high chars with code > 0x7F if ( c & 0x80 ) { *pOut++=c; return; } // lookup escaping chars if ( g_JsonEscapingLookupTable[c] & 0x80 ) { pOut[0] = '\\'; pOut[1] = g_JsonEscapingLookupTable[c] & 0x7F; pOut += 2; return; } // not yet escaped chars with codes > 0x1F if ( c & 0xE0 ) { *pOut++ = c; return; } // not yet escaped control chars - transform to \u00XX memcpy ( pOut, "\\u00", 4 ); memcpy ( pOut + 4, g_JsonEscapeControlTable + c * 2, 2 ); pOut += 6; } static void EscapeCharWithSpaces ( BYTE*& pOut, BYTE c ) { EscapeChar ( pOut, c ); } static void FixupSpace ( BYTE*& pOut, BYTE c ) { EscapeChar ( pOut, c ); } }; inline const StrBlock_t dJsonObj { FROMS ( "," ), FROMS ( "{" ), FROMS ( "}" ) }; // json object inline const StrBlock_t dJsonArr { FROMS ( "," ), FROMS ( "[" ), FROMS ( "]" ) }; // json array inline const StrBlock_t dJsonObjW { FROMS ( ",\n" ), FROMS ( "{\n" ), FROMS ( "\n}" ) }; // json object with formatting inline const StrBlock_t dJsonArrW { FROMS ( ",\n" ), FROMS ( "[\n" ), FROMS ( "\n]" ) }; // json array with formatting class JsonEscapedBuilder : public EscapedStringBuilder_T<EscapeJsonString_t> { using Base_T = EscapedStringBuilder_T<EscapeJsonString_t>; public: ScopedComma_c Named ( const char * sName ) { Base_T::FixupSpacedAndAppendEscaped ( sName ); AppendRawChunk ( FROMS ( ":" ) ); SkipNextComma (); return { *this, nullptr }; } ScopedComma_c Object ( bool bAllowEmpty = false ) { return { *this, dJsonObj, bAllowEmpty }; } ScopedComma_c ObjectW ( bool bAllowEmpty = false ) { return { *this, dJsonObjW, bAllowEmpty }; } ScopedComma_c Array ( bool bAllowEmpty = false ) { return { *this, dJsonArr, bAllowEmpty }; } ScopedComma_c ArrayW ( bool bAllowEmpty = false ) { return { *this, dJsonArrW, bAllowEmpty }; } int NamedBlock( const char* sName ) { FixupSpacedAndAppendEscaped( sName ); AppendRawChunk( { ":", 1 } ); SkipNextComma(); return MuteBlock(); } int ObjectBlock() { return StartBlock( dJsonObj ); } int ObjectWBlock() { return StartBlock( dJsonObjW ); } int ArrayBlock() { return StartBlock ( dJsonArr ); } int ArrayWBlock() { return StartBlock ( dJsonArrW ); } void NamedString ( const char* szName, const char* szValue ) { Named ( szName ); FixupSpacedAndAppendEscaped ( szValue ); } void NamedString ( const char* szName, Str_t sValue ) { Named ( szName ); FixupSpacedAndAppendEscaped ( sValue.first, sValue.second ); } void NamedString ( const char* szName, const CSphString& sValue ) { NamedString ( szName, sValue.cstr() ); } void NamedStringNonEmpty ( const char* szName, const CSphString& sValue ) { if ( !sValue.IsEmpty() ) NamedString ( szName, sValue ); } void NamedStringNonDefault ( const char* szName, const CSphString& sValue, CSphString sDefault ) { if ( sValue!=sDefault ) NamedString ( szName, sValue ); } template<typename T> void NamedVal ( const char* szName, const T & tValue ) { Named ( szName ); *this << tValue; } template<typename T> void NamedValNonDefault ( const char* szName, T tValue, T tDefault=0 ) { if ( tValue != tDefault ) NamedVal ( szName, tValue ); } void String ( const char* szValue ) { FixupSpacedAndAppendEscaped ( szValue ); } void String ( Str_t sValue ) { FixupSpacedAndAppendEscaped ( sValue.first, sValue.second ); } void String ( const CSphString& sValue ) { FixupSpacedAndAppendEscaped ( sValue.cstr() ); } void StringNonEmpty ( const CSphString& sValue ) { if ( !sValue.IsEmpty() ) String ( sValue ); } // non-escaped. // Imply, that only internal strings no-need of escape (say, pre-escaped) in use, // works faster, because skip escaping pass. template<typename STR> void NameNE ( STR sName ) { StringBuilder_c::AppendName ( sName ); } template<typename STR1, typename STR2> void NamedStringNE ( STR1 sName, STR2 sValue ) { NameNE ( sName ); AppendString ( sValue, '"' ); } template<typename STR, typename T> void NamedValNE ( STR sName, T tValue ) { NameNE ( sName ); *this << tValue; } template<typename STR, typename T> void NamedValNonNull ( STR sName, T&& tValue ) { if ( tValue ) NamedValNE ( sName, std::forward<T&&> ( tValue ) ); } }; /// parse JSON, convert it into SphinxBSON blob bool sphJsonParse ( CSphVector<BYTE> & dData, char * sData, bool bAutoconv, bool bToLowercase, bool bCheckSize, CSphString & sError ); bool sphJsonParse ( CSphVector<BYTE> & dData, char * sData, bool bAutoconv, bool bToLowercase, bool bCheckSize, StringBuilder_c & sMsg ); bool sphJsonParse ( CSphVector<BYTE> & dData, const CSphString& sFileName, CSphString & sError ); /// convert SphinxBSON blob back to JSON document void sphJsonFormat ( JsonEscapedBuilder & dOut, const BYTE * pData ); /// convert SphinxBSON blob back to JSON document /// NOTE, bQuoteString==false is intended to format individual values only (and avoid quoting string values in that case) const BYTE * sphJsonFieldFormat ( JsonEscapedBuilder & sOut, const BYTE * pData, ESphJsonType eType, bool bQuoteString=true ); /// compute key mask (for Bloom filtering) from the key name DWORD sphJsonKeyMask ( const char * sKey, int iLen ); /// returns core type for collections (like JSON_INT32 for JSON_INT32_VECTOR), or JSON_EOF if not suitable ESphJsonType sphJsonGetCoreType ( ESphJsonType eType ); /// find first value in SphinxBSON blob, return associated type ESphJsonType sphJsonFindFirst ( const BYTE ** ppData ); /// find value by key in SphinxBSON blob, return associated type ESphJsonType sphJsonFindByKey ( ESphJsonType eType, const BYTE ** ppValue, const void * pKey, int iLen, DWORD uMask ); /// find value by index in SphinxBSON blob, return associated type ESphJsonType sphJsonFindByIndex ( ESphJsonType eType, const BYTE ** ppValue, int iIndex ); /// extract object part from the name; return false if not JSON name. szIndex is the possible name of joined index bool sphJsonNameSplit ( const char * szName, const char * szIndex = nullptr, CSphString * pColumn = nullptr ); /// compute node size, in bytes /// returns -1 when data itself is required to compute the size, but pData is NULL int sphJsonNodeSize ( ESphJsonType eType, const BYTE * pData ); /// size of note type eType (-1 for arrays) int sphJsonSingleNodeSize ( ESphJsonType eType ); /// skip the current node, and update the pointer void sphJsonSkipNode ( ESphJsonType eType, const BYTE ** ppData ); /// return object length or array length, in elements /// POD types return 1, empty objects return 0 int sphJsonFieldLength ( ESphJsonType eType, const BYTE * pData ); /// inplace JSON update, both for realtime and non-realtime indexes, returns true if update is possible bool sphJsonInplaceUpdate ( ESphJsonType eValueType, int64_t iValue, ISphExpr * pExpr, BYTE * pBlobPool, const CSphRowitem * pRow, bool bUpdate ); /// converts string to number bool sphJsonStringToNumber ( const char * s, int iLen, ESphJsonType & eType, int64_t & iVal, double & fVal ); /// unpack json data offset from uint64_t uint64_t sphJsonUnpackOffset ( uint64_t uPacked ); /// unpack json data type from uint64_t ESphJsonType sphJsonUnpackType ( uint64_t uPacked ); /// pack json type and offset to uint64_t uint64_t sphJsonPackTypeOffset ( ESphJsonType eType, uint64_t uOffset ); /// internal cJSON init void sphInitCJson(); const char * JsonTypeName ( ESphJsonType eType ); struct cJSON; /// simple cJSON wrapper class JsonObj_c { public: explicit JsonObj_c ( bool bArray = false ); explicit JsonObj_c ( cJSON * pRoot, bool bOwner = true ); explicit JsonObj_c ( const char * szJson ); explicit JsonObj_c ( Str_t sJson ); JsonObj_c ( JsonObj_c && rhs ) noexcept; ~JsonObj_c(); // a shortcut for !Empty() operator bool() const; void Swap ( JsonObj_c& rhs ) noexcept; JsonObj_c & operator = ( JsonObj_c rhs ); JsonObj_c operator[] ( int iItem ) const; JsonObj_c & operator++(); JsonObj_c operator*(); void AddStr ( const char * szName, const char * szValue ); void AddStr ( const char * szName, const CSphString & sValue ); void AddInt ( const char * szName, int64_t iValue ); void AddUint ( const char * szName, uint64_t uValue ); void AddFlt ( const char * szName, float fValue ); void AddBool ( const char * szName, bool bValue ); void AddNull ( const char * szName ); void AddItem ( const char * szName, JsonObj_c & tObj ); void AddItem ( JsonObj_c & tObj ); void DelItem ( const char * szName ); void ReplaceItem ( int iIndex, JsonObj_c & tObj ); JsonObj_c Clone () const; int Size() const; JsonObj_c GetItem ( const char * szName ) const; JsonObj_c GetIntItem ( const char * szName, CSphString & sError, bool bIgnoreMissing=false ) const; JsonObj_c GetIntItem ( const char * szName1, const char * szName2, CSphString & sError ) const; JsonObj_c GetBoolItem ( const char * szName, CSphString & sError, bool bIgnoreMissing=false ) const; JsonObj_c GetStrItem ( const char * szName, CSphString & sError, bool bIgnoreMissing=false ) const; JsonObj_c GetStrItem ( const char * szName1, const char * szName2, CSphString & sError ) const; JsonObj_c GetObjItem ( const char * szName, CSphString & sError, bool bIgnoreMissing=false ) const; JsonObj_c GetArrayItem ( const char * szName, CSphString & sError, bool bIgnoreMissing=false ) const; bool FetchIntItem ( int & iValue, const char * szName, CSphString & sError, bool bIgnoreMissing=false ) const; bool FetchBoolItem ( bool & bValue, const char * szName, CSphString & sError, bool bIgnoreMissing=false ) const; bool FetchStrItem ( CSphString & sValue, const char * szName, CSphString & sError, bool bIgnoreMissing=false ) const; bool HasItem ( const char * szName ) const; static JsonObj_c CreateInt ( int64_t iInt ); static JsonObj_c CreateUint ( uint64_t uInt ); static JsonObj_c CreateStr ( const CSphString & sStr ); bool IsInt() const; bool IsUint() const; bool IsDbl() const; bool IsNum() const; bool IsBool() const; bool IsObj() const; bool IsStr() const; bool IsArray() const; bool Empty() const; bool IsNull() const; const char * Name() const; const char * TypeName() const; int64_t IntVal() const; bool BoolVal() const; float FltVal() const; double DblVal() const; const char * SzVal() const; CSphString StrVal() const; const char * GetErrorPtr() const; bool GetError ( const char * szBuf, int iBufLen, CSphString & sError ) const; bool GetError ( const char* szBuf, int iBufLen ) const; cJSON * GetRoot() const; CSphString AsString ( bool bFormat=false ) const; JsonObj_c begin() const; JsonObj_c end() const; protected: cJSON * m_pRoot {nullptr}; bool m_bOwner {true}; cJSON * Leak(); JsonObj_c GetChild ( const char * szName, CSphString & sError, bool bIgnoreMissing ) const; }; #ifndef JsonNull #define JsonNull JsonObj_c(nullptr,false) #endif namespace bson { using NodeHandle_t = std::pair< const BYTE *, ESphJsonType>; const NodeHandle_t nullnode = { nullptr, JSON_EOF }; inline NodeHandle_t MakeHandle ( const VecTraits_T<BYTE>& dData ) { return dData.IsEmpty () ? nullnode : NodeHandle_t ( { dData.begin (), JSON_ROOT } ); } bool IsAssoc ( const NodeHandle_t & ); bool IsArray ( const NodeHandle_t & ); bool IsPODBlob ( const NodeHandle_t & ); bool IsString ( const NodeHandle_t & ); bool IsInt ( const NodeHandle_t & ); bool IsDouble ( const NodeHandle_t & ); bool IsNumeric ( const NodeHandle_t & ); // access to values by locator bool Bool ( const NodeHandle_t& tLocator, bool bDefault=false ); int64_t Int ( const NodeHandle_t & tLocator, int64_t iDefault=0 ); double Double ( const NodeHandle_t & tLocator, double fDefault=0.0 ); CSphString String ( const NodeHandle_t & tLocator, CSphString sDefault="" ); Str_t ToStr ( const NodeHandle_t & tLocator ); inline bool IsNullNode ( const NodeHandle_t & dNode ) { return dNode==nullnode; } // iterate over collection (without names). using Action_f = std::function<void ( const NodeHandle_t &tNode )>; void ForEach ( const NodeHandle_t &tLocator, Action_f&& fAction ); // iterate over collection (incl. names). using NamedAction_f = std::function<void ( CSphString&& sName, const NodeHandle_t &tNode )>; void ForEach ( const NodeHandle_t &tLocator, NamedAction_f&& fAction ); // iterate over collection (without names). Return false from action means 'stop iteration' using CondAction_f = std::function<bool ( const NodeHandle_t &tNode )>; void ForSome ( const NodeHandle_t &tLocator, CondAction_f&& fAction ); // iterate over collection (incl. names). Return false from action means 'stop iteration' using CondNamedAction_f = std::function<bool ( CSphString&& sName, const NodeHandle_t &tNode )>; void ForSome ( const NodeHandle_t &tLocator, CondNamedAction_f&& fAction ); // suitable for strings and vectors of pods as int, int64, double. Str_t RawBlob ( const NodeHandle_t &tLocator ); // many internals might be represented as vector template<typename BLOB> VecTraits_T<BLOB> Vector ( const NodeHandle_t &tLocator ) { auto dBlob = RawBlob ( tLocator ); return VecTraits_T<BLOB> ( (BLOB*) dBlob.first, dBlob.second ); } // access to encoded bson class Bson_c { protected: NodeHandle_t m_dData { nullnode }; mutable StringBuilder_c m_sError; public: Bson_c ( NodeHandle_t dBson = nullnode ) : m_dData { std::move (dBson) } {} explicit Bson_c ( const VecTraits_T<BYTE>& dBlob ); // traits bool IsAssoc () const { return bson::IsAssoc ( m_dData ); } /// whether we can access members by name bool IsArray () const { return bson::IsArray ( m_dData ); } /// whether we can access members by index bool IsNull () const { return m_dData==nullnode; } /// whether node valid (i.e. not eof type, not nullptr locator). operator bool() const { return !IsNull(); } // same as IsNull. bool IsString () const { return m_dData.second==JSON_STRING; } bool IsInt () const { return bson::IsInt ( m_dData ); } bool IsDouble () const { return bson::IsDouble ( m_dData ); } bool IsNumeric () const { return bson::IsNumeric (m_dData); } bool IsNonEmptyString () const { return bson::IsString ( m_dData ) && !IsEmpty (); } /// whether we can return non-empty string bool IsEmpty () const; /// whether container bson has child elements, or string is empty. int CountValues() const; /// count of elems. Objs and root will linearly iterate, other returns immediately. int StandaloneSize() const; /// size of blob need to save node as root (standalone) bson bool StrEq ( const char* sValue ) const; // true if value is string and eq to sValue // navigate over bson NodeHandle_t ChildByName ( const char* sName ) const; // look by direct child name NodeHandle_t ChildByIndex ( int iIdx ) const; // look by direct child idx NodeHandle_t ChildByPath ( const char * sPath ) const; // complex look like 'query.percolate.documents[3].title' // rapid lookup by name helpers. Ellipsis must be list of str literals, // like HasAnyOf (2, "foo", "bar"); HasAnyOf (3, "foo", "bar", "baz") bool HasAnyOf ( int iNames, ... ) const; bool HasAnyOf ( std::initializer_list<const char*> dNames ) const; std::pair<int,NodeHandle_t> GetFirstOf ( std::initializer_list<const char *> dNames ) const; // access to my values bool Bool () const; int64_t Int () const; double Double () const; CSphString String () const; void ForEach ( Action_f&& fAction ) const; void ForEach ( NamedAction_f&& fAction ) const; void ForSome ( CondAction_f&& fAction ) const; void ForSome ( CondNamedAction_f&& fAction ) const; // format back to json bool BsonToJson ( CSphString& ) const; bool BsonToJson ( CSphString& , bool bQuot ) const; // save as standalone (root) bson. bool BsonToBson ( BYTE* ) const; bool BsonToBson ( CSphVector<BYTE>& dOutput ) const; // helpers inline ESphJsonType GetType() const { return m_dData.second; } operator NodeHandle_t () const { return m_dData; } const char * sError () const; }; // iterate over Bson_c class BsonIterator_c : public Bson_c { const BYTE * m_pData = nullptr; ESphJsonType m_eType = JSON_EOF; // parent's type int m_iSize = -1; // for nodes with known size CSphString m_sName; inline bool Finish () // used as shortcut return { if ( m_iSize>0 ) m_iSize = 0; m_dData = bson::nullnode; return false; } public: explicit BsonIterator_c ( const NodeHandle_t &dParent ); bool Next(); int NumElems() const { return m_iSize; } // how many items we still not iterated ( actual only for arrays; otherwise it is -1 ) CSphString GetName() const { return m_sName; } }; // parse and access to encoded bson class BsonContainer_c : public Bson_c { CSphVector<BYTE> m_Bson; public: explicit BsonContainer_c ( char* sJson, bool bAutoconv=false, bool bToLowercase=true, bool bCheckSize=true ); explicit BsonContainer_c ( const char * sJsonc, bool bAutoconv=false, bool bToLowercase = true, bool bCheckSize=true ) : BsonContainer_c ( const_cast<char *> ( CSphString ( sJsonc ).cstr() ), bToLowercase, bCheckSize ) {} }; class BsonContainer2_c : public Bson_c { CSphVector<BYTE> m_Bson; public: explicit BsonContainer2_c ( const char * sJsonc, bool bAutoconv = false, bool bToLowercase = true ); }; bool JsonObjToBson ( JsonObj_c & tJSON, CSphVector<BYTE> &dData, bool bAutoconv, bool bToLowercase/*, StringBuilder_c &sMsg*/ ); bool cJsonToBson ( cJSON * pCJSON, CSphVector<BYTE> &dData, bool bAutoconv=false, bool bToLowercase = true /*, StringBuilder_c &sMsg */); enum class JsonParser_e { BSON, CJSON, }; bool ValidateJson ( const char * sJson, JsonParser_e eParse, CSphString * pError=nullptr ); bool ValidateJson ( const char* sJson, CSphString* pError=nullptr ); // this are generic purpose serializer (bson as any object) class Assoc_c { protected: CSphVector<BYTE>& m_dBson; DWORD m_uBloomMask = 0; void StartTypedNode ( ESphJsonType eType, const char* szName=nullptr ); public: explicit Assoc_c ( CSphVector<BYTE> & dBsonTarget ) : m_dBson ( dBsonTarget ) {} void AddInt ( const char* szName, int64_t iValue ); void AddDouble ( const char * szName, double fValue ); void AddString ( const char * szName, const char* szValue ); void AddBlob ( const char * szName, const ByteBlob_t & dValue ); // blob of bytes as string void AddBool ( const char * szName, bool bValue ); void AddNull ( const char * szName ); void AddStringVec ( const char * szName, const VecTraits_T<CSphString> & dData ); void AddStringVec ( const char * szName, const VecTraits_T<const char *> & dData ); void AddIntVec ( const char * szName, const VecTraits_T<int> & dData ); void AddIntVec ( const char * szName, const VecTraits_T<int64_t> & dData ); void AddDoubleVec ( const char * szName, const VecTraits_T<double> & dData ); CSphVector<BYTE> & StartObj ( const char * szName ); CSphVector<BYTE> & StartStringVec ( const char * szName ); CSphVector<BYTE> & StartIntVec ( const char * szName ); CSphVector<BYTE> & StartBigintVec ( const char * szName ); CSphVector<BYTE> & StartDoubleVec ( const char * szName ); CSphVector<BYTE> & StartMixedVec ( const char * szName ); }; class Root_c : public Assoc_c { public: explicit Root_c ( CSphVector<BYTE> & dBsonTarget ); ~Root_c (); }; class Obj_c : public Assoc_c { int m_iStartPos; public: explicit Obj_c ( CSphVector<BYTE> & dBsonTarget ); ~Obj_c (); }; class MixedVector_c { CSphVector<BYTE>& m_dBson; int m_iStartPos; public: MixedVector_c ( CSphVector<BYTE> & dBson, int iSize ); ~MixedVector_c(); void AddInt ( int64_t iValue ); void AddDouble ( double fValue ); void AddString ( const char* szValue ); void AddBlob ( const ByteBlob_t& dValue ); // blob of bytes as string void AddBool ( bool bValue ); void AddNull (); void AddStringVec ( const VecTraits_T<CSphString> & dData ); void AddStringVec ( const VecTraits_T<const char*> & dData ); void AddIntVec ( const VecTraits_T<int> & dData ); void AddIntVec ( const VecTraits_T<int64_t> & dData ); void AddDoubleVec ( const VecTraits_T<double> & dData ); CSphVector<BYTE> & StartObj (); CSphVector<BYTE> & StartStringVec (); CSphVector<BYTE> & StartIntVec (); CSphVector<BYTE> & StartBigintVec (); CSphVector<BYTE> & StartDoubleVec (); CSphVector<BYTE> & StartMixedVec (); }; class StringVector_c { CSphVector<BYTE>& m_dBson; int m_iStartPos; public: StringVector_c ( CSphVector<BYTE> & dBson, int iSize ); ~StringVector_c(); void AddValue ( const char * szValue ); void AddValue ( const ByteBlob_t& dValue ); void AddValues ( const VecTraits_T<CSphString> & dData ); void AddValues ( const VecTraits_T<const char *> & dData ); }; class IntVector_c { CSphVector<BYTE>& m_dBson; public: IntVector_c ( CSphVector<BYTE> & dBson, int iSize ); void AddValue ( int iValue ); void AddValues ( const VecTraits_T<int> & dData ); }; class BigintVector_c { CSphVector<BYTE>& m_dBson; public: BigintVector_c ( CSphVector<BYTE> & dBson, int iSize ); void AddValue ( int64_t iValue ); void AddValues ( const VecTraits_T<int64_t> & dData ); }; class DoubleVector_c { CSphVector<BYTE>& m_dBson; public: DoubleVector_c ( CSphVector<BYTE> & dBson, int iSize ); void AddValue ( double iValue ); void AddValues ( const VecTraits_T<double> & dData ); }; }; // namespace bson int sphJsonUnescape ( char ** pEscaped, int iLen ); int sphJsonUnescape1 ( char ** pEscaped, int iLen ); int JsonUnescape ( char * pTarget, const char * pEscaped, int iLen ); CSphString FormatJsonAsSortStr ( const BYTE * pVal, ESphJsonType eJson ); template <typename PUSH> static bool PushJsonField ( int64_t iValue, const BYTE * pBlobPool, PUSH && fnPush ) { int iLen; char szBuf[32]; SphGroupKey_t uGroupKey; ESphJsonType eJson = sphJsonUnpackType ( iValue ); const BYTE * pValue = pBlobPool + sphJsonUnpackOffset ( iValue ); switch ( eJson ) { case JSON_ROOT: { iLen = sphJsonNodeSize ( JSON_ROOT, pValue ); bool bEmpty = iLen==5; // mask and JSON_EOF uGroupKey = bEmpty ? 0 : sphFNV64 ( pValue, iLen ); return fnPush ( bEmpty ? nullptr : &iValue, uGroupKey ); } case JSON_STRING: case JSON_OBJECT: case JSON_MIXED_VECTOR: iLen = sphJsonUnpackInt ( &pValue ); uGroupKey = ( iLen==1 && eJson!=JSON_STRING ) ? 0 : sphFNV64 ( pValue, iLen ); return fnPush ( ( iLen==1 && eJson!=JSON_STRING ) ? nullptr : &iValue, uGroupKey ); case JSON_STRING_VECTOR: { bool bRes = false; sphJsonUnpackInt ( &pValue ); iLen = sphJsonUnpackInt ( &pValue ); for ( int i=0;i<iLen;i++ ) { int64_t iNewValue = sphJsonPackTypeOffset ( JSON_STRING, pValue-pBlobPool ); int iStrLen = sphJsonUnpackInt ( &pValue ); uGroupKey = sphFNV64 ( pValue, iStrLen ); bRes |= fnPush ( &iNewValue, uGroupKey ); pValue += iStrLen; } return bRes; } case JSON_INT32: #if __has_include( <charconv>) *std::to_chars ( szBuf, szBuf + 32, (int)sphGetDword ( pValue ) ).ptr = '\0'; return fnPush ( &iValue, sphFNV64 ( szBuf ) ); #else return fnPush ( &iValue, sphFNV64 ( (BYTE*)FormatInt ( szBuf, (int)sphGetDword ( pValue ) ) ) ); #endif case JSON_INT64: #if __has_include( <charconv>) *std::to_chars ( szBuf, szBuf + 32, sphJsonLoadBigint ( &pValue ) ).ptr = '\0'; return fnPush ( &iValue, sphFNV64 ( szBuf ) ); #else return fnPush ( &iValue, sphFNV64 ( (BYTE*)FormatInt ( szBuf, (int)sphJsonLoadBigint ( &pValue ) ) ) ); #endif case JSON_DOUBLE: snprintf ( szBuf, sizeof(szBuf), "%f", sphQW2D ( sphJsonLoadBigint ( &pValue ) ) ); return fnPush ( &iValue, sphFNV64 ( (const BYTE*)szBuf ) ); case JSON_INT32_VECTOR: { bool bRes = false; iLen = sphJsonUnpackInt ( &pValue ); auto p = (const int*)pValue; for ( int i=0;i<iLen;i++ ) { int64_t iPacked = sphJsonPackTypeOffset ( JSON_INT32, (const BYTE*)p-pBlobPool ); uGroupKey = *p++; bRes |= fnPush ( &iPacked, uGroupKey ); } return bRes; } case JSON_INT64_VECTOR: case JSON_DOUBLE_VECTOR: { bool bRes = false; iLen = sphJsonUnpackInt ( &pValue ); auto p = (const int64_t*)pValue; ESphJsonType eType = eJson==JSON_INT64_VECTOR ? JSON_INT64 : JSON_DOUBLE; for ( int i=0;i<iLen;i++ ) { int64_t iPacked = sphJsonPackTypeOffset ( eType, (const BYTE*)p-pBlobPool ); uGroupKey = *p++; bRes |= fnPush ( &iPacked, uGroupKey ); } return bRes; } case JSON_TRUE: case JSON_FALSE: uGroupKey = eJson; return fnPush ( &iValue, uGroupKey ); default: uGroupKey = 0; iValue = 0; return fnPush ( &iValue, uGroupKey ); } } template <typename PUSH> void PushJsonFieldPtr ( const BYTE * pVal, ESphJsonType eJson, PUSH && fnPush ) { if ( !pVal ) return; switch ( eJson ) { case JSON_INT32: fnPush ( sphFNV64 ( sphJsonLoadInt(&pVal) ) ); break; case JSON_INT64: case JSON_DOUBLE: fnPush ( sphFNV64 ( sphJsonLoadBigint(&pVal) ) ); break; case JSON_STRING: { int iLen = sphJsonUnpackInt ( &pVal ); fnPush ( sphFNV64 ( pVal, iLen ) ); } break; case JSON_INT32_VECTOR: case JSON_INT64_VECTOR: case JSON_DOUBLE_VECTOR: { int iSize = eJson==JSON_INT32_VECTOR ? 1 : 2; int iVals = sphJsonUnpackInt ( &pVal ); if ( !iVals ) break; auto * pValues = (const int*)pVal; for ( int i = 0; i < iVals; i++ ) { fnPush ( sphFNV64(*pValues) ); pValues += iSize; } } break; case JSON_STRING_VECTOR: { sphJsonUnpackInt ( &pVal ); // total length int iCount = sphJsonUnpackInt ( &pVal ); // head element if ( iCount ) { int iElemLen = sphJsonUnpackInt ( &pVal ); fnPush ( sphFNV64 ( pVal, iElemLen ) ); pVal += iElemLen; } // tail elements separated by space for ( int i=1; i<iCount; i++ ) { int iElemLen = sphJsonUnpackInt ( &pVal ); fnPush ( sphFNV64 ( pVal, iElemLen ) ); pVal += iElemLen; } break; } default: break; } } #endif // _sphinxjson_
30,393
C++
.h
848
33.643868
146
0.703568
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,145
searchdexpr.h
manticoresoftware_manticoresearch/src/searchdexpr.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #ifndef _searchdexpr_ #define _searchdexpr_ #include "sphinxexpr.h" #include "sphinxdefs.h" class CSphIndex; /// searchd expression hook /// needed to implement functions that are builtin for searchd, /// but can not be builtin in the generic expression engine itself, /// like SNIPPET() function that must know about indexes, tokenizers, etc class ExprHook_c : public ISphExprHook { public: int IsKnownIdent ( const char * ) const final { return -1; } int IsKnownFunc ( const char * sFunc ) const final; ISphExpr * CreateNode ( int iID, ISphExpr * pLeft, const ISphSchema * pRsetSchema, ESphEvalStage * pEvalStage, bool * pNeedDocIds, CSphString & sError ) final; ESphAttr GetIdentType ( int ) const final; ESphAttr GetReturnType ( int iID, const CSphVector<ESphAttr> & dArgs, bool, CSphString & sError ) const final; void CheckEnter ( int ) final {} void CheckExit ( int ) final {} void SetIndex ( const CSphIndex * pIndex ) { m_pIndex = pIndex; } void SetProfiler ( QueryProfile_c * pProfiler ) { m_pProfiler = pProfiler; } void SetQueryType ( QueryType_e eType ) { m_eQueryType = eType; } private: const CSphIndex * m_pIndex = nullptr; /// BLOODY HACK QueryProfile_c * m_pProfiler = nullptr; QueryType_e m_eQueryType = QUERY_API; }; #endif // _searchdexpr_
1,770
C++
.h
39
43.871795
160
0.741879
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,146
sphinxql_second.h
manticoresoftware_manticoresearch/src/sphinxql_second.h
// // Copyright (c) 2021-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #pragma once #include "searchdsql.h" ParseResult_e ParseSecond ( Str_t sQuery, CSphVector<SqlStmt_t>& dStmt, CSphString& sError );
609
C++
.h
14
42.357143
93
0.755481
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,147
match.h
manticoresoftware_manticoresearch/src/match.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #pragma once #include "schema/locator.h" /// search query match (document info plus weight/tag) class CSphMatch : public ISphNoncopyable { friend class ISphSchema; friend class CSphSchema; friend class CSphSchemaHelper; friend class CSphRsetSchema; public: RowID_t m_tRowID {INVALID_ROWID}; ///< document ID const CSphRowitem * m_pStatic {nullptr}; ///< static part (stored in and owned by the index) CSphRowitem * m_pDynamic {nullptr}; ///< dynamic part (computed per query; owned by the match) int m_iWeight {0}; ///< my computed weight int m_iTag {0}; ///< my index tag public: CSphMatch () = default; CSphMatch ( RowID_t tRowID, const CSphRowitem* pStatic ) : m_tRowID { tRowID } , m_pStatic { pStatic } {} /// dtor. frees everything ~CSphMatch (); /// reset void Reset ( int iDynamic ); // if mem region reinterpreted as match - ensure d-tr will not do sad things as delete garbaged m_pDynamic void CleanGarbage(); void ResetDynamic(); /// assignment void Combine ( const CSphMatch & rhs, int iDynamic ); /// integer getter FORCE_INLINE SphAttr_t GetAttr ( const CSphAttrLocator & tLoc ) const; float GetAttrFloat ( const CSphAttrLocator & tLoc ) const; double GetAttrDouble ( const CSphAttrLocator & tLoc ) const; /// integer setter FORCE_INLINE void SetAttr ( const CSphAttrLocator & tLoc, SphAttr_t uValue ) const; /// add scalar value to attribute void AddCounterScalar ( const CSphAttrLocator & tLoc, SphAttr_t uValue ) const; /// add same-located value from another match void AddCounterAttr ( const CSphAttrLocator & tLoc, const CSphMatch& tValue ) const; void SetAttrFloat ( const CSphAttrLocator & tLoc, float fValue ) const; void SetAttrDouble ( const CSphAttrLocator & tLoc, double fValue ) const; /// fetches blobs from both data ptr attrs and pooled blob attrs ByteBlob_t FetchAttrData ( const CSphAttrLocator & tLoc, const BYTE * pPool ) const; }; /// specialized swapper void Swap ( CSphMatch & a, CSphMatch & b ); FORCE_INLINE SphAttr_t ExchangeAttr ( const CSphMatch& tMatch, const CSphAttrLocator& tLoc, SphAttr_t uNewValue ); #include "match_impl.h"
2,635
C++
.h
60
41.933333
114
0.742857
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,148
knnlib.h
manticoresoftware_manticoresearch/src/knnlib.h
// // Copyright (c) 2020-2024, Manticore Software LTD (https://manticoresearch.com) // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #pragma once #include "sphinxexpr.h" #include "knn/knn.h" class ISphSchema; std::unique_ptr<knn::KNN_i> CreateKNN ( CSphString & sError ); std::unique_ptr<knn::Builder_i> CreateKNNBuilder ( const ISphSchema & tSchema, int64_t iNumElements, CSphString & sError ); std::unique_ptr<knn::Distance_i> CreateKNNDistanceCalc ( const knn::IndexSettings_t & tSettings ); bool InitKNN ( CSphString & sError ); void ShutdownKNN(); const char * GetKNNVersionStr(); bool IsKNNLibLoaded();
870
C++
.h
20
42.2
124
0.75
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,149
client_session.h
manticoresoftware_manticoresearch/src/client_session.h
// // Copyright (c) 2021-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org // #pragma once #include "sphinxstd.h" #include "sphinx.h" #include "queryprofile.h" #include "searchdaemon.h" #include "searchdsql.h" #include "sphinxpq.h" class ClientSession_c { public: CSphString m_sError; CSphQueryResultMeta m_tLastMeta; CSphSessionAccum m_tAcc; CPqResult m_tPercolateMeta; SqlStmt_e m_eLastStmt { STMT_DUMMY }; bool m_bFederatedUser = false; CSphString m_sFederatedQuery; CSphString m_sUser; public: bool m_bAutoCommit = true; bool m_bInTransaction = false; CSphVector<int64_t> m_dLastIds; QueryProfile_c m_tProfile; QueryProfile_c m_tLastProfile; bool m_bOptimizeById = true; bool m_bDeprecatedEOF = false; public: bool Execute ( Str_t sQuery, RowBuffer_i& tOut ); void FreezeLastMeta(); };
1,209
C++
.h
41
27.95122
80
0.773861
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,150
searchdaemon.h
manticoresoftware_manticoresearch/src/searchdaemon.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // /// @file searchdaemon.h /// Declarations for the stuff specifically needed by searchd to serve the indexes. #ifndef _searchdaemon_ #define _searchdaemon_ #include "searchdconfig.h" #include "memio.h" #include "accumulator.h" ///////////////////////////////////////////////////////////////////////////// // MACHINE-DEPENDENT STUFF ///////////////////////////////////////////////////////////////////////////// #if _WIN32 // Win-specific headers and calls #include <winsock2.h> #define HAVE_POLL 1 static inline int poll ( struct pollfd *pfd, int nfds, int timeout ) { return WSAPoll ( pfd, nfds, timeout ); } #define sphSockRecv(_sock,_buf,_len) ::recv(_sock,_buf,_len,0) #define sphSockSend(_sock,_buf,_len) ::send(_sock,_buf,_len,0) #define sphSockClose(_sock) ::closesocket(_sock) #define SSIZE_T long using sphIovec=WSABUF; #define IOBUFTYPE (CHAR FAR *) #define IOPTR(tX) (tX.buf) #define IOLEN(tX) (tX.len) // Windows hacks #undef EINTR #undef EWOULDBLOCK #undef ETIMEDOUT #undef EINPROGRESS #undef ECONNRESET #undef ECONNABORTED #define LOCK_EX 0 #define LOCK_UN 1 #define STDIN_FILENO fileno(stdin) #define STDOUT_FILENO fileno(stdout) #define STDERR_FILENO fileno(stderr) #define ETIMEDOUT WSAETIMEDOUT #define EWOULDBLOCK WSAEWOULDBLOCK #define EINPROGRESS WSAEINPROGRESS #define EINTR WSAEINTR #define ECONNRESET WSAECONNRESET #define ECONNABORTED WSAECONNABORTED #define ESHUTDOWN WSAESHUTDOWN #define ftruncate _chsize #else // UNIX-specific headers and calls #include <sys/socket.h> #include <sys/un.h> #include <arpa/inet.h> #if HAVE_POLL #include <poll.h> #endif #if HAVE_EPOLL #include <sys/epoll.h> #endif // there's no MSG_NOSIGNAL on OS X #ifndef MSG_NOSIGNAL #define MSG_NOSIGNAL 0 #endif #define sphSockRecv(_sock,_buf,_len) ::recv(_sock,_buf,_len,MSG_NOSIGNAL) #define sphSockSend(_sock,_buf,_len) ::send(_sock,_buf,_len,MSG_NOSIGNAL) #define sphSockClose(_sock) ::close(_sock) #define SSIZE_T ssize_t using sphIovec = iovec; #define IOBUFTYPE #define IOPTR(tX) (tX.iov_base) #define IOLEN(tX) (tX.iov_len) #endif // declarations for correct work of code analysis #include "sphinxutils.h" #include "sphinxint.h" #include "sphinxrt.h" #include "task_info.h" #include "client_task_info.h" #include "coroutine.h" #include "conversion.h" constexpr int SPHINXAPI_PORT = 9312; constexpr int SPHINXQL_PORT = 9306; constexpr int SPH_ADDRESS_SIZE = sizeof("000.000.000.000"); constexpr int SPH_ADDRPORT_SIZE = sizeof("000.000.000.000:00000"); constexpr int NETOUTBUF = 8192; volatile bool& sphGetGotSighup() noexcept; volatile bool& sphGetGotSigusr1() noexcept; volatile bool& sphGetGotSigusr2() noexcept; ///////////////////////////////////////////////////////////////////////////// // SOME SHARED GLOBAL VARIABLES ///////////////////////////////////////////////////////////////////////////// // these are in searchd.cpp extern int g_iReadTimeoutS; // defined in searchd.cpp extern int g_iWriteTimeoutS; // sec extern bool g_bTimeoutEachPacket; extern int g_iMaxPacketSize; // in bytes; for both query packets from clients and response packets from agents static const int64_t S2US = I64C ( 1000000 ); ///////////////////////////////////////////////////////////////////////////// // MISC GLOBALS ///////////////////////////////////////////////////////////////////////////// /// known commands /// (shared here because at least SEARCHD_COMMAND_TOTAL used outside the core) enum SearchdCommand_e : WORD { SEARCHD_COMMAND_SEARCH = 0, SEARCHD_COMMAND_EXCERPT = 1, SEARCHD_COMMAND_UPDATE = 2, SEARCHD_COMMAND_KEYWORDS = 3, SEARCHD_COMMAND_PERSIST = 4, SEARCHD_COMMAND_STATUS = 5, SEARCHD_COMMAND_UNUSED_6 = 6, SEARCHD_COMMAND_FLUSHATTRS = 7, SEARCHD_COMMAND_SPHINXQL = 8, SEARCHD_COMMAND_PING = 9, SEARCHD_COMMAND_DELETE = 10, SEARCHD_COMMAND_UVAR = 11, SEARCHD_COMMAND_INSERT = 12, SEARCHD_COMMAND_REPLACE = 13, SEARCHD_COMMAND_COMMIT = 14, SEARCHD_COMMAND_SUGGEST = 15, SEARCHD_COMMAND_JSON = 16, SEARCHD_COMMAND_CALLPQ = 17, SEARCHD_COMMAND_CLUSTER = 18, SEARCHD_COMMAND_GETFIELD = 19, SEARCHD_COMMAND_TOTAL, SEARCHD_COMMAND_WRONG = SEARCHD_COMMAND_TOTAL, }; const char* szCommand ( int ); /// master-agent API SEARCH command protocol extensions version enum { VER_COMMAND_SEARCH_MASTER = 23 }; /// known command versions /// (shared here because of REPLICATE) enum SearchdCommandV_e : WORD { VER_COMMAND_SEARCH = 0x126, // 1.38 VER_COMMAND_EXCERPT = 0x104, VER_COMMAND_UPDATE = 0x104, VER_COMMAND_KEYWORDS = 0x102, VER_COMMAND_STATUS = 0x101, VER_COMMAND_FLUSHATTRS = 0x100, VER_COMMAND_SPHINXQL = 0x100, VER_COMMAND_JSON = 0x100, VER_COMMAND_PING = 0x100, VER_COMMAND_UVAR = 0x100, VER_COMMAND_CALLPQ = 0x100, VER_COMMAND_CLUSTER = 0x109, VER_COMMAND_GETFIELD = 0x100, VER_COMMAND_SUGGEST = 0x101, VER_COMMAND_WRONG = 0, }; enum UpdateType_e { UPDATE_INT = 0, UPDATE_MVA32 = 1, UPDATE_STRING = 2, UPDATE_JSON = 3 }; enum ESphAddIndex { ADD_ERROR, // wasn't added because of config or other error ADD_NEEDLOAD, // index is loaded, but need to prealloc/preload, etc. ADD_DISTR, // distributed ADD_SERVED, // added and active (can be used in queries) // ADD_CLUSTER = 4, }; struct ListenerDesc_t { Proto_e m_eProto = Proto_e::UNKNOWN; CSphString m_sUnix; CSphString m_sAddr; DWORD m_uIP = 0; int m_iPort = 0; int m_iPortsCount = 0; bool m_bVIP = false; bool m_bReadOnly = false; }; // 'like' matcher class CheckLike { private: CSphString m_sPattern; public: explicit CheckLike( const char* sPattern ); bool Match( const char* sValue ) const noexcept; }; using Generator_fn = std::function<CSphString ( void )>; using GeneratorS_fn = std::function<StringBuilder_c ( void )>; // string vector with 'like' matcher class VectorLike: public StrVec_t, public CheckLike { StrVec_t m_dHeadNames; void FillTail (int iHas); public: explicit VectorLike ( int iCols = 2 ); explicit VectorLike ( const CSphString & sPattern ); // default 2 columns, { "Variable_name", "Value" } explicit VectorLike ( const CSphString & sPattern, int iCols ); explicit VectorLike ( const CSphString & sPattern, std::initializer_list<const char*> sCols); void SetColNames ( std::initializer_list<const char *> sCols ); void SetColName ( CSphString sValue, int iIdx = 0 ); const VecTraits_T<CSphString> & Header () const; // returns true, if single value matches bool MatchAdd( const char* sValue ); bool MatchAddf ( const char* sTemplate, ... ) __attribute__ (( format ( printf, 2, 3 ))); bool Matchf ( const char* sTemplate, ... ) const noexcept __attribute__ ( ( format ( printf, 2, 3 ) ) ); // unconditionally add formatted void Addf ( const char * sValueTmpl, ... ); // add pair void MatchTuplet ( const char * sKey, const char * sValue ); void MatchTupletf ( const char * sKey, const char* sValueTmpl, ... ); // __attribute__ ((format ( printf,3, 4 ))); void MatchTupletFn ( const char * sKey, Generator_fn && fnValuePrinter ); void MatchTupletFn ( const char * sKey, GeneratorS_fn && fnValuePrinter ); }; const char* GetIndexTypeName ( IndexType_e eType ); IndexType_e TypeOfIndexConfig ( const CSphString & sType ); // forwards from searchd bool CheckPort( int iPort, CSphString * pFatal=nullptr ); ListenerDesc_t ParseListener ( const char * sSpec, CSphString * pFatal=nullptr ); ListenerDesc_t ParseResolveListener ( const char* sSpec, bool bResolve = true, CSphString* pFatal = nullptr ); ///////////////////////////////////////////////////////////////////////////// // NETWORK SOCKET WRAPPERS ///////////////////////////////////////////////////////////////////////////// const char* sphSockError( int = 0 ); int sphSockGetErrno(); void sphSockSetErrno( int ); int sphSockPeekErrno(); int sphSetSockNB( int ); void sphSetSockNodelay ( int ); void sphSetSockReuseAddr ( int ); void sphSetSockReusePort ( int ); void sphSetSockTFO ( int ); int sphPoll( int iSock, int64_t tmTimeout, bool bWrite = false ); void SafeCloseSocket ( int & iFD ); /** \brief wrapper over getaddrinfo Invokes getaddrinfo for given host which perform name resolving (dns). \param[in] sHost the host name \param[in] bFatal whether failed resolving is fatal (false by default) - FIXME!!! true not used any more, refactor and remove that argument \param[in] bIP set true if sHost contains IP address (false by default) so no potentially lengthy network host address lockup necessary \return ipv4 address as DWORD, to be directly used as s_addr in connect(). */ DWORD sphGetAddress( const char* sHost, bool bFatal = false, bool bIP = false, CSphString * pFatal=nullptr ); char* sphFormatIP( char* sBuffer, int iBufferSize, DWORD uAddress ); CSphString GetMacAddress(); bool IsPortInRange( int iPort ); ///////////////////////////////////////////////////////////////////////////// // NETWORK BUFFERS ///////////////////////////////////////////////////////////////////////////// /// dynamic send buffer /// to remove ISphNoncopyable just add copy c-tor and operator= /// we just cache all streamed data into internal blob; /// NO data sending itself lives in this class. class ISphOutputBuffer { public: ISphOutputBuffer (); explicit ISphOutputBuffer ( CSphVector<BYTE>& dChunk ); virtual ~ISphOutputBuffer() {} void SendInt ( int iValue ) { SendT<int> ( htonl ( iValue ) ); } void SendAsDword ( int64_t iValue ) ///< sends the 32bit MAX_UINT if the value is greater than it. { iValue = Min ( Max ( iValue, 0 ), UINT_MAX ); SendDword ( DWORD(iValue) ); } void SendDword ( DWORD iValue ) { SendT<DWORD> ( htonl ( iValue ) ); } void SendWord ( WORD iValue ) { SendT<WORD> ( htons ( iValue ) ); } void SendFloat ( float fValue ) { SendT<DWORD> ( htonl ( sphF2DW ( fValue ) ) ); } void SendDouble ( double fValue ) { SendUint64 ( sphD2QW(fValue) ); } void SendByte ( BYTE uValue ) { SendT<BYTE> ( uValue ); } void SendLSBDword ( DWORD v ) { #if USE_LITTLE_ENDIAN SendT <DWORD> (v); #else SendByte ( (BYTE)( v & 0xff ) ); SendByte ( (BYTE)( (v>>8) & 0xff ) ); SendByte ( (BYTE)( (v>>16) & 0xff ) ); SendByte ( (BYTE)( (v>>24) & 0xff) ); #endif } void SendLSBWord ( WORD v ) { #if USE_LITTLE_ENDIAN SendT<WORD> ( v ); #else SendByte ( (BYTE)( v & 0xff ) ); SendByte ( (BYTE)( ( v >> 8 ) & 0xff ) ); #endif } void SendUint64 ( uint64_t uValue ) { SendT<DWORD> ( htonl ( (DWORD)( uValue>>32) ) ); SendT<DWORD> ( htonl ( (DWORD)( uValue & 0xffffffffUL) ) ); } void SendUint64 ( int64_t iValue ) { SendUint64 ( (uint64_t) iValue ); } void SendBytes ( const void * pBuf, int iLen ); ///< (was) protected to avoid network-vs-host order bugs void SendBytes ( const char * pBuf ); // used strlen() to get length void SendBytes ( const CSphString& sStr ); // used strlen() to get length void SendBytes ( const Str_t& sStr ); void SendBytes ( const VecTraits_T<BYTE>& dBuf ); void SendBytes ( const StringBuilder_c& dBuf ); void SendBytes ( ByteBlob_t dData ); // send array: first length(int), then byte blob void SendString ( const char * sStr ); void SendString ( const Str_t& sStr ); void SendArray ( const ISphOutputBuffer &tOut ); void SendArray ( const VecTraits_T<BYTE> &dBuf, int iElems=-1 ); void SendArray ( ByteBlob_t dData ); void SendArray ( const void * pBuf, int iLen ); void SendArray ( const StringBuilder_c &dBuf ); void SwapData ( CSphVector<BYTE> & rhs ) { m_dBuf.SwapData ( rhs ); } int GetSentCount () const { return m_dBuf.GetLength(); } void * GetBufPtr () const { return (char*) m_dBuf.begin();} void WriteInt ( int64_t iOff, int iValue ) // int in network file order { WriteT<int> ( iOff, htonl ( iValue ) ); } void WriteLSBDword ( int64_t iOff, DWORD v ) { #if USE_LITTLE_ENDIAN WriteT<DWORD> ( iOff, v ); #else WriteT<BYTE> ( iOff, (BYTE)( v & 0xff ) ); WriteT<BYTE> ( iOff+1, (BYTE)( ( v >> 8 ) & 0xff ) ); WriteT<BYTE> ( iOff+2, (BYTE)( ( v >> 16 ) & 0xff ) ); WriteT<BYTE> ( iOff+3, (BYTE)( ( v >> 24 ) & 0xff ) ); #endif } BYTE* ReservePlace ( int64_t iPlace ) { auto pRes = m_dBuf.AddN ( (int)iPlace ); m_dBuf.Resize ( m_dBuf.Idx(pRes)); return pRes; } void CommitZeroCopy ( int64_t iSize ) { m_dBuf.AddN ( (int)iSize ); } void Rewind ( int64_t iPos ) { m_dBuf.Resize ( iPos ); } CSphVector<BYTE> m_dBuf; template < typename T > void WriteT ( int64_t iOff, T tValue ) { sphUnalignedWrite ( m_dBuf.Begin () + iOff, tValue ); } private: template < typename T > void SendT ( T tValue ) ///< (was) protected to avoid network-vs-host order bugs { int64_t iOff = m_dBuf.GetLength64(); m_dBuf.AddN ( sizeof(T) ); WriteT ( iOff, tValue ); } }; // RAII Sphinx API block: in ctr reserve place for size, in dtr write hton int into reserved place class APIBlob_c { intptr_t m_iPos = 0; ISphOutputBuffer & m_dOut; public: explicit APIBlob_c ( ISphOutputBuffer& dOut ) : m_dOut ( dOut ) { m_iPos = (intptr_t) dOut.GetSentCount (); dOut.SendInt ( 0 ); } ~APIBlob_c() { auto iBlobLen = m_dOut.GetSentCount ()-m_iPos-sizeof ( int ); m_dOut.WriteInt ( m_iPos, (int) iBlobLen ); } }; // RAII Start Sphinx API command/request header APIBlob_c APIHeader ( ISphOutputBuffer & dBuff, WORD uCommand, WORD uVer = 0 /* SEARCHD_OK */ ); // RAII Sphinx API answer APIBlob_c APIAnswer ( ISphOutputBuffer & dBuff, WORD uVer = 0, WORD uStatus = 0 /* SEARCHD_OK */ ); // buffer that knows if it has requested data or not class SmartOutputBuffer_t final: public ISphOutputBuffer { CSphVector<ISphOutputBuffer *> m_dChunks; public: SmartOutputBuffer_t () = default; ~SmartOutputBuffer_t () final; void StartNewChunk (); // void AppendBuf ( SmartOutputBuffer_t &dBuf ); // void PrependBuf ( SmartOutputBuffer_t &dBuf ); size_t GetIOVec ( CSphVector<sphIovec> &dOut ) const; void Reset(); #if _WIN32 void LeakTo ( CSphVector<ISphOutputBuffer *> dOut ); #endif }; class GenericOutputBuffer_c : public ISphOutputBuffer { public: bool GetError () const { return m_bError; } const CSphString & GetErrorMessage() const { return m_sError; } void ResetError(); void SetProfiler ( QueryProfile_c * pProfiler ) { m_pProfile = pProfiler; } bool Flush () { if ( !SendBuffer ( m_dBuf ) ) return false; m_dBuf.Resize ( 0 ); // check and fix! return true; } virtual bool SendBuffer ( const VecTraits_T<BYTE> & dData ) = 0; virtual void SetWTimeoutUS ( int64_t iTimeoutUS ) = 0; virtual int64_t GetWTimeoutUS () const = 0; virtual int64_t GetTotalSent() const = 0; protected: QueryProfile_c * m_pProfile = nullptr; bool m_bError = false; CSphString m_sError; }; /// generic request buffer class InputBuffer_c { public: InputBuffer_c ( const BYTE * pBuf, int iLen ); InputBuffer_c ( const VecTraits_T<BYTE>& dBuf ); virtual ~InputBuffer_c () {} int GetInt () { return ntohl ( GetT<int> () ); } WORD GetWord () { return ntohs ( GetT<WORD> () ); } DWORD GetDword () { return ntohl ( GetT<DWORD> () ); } DWORD GetLSBDword () { #if USE_LITTLE_ENDIAN return GetT<DWORD> (); #else BYTE dB[4]; GetBytes(dB,4); return dB[0] + ( dB[1]<<8 ) + ( dB[2]<<16 ) + ( dB[3]<<24 ); #endif } uint64_t GetUint64() { uint64_t uRes = GetDword(); return (uRes<<32)+GetDword(); } BYTE GetByte () { return GetT<BYTE> (); } float GetFloat () { return sphDW2F ( ntohl ( GetT<DWORD> () ) ); } float GetDouble () { return sphQW2D ( GetUint64() ); } CSphString GetString (); CSphString GetRawString ( int iLen ); bool GetString ( CSphVector<BYTE> & dBuffer ); bool GetBytes ( void * pBuf, int iLen ); const BYTE * GetBufferPtr () const { return m_pCur; } int GetBufferPos () const { return int ( m_pCur - m_pBuf ); } void SetBufferPos (int iPos) { m_pCur = m_pBuf + iPos; } bool GetBytesZerocopy ( const BYTE ** ppData, int iLen ); bool GetDwords ( CSphVector<DWORD> & dBuffer, int & iGot, int iMax ); bool GetQwords ( CSphVector<SphAttr_t> & dBuffer, int & iGot, int iMax ); inline int HasBytes() const { return int ( m_pBuf - m_pCur + m_iLen ); } bool GetError() const { return m_bError; } const CSphString & GetErrorMessage() const { return m_sError; } void ResetError(); int GetMaxPacketSize() const { return m_iMaxPacketSize; } void SetMaxPacketSize( int iMaxPacketSize ); protected: const BYTE * m_pBuf; const BYTE * m_pCur; int m_iLen; protected: void SetError ( const char * sTemplate, ... ) __attribute__ ( ( format ( printf, 2, 3 ) ) ); bool IsDataSizeValid ( int iSize ); bool IsLessMaxPacket ( int iSize ); template < typename T > T GetT () { if ( m_bError || !IsDataSizeValid ( sizeof( T ) ) ) return 0; T iRes = sphUnalignedRead( *( T* ) const_cast<BYTE*>(m_pCur) ); m_pCur += sizeof( T ); return iRes; } private: CSphString m_sError; bool m_bError = false; int m_iMaxPacketSize = g_iMaxPacketSize; }; /// simple memory request buffer using MemInputBuffer_c = InputBuffer_c; ///////////////////////////////////////////////////////////////////////////// // SERVED INDEX DESCRIPTORS STUFF ///////////////////////////////////////////////////////////////////////////// namespace QueryStats { enum { INTERVAL_1MIN, INTERVAL_5MIN, INTERVAL_15MIN, INTERVAL_ALLTIME, INTERVAL_TOTAL }; enum { TYPE_AVG, TYPE_MIN, TYPE_MAX, TYPE_95, TYPE_99, TYPE_TOTAL, }; } struct QueryStatElement_t { uint64_t m_dData[QueryStats::TYPE_TOTAL] = { 0, UINT64_MAX, 0, 0, 0, }; uint64_t m_uTotalQueries = 0; }; struct QueryStats_t { QueryStatElement_t m_dStats[QueryStats::INTERVAL_TOTAL]; }; struct QueryStatRecord_t { uint64_t m_uQueryTimeMin; uint64_t m_uQueryTimeMax; uint64_t m_uQueryTimeSum; uint64_t m_uFoundRowsMin; uint64_t m_uFoundRowsMax; uint64_t m_uFoundRowsSum; uint64_t m_uTimestamp; int m_iCount; }; class QueryStatContainer_i { public: virtual ~QueryStatContainer_i() {} virtual void Add ( uint64_t uFoundRows, uint64_t uQueryTime, uint64_t uTimestamp ) = 0; virtual QueryStatRecord_t GetRecord ( int iRecord ) const noexcept = 0; virtual int GetNumRecords() const = 0; }; std::unique_ptr<QueryStatContainer_i> MakeStatsContainer(); class ServedStats_c final { public: ServedStats_c(); void AddQueryStat ( uint64_t uFoundRows, uint64_t uQueryTime ); // REQUIRES ( !m_tStatsLock ); /// since mutex is internal, void CalculateQueryStats ( QueryStats_t & tRowsFoundStats, QueryStats_t & tQueryTimeStats ) const EXCLUDES ( m_tStatsLock ); #ifndef NDEBUG void CalculateQueryStatsExact ( QueryStats_t & tRowsFoundStats, QueryStats_t & tQueryTimeStats ) const EXCLUDES ( m_tStatsLock ); #endif private: mutable RwLock_t m_tStatsLock; std::unique_ptr<QueryStatContainer_i> m_pQueryStatRecords GUARDED_BY ( m_tStatsLock ); #ifndef NDEBUG std::unique_ptr<QueryStatContainer_i> m_pQueryStatRecordsExact GUARDED_BY ( m_tStatsLock ); #endif TDigest_c m_tQueryTimeDigest GUARDED_BY ( m_tStatsLock ); TDigest_c m_tRowsFoundDigest GUARDED_BY ( m_tStatsLock ); uint64_t m_uTotalFoundRowsMin GUARDED_BY ( m_tStatsLock )= UINT64_MAX; uint64_t m_uTotalFoundRowsMax GUARDED_BY ( m_tStatsLock )= 0; uint64_t m_uTotalFoundRowsSum GUARDED_BY ( m_tStatsLock )= 0; uint64_t m_uTotalQueryTimeMin GUARDED_BY ( m_tStatsLock )= UINT64_MAX; uint64_t m_uTotalQueryTimeMax GUARDED_BY ( m_tStatsLock )= 0; uint64_t m_uTotalQueryTimeSum GUARDED_BY ( m_tStatsLock )= 0; uint64_t m_uTotalQueries GUARDED_BY ( m_tStatsLock ) = 0; void DoStatCalcStats ( const QueryStatContainer_i * pContainer, QueryStats_t & tRowsFoundStats, QueryStats_t & tQueryTimeStats ) const REQUIRES_SHARED ( m_tStatsLock ); }; void CalcSimpleStats ( const QueryStatContainer_i * pContainer, QueryStats_t & tRowsFoundStats, QueryStats_t & tQueryTimeStats ); // calculate index mass based on status uint64_t CalculateMass ( const CSphIndexStatus & dStats ); struct ServedDesc_t : public ISphRefcountedMT { IndexType_e m_eType = IndexType_e::PLAIN; CSphString m_sIndexPath; ///< current index path; independent but related to one in m_pIndex CSphString m_sGlobalIDFPath; StrVec_t m_dKilllistTargets; CSphString m_sCluster; MutableIndexSettings_c m_tSettings { MutableIndexSettings_c::GetDefaults() }; ServedDesc_t() = default; ServedDesc_t ( const ServedDesc_t& rhs ) : m_eType { rhs.m_eType } , m_sIndexPath { rhs.m_sIndexPath } , m_sGlobalIDFPath { rhs.m_sGlobalIDFPath } , m_dKilllistTargets { rhs.m_dKilllistTargets } , m_sCluster { rhs.m_sCluster } , m_tSettings { rhs.m_tSettings } {} void Swap ( ServedDesc_t& rhs ) noexcept { ::Swap ( m_eType, rhs.m_eType ); ::Swap ( m_sIndexPath, rhs.m_sIndexPath ); ::Swap ( m_sGlobalIDFPath, rhs.m_sGlobalIDFPath ); ::Swap ( m_dKilllistTargets, rhs.m_dKilllistTargets ); ::Swap ( m_sCluster, rhs.m_sCluster ); ::Swap ( m_tSettings, rhs.m_tSettings ); } ServedDesc_t ( ServedDesc_t&& rhs ) noexcept { Swap ( rhs ); } ServedDesc_t& operator= ( ServedDesc_t rhs ) noexcept { Swap ( rhs ); return *this; } // statics instead of members below used to simultaneously check pointer for null also. // mutable is one which can be insert/replace static bool IsMutable ( const ServedDesc_t* pServed ) { return pServed && ( pServed->m_eType == IndexType_e::RT || pServed->m_eType == IndexType_e::PERCOLATE ); } // local is one stored locally on disk static bool IsLocal ( const ServedDesc_t* pServed ) { return pServed && ( IsMutable ( pServed ) || pServed->m_eType == IndexType_e::PLAIN ); } // cluster is one which can deals with replication static bool IsCluster ( const ServedDesc_t* pServed ) { return pServed && !pServed->m_sCluster.IsEmpty(); } // CanSelect is one which supports select ... from (at least full-scan). static bool IsSelectable ( const ServedDesc_t* pServed ) { return pServed && ( IsFT ( pServed ) || pServed->m_eType == IndexType_e::PERCOLATE ); } // FT is one which supports full-text searching static bool IsFT ( const ServedDesc_t* pServed ) { return pServed && ( pServed->m_eType == IndexType_e::PLAIN || pServed->m_eType == IndexType_e::RT || pServed->m_eType == IndexType_e::DISTR ); // fixme! distrs not necessary ft. } }; // wrap CSphIndex into refcounted, trace it finally unlink on dtr (if requested) class RunningIndex_c: public ISphRefcountedMT { mutable Threads::Coro::RWLock_c m_tLock; std::unique_ptr<CSphIndex> m_pIndex GUARDED_BY ( m_tLock ); ///< owned index; will be deleted in d-tr mutable CSphString m_sUnlink; ///< set if we need to unlink the index on destroy. bool m_bLeaked = false; ///< avoid destroying index on dtr (say, if it's ownership changed due to Attach() ) private: ~RunningIndex_c() override; template<typename IDX> friend class RIdx_T; template<typename IDX> friend class WIdx_T; friend class ServedIndex_c; public: Threads::Coro::RWLock_c& Locker() const RETURN_CAPABILITY ( m_tLock ) { return m_tLock; } }; using RunningIndexRefPtr_t = CSphRefcountedPtr<RunningIndex_c>; // wrapped ServedDesc_t - to be served as pointers in containers class ServedIndex_c : public ServedDesc_t { mutable int64_t m_iMass = 0; // relative weight (by access speed) of the index ServedIndex_c() = default; friend CSphRefcountedPtr<ServedIndex_c> MakeServedIndex(); friend CSphIndex* UnlockedHazardIdxFromServed ( const ServedIndex_c& tServed ); // no manual deletion; lifetime managed by AddRef/Release() ~ServedIndex_c () override = default; // available only to friends inline CSphIndex* GetInternalIndexAvoidingLocks () const NO_THREAD_SAFETY_ANALYSIS { if ( !m_pIndex ) return nullptr; return m_pIndex->m_pIndex.get(); } public: RunningIndexRefPtr_t m_pIndex; mutable SharedPtr_t<ServedStats_c> m_pStats; public: // Update index mass for searching. Mass after preread typically will be less. void UpdateMass () const; // Get index mass static uint64_t GetIndexMass ( const ServedIndex_c* pServed ); void SetIdx ( std::unique_ptr<CSphIndex>&& pIndex ); void ReleaseIdx () const; void SetIdxAndStatsFrom ( const ServedIndex_c& tIndex ); void SetStatsFrom ( const ServedIndex_c& tIndex ); void SetUnlink ( CSphString sUnlink ) const; }; using cServedIndexRefPtr_c = CSphRefcountedPtr<const ServedIndex_c>; using ServedIndexRefPtr_c = CSphRefcountedPtr<ServedIndex_c>; ServedIndexRefPtr_c MakeServedIndex(); /// RAII shared reader for CSphIndex* hidden in ServedIndexRefPtr_c template<typename PIDX> class SCOPED_CAPABILITY RIdx_T : ISphNoncopyable { CSphRefcountedPtr<const ISphRefcountedMT> m_pServedKeeper; const RunningIndex_c& m_tRunningIndex; public: // acquire read (shared) lock explicit RIdx_T ( const cServedIndexRefPtr_c& pServed ) ACQUIRE_SHARED ( ( *pServed ).m_pIndex->Locker(), m_tRunningIndex.m_tLock ) : m_pServedKeeper { pServed } , m_tRunningIndex { *pServed->m_pIndex } { assert ( pServed ); m_tRunningIndex.m_tLock.ReadLock(); } RIdx_T ( RIdx_T && rhs ) : m_pServedKeeper ( std::move(rhs.m_pServedKeeper) ) , m_tRunningIndex ( std::move(rhs.m_tRunningIndex) ) {} ~RIdx_T () RELEASE () { m_tRunningIndex.m_tLock.Unlock(); } PIDX Ptr () const NO_THREAD_SAFETY_ANALYSIS { return static_cast<PIDX> ( m_tRunningIndex.m_pIndex.get() ); } PIDX operator-> () const { return Ptr(); } explicit operator bool () const NO_THREAD_SAFETY_ANALYSIS { return m_tRunningIndex.m_pIndex!=nullptr; } operator PIDX () const { return Ptr(); } }; using RIdx_c = RIdx_T<const CSphIndex*>; // read-lock backend, and provide const access using RWIdx_c = RIdx_T<CSphIndex*>; // read-lock backend, and provide non-const access (that is - for inserts, deletes, etc.) /// RAII exclusive writer for CSphIndex* hidden in ServedIndexRefPtr_c template<typename PIDX> class SCOPED_CAPABILITY WIdx_T : ISphNoncopyable { CSphRefcountedPtr<const ISphRefcountedMT> m_pServedKeeper; RunningIndex_c& m_tRunningIndex; public: // acquire write (exclusive) lock explicit WIdx_T ( const cServedIndexRefPtr_c& pServed ) ACQUIRE ( (*pServed).m_pIndex->Locker() ) ACQUIRE ( m_tRunningIndex.m_tLock ) : m_pServedKeeper { pServed } , m_tRunningIndex { *pServed->m_pIndex } { assert ( pServed ); m_tRunningIndex.m_tLock.WriteLock(); } // acquire write (exclusive) lock explicit WIdx_T ( const ServedIndexRefPtr_c& pServed ) ACQUIRE ( ( *pServed ).m_pIndex->Locker() ) ACQUIRE ( m_tRunningIndex.m_tLock ) : m_pServedKeeper { pServed } , m_tRunningIndex { *pServed->m_pIndex } { assert ( pServed ); m_tRunningIndex.m_tLock.WriteLock(); } ~WIdx_T () RELEASE () { m_tRunningIndex.m_tLock.Unlock(); } PIDX Ptr() const NO_THREAD_SAFETY_ANALYSIS { return static_cast<PIDX> ( m_tRunningIndex.m_pIndex.get() ); } PIDX operator-> () const { return Ptr(); } explicit operator bool () const NO_THREAD_SAFETY_ANALYSIS { return m_tRunningIndex.m_pIndex!=nullptr; } operator PIDX () const { return Ptr(); } }; using WIdx_c = WIdx_T<CSphIndex*>; // write-lock backend, and provide full access /// Accessor to naked CSphIndex* hidden in ServedIndex_c. Doesn't use r/w lock, use only to work with free or pre-locked indexes! inline CSphIndex* UnlockedHazardIdxFromServed ( const ServedIndex_c& tServed ) { return tServed.GetInternalIndexAvoidingLocks(); } void LightClone ( ServedIndexRefPtr_c& pTarget, const cServedIndexRefPtr_c& pSource ); void FullClone ( ServedIndexRefPtr_c& pTarget, const cServedIndexRefPtr_c& pSource ); ServedIndexRefPtr_c MakeLightClone ( const cServedIndexRefPtr_c& pSource ); ServedIndexRefPtr_c MakeFullClone ( const cServedIndexRefPtr_c& pSource ); using AddOrReplaceHookFn = std::function<void( const CSphString& )>; template<typename T> using HashOfRefcnt_T = SmallStringHash_T<RefCountedRefPtr_T<T>>; template<typename T> using cHashOfRefcnt_T = SmallStringHash_T<cRefCountedRefPtr_T<T>>; template<typename T> class cRefCountedHashOfRefcnt_T final: public ISphRefcountedMT, public cHashOfRefcnt_T<T> { protected: ~cRefCountedHashOfRefcnt_T() final = default; }; template<typename T = ISphRefcountedMT> class ReadOnlyHash_T { public: using Hash_t = cRefCountedHashOfRefcnt_T<T>; using cRefPtrHash_t = cRefCountedRefPtr_T<cRefCountedHashOfRefcnt_T<T>>; using cRefCountedRefPtr_t = cRefCountedRefPtr_T<T>; using RefCountedRefPtr_t = RefCountedRefPtr_T<T>; using Snapshot_t = std::pair<cRefPtrHash_t, int64_t>; private: mutable RwLock_t m_tLock; // should be very short-term cRefPtrHash_t m_pHash GUARDED_BY ( m_tLock ) { new Hash_t }; int64_t m_iGeneration GUARDED_BY ( m_tLock ) { 0 }; // eliminate ABA race on insert/delete AddOrReplaceHookFn m_pHook = nullptr; template<typename TT> friend class WriteableHash_T; public: Snapshot_t GetSnapshot() const { ScRL_t rLock ( m_tLock ); return { m_pHash, m_iGeneration }; } cRefPtrHash_t GetHash() const { return GetSnapshot().first; } bool IsEmpty() const { ScRL_t rLock ( m_tLock ); return !m_pHash->GetLength(); } int GetLength() const { ScRL_t rLock ( m_tLock ); return m_pHash->GetLength(); } cRefCountedRefPtr_t Get ( const CSphString& sKey ) const { auto pSnap = GetHash(); auto* pEntry = ( *pSnap ) ( sKey ); if ( !pEntry ) return cRefCountedRefPtr_t {}; return *pEntry; } // check if hash contains an entry bool Contains ( const CSphString& sKey ) const { return ( *GetHash() ) ( sKey ) != nullptr; } void SetAddOrReplaceHook ( AddOrReplaceHookFn pHook ) { m_pHook = std::move ( pHook ); } bool Add ( RefCountedRefPtr_t pEntry, const CSphString & sKey ); void AddOrReplace ( RefCountedRefPtr_t pValue, const CSphString & sKey ); bool Replace ( RefCountedRefPtr_t pValue, const CSphString & sKey ); void Delete ( const CSphString &sKey ); void ReleaseAndClear (); void Hook ( const CSphString & sName ) { if ( m_pHook ) m_pHook ( sName ); } }; // created with null set of elems // on d-tr any not-null set will replace the owner // Note, if you want to modify existing set, you NEED to guard some way period between reading old / writing modified template<typename T> class WriteableHash_T { using cRefCountedRefPtr_t = cRefCountedRefPtr_T<T>; using RefCountedRefPtr_t = RefCountedRefPtr_T<T>; using cRefCountedHashOfRefcnt_t = cRefCountedHashOfRefcnt_T<T>; using ReadOnlyHash_t = ReadOnlyHash_T<T>; using RefPtrHash_t = RefCountedRefPtr_T<cRefCountedHashOfRefcnt_t>; using cRefPtrHash_t = cRefCountedRefPtr_T<cRefCountedHashOfRefcnt_t>; public: ReadOnlyHash_t& m_tOwner; RefPtrHash_t m_pNewHash; int64_t m_iGeneration {-1}; // to be different from default read-only generation, which is 0. Threads::Handler m_fnOnHashChanged; WriteableHash_T ( WriteableHash_T&& rhs ) noexcept = default; WriteableHash_T ( ReadOnlyHash_t& tOwner, Threads::Handler&& fnOnHashChanged ) : m_tOwner ( tOwner ) , m_fnOnHashChanged { std::move ( fnOnHashChanged ) } {} explicit WriteableHash_T ( ReadOnlyHash_t& tOwner ) noexcept : m_tOwner ( tOwner ) {} bool TryCommit ( bool bForce=false ) { if ( !m_pNewHash ) return true; { cRefPtrHash_t VARIABLE_IS_NOT_USED hKeeper; // will grab previous hash, so that it will be released outside the lock block. { ScWL_t wLock ( m_tOwner.m_tLock ); if ( !bForce && m_iGeneration!=m_tOwner.m_iGeneration ) return false; // use leak since we convert 'data*' to 'const data*' here. hKeeper = std::exchange ( m_tOwner.m_pHash, m_pNewHash.Leak() ); ++m_tOwner.m_iGeneration; m_iGeneration = -1; } } if ( m_fnOnHashChanged ) m_fnOnHashChanged(); return true; } ~WriteableHash_T() { TryCommit ( true ); } void ResetChanges() // undo all changes (will not commit/change owner anyway) { m_pNewHash = nullptr; m_iGeneration = -1; } void InitEmptyHash () // init with empty - will wipe owner on commit { m_pNewHash = new cRefCountedHashOfRefcnt_t; m_iGeneration = -1; } void CopyOwnerHash() EXCLUDES ( m_tOwner.m_tLock ) // init with copy of owner { InitEmptyHash (); cRefPtrHash_t tHash; std::tie ( tHash, m_iGeneration ) = m_tOwner.GetSnapshot(); for ( const auto& tElem : *tHash ) m_pNewHash->Add ( tElem.second, tElem.first ); } bool Add ( cRefCountedRefPtr_t pEntry, const CSphString& sKey ) { return m_pNewHash->Add ( std::move(pEntry), sKey ); } bool Add ( RefCountedRefPtr_t pEntry, const CSphString& sKey ) { return Add ( cRefCountedRefPtr_t { pEntry }, sKey ); } }; template<typename T> bool ReadOnlyHash_T<T>::Add ( RefCountedRefPtr_t pEntry, const CSphString& sKey ) { bool bSuccess; bool bSuitable = pEntry; WriteableHash_T<T> tChanger { *this }; cRefCountedRefPtr_t pConstEntry { pEntry.Leak() }; do { tChanger.CopyOwnerHash(); bSuccess = tChanger.m_pNewHash->Add ( pConstEntry, sKey ); } while ( !tChanger.TryCommit() ); if ( bSuitable ) Hook ( sKey ); return bSuccess; } template<typename T> void ReadOnlyHash_T<T>::AddOrReplace ( RefCountedRefPtr_t pValue, const CSphString& sKey ) { bool bSuitable = pValue; WriteableHash_T<T> tChanger { *this }; cRefCountedRefPtr_t pConstValue { pValue.Leak() }; do { tChanger.CopyOwnerHash(); auto* pEntry = ( *tChanger.m_pNewHash ) ( sKey ); if ( pEntry ) *pEntry = pConstValue; else Verify ( tChanger.m_pNewHash->Add ( pConstValue, sKey ) ); } while ( !tChanger.TryCommit() ); if ( bSuitable ) Hook ( sKey ); } template<typename T> bool ReadOnlyHash_T<T>::Replace ( RefCountedRefPtr_t pValue, const CSphString& sKey ) { if ( !Contains ( sKey ) ) // short circuit check, will also check in clone later. return false; WriteableHash_T<T> tChanger { *this }; do { tChanger.CopyOwnerHash(); auto* pEntry = ( *tChanger.m_pNewHash ) ( sKey ); if ( !pEntry ) { tChanger.ResetChanges(); return false; } *pEntry = pValue; } while ( !tChanger.TryCommit() ); return true; } template<typename T> void ReadOnlyHash_T<T>::Delete ( const CSphString& sKey ) { WriteableHash_T<T> tChanger { *this }; do { tChanger.CopyOwnerHash(); if ( !tChanger.m_pNewHash->Delete ( sKey ) ) tChanger.ResetChanges(); } while ( !tChanger.TryCommit() ); } template<typename T> void ReadOnlyHash_T<T>::ReleaseAndClear() { WriteableHash_T<T> tChanger { *this }; tChanger.InitEmptyHash(); } using HashOfServed_c = HashOfRefcnt_T<ServedIndex_c>; using VecOfServed_c = CSphVector<HashOfServed_c::KeyValue_t>; using ReadOnlyServedHash_c = ReadOnlyHash_T<ServedIndex_c>; using WriteableServedHash_c = WriteableHash_T<ServedIndex_c>; using ServedSnap_t = typename ReadOnlyServedHash_c::cRefPtrHash_t; extern std::unique_ptr<ReadOnlyServedHash_c> g_pLocalIndexes; // served (local) indexes hash inline cServedIndexRefPtr_c GetServed ( const CSphString &sName ) { return g_pLocalIndexes->Get ( sName ); } class ServedClone_c: ISphNoncopyable { cServedIndexRefPtr_c m_pSource; ServedIndexRefPtr_c m_pTarget; CSphString m_sIndex; public: explicit ServedClone_c ( cServedIndexRefPtr_c pOrigin ) : m_pSource { std::move ( pOrigin ) } {} cServedIndexRefPtr_c& Orig() { return m_pSource; } ServedIndexRefPtr_c& CloneRef() { return m_pTarget; } ServedIndexRefPtr_c& LightCloneOnce(); ServedIndexRefPtr_c& FullCloneOnce(); }; class HashedServedClone_c: public ServedClone_c { CSphString m_sIndex; ReadOnlyServedHash_c* m_pHash = nullptr; public: HashedServedClone_c ( CSphString sIndex, ReadOnlyServedHash_c* pHash ); ~HashedServedClone_c(); }; using ResultAndIndex_t = std::pair<ESphAddIndex, ServedIndexRefPtr_c>; ESphAddIndex ConfigureAndPreloadIndex ( const CSphConfigSection & hIndex, const char * szIndexName, StrVec_t & dWarnings, CSphString & sError ); ResultAndIndex_t AddIndex ( const char * szIndexName, const CSphConfigSection & hIndex, bool bCheckDupe, bool bMutableOpt, StrVec_t * pWarnings, CSphString & sError ); bool PreallocNewIndex ( ServedIndex_c & tIdx, const CSphConfigSection * pConfig, const char * szIndexName, StrVec_t & dWarnings, CSphString & sError ); struct AttrUpdateArgs: public CSphAttrUpdateEx { const CSphQuery* m_pQuery = nullptr; const CSphString* m_pIndexName = nullptr; bool m_bJson = false; }; bool HandleUpdateAPI ( AttrUpdateArgs& tArgs, CSphIndex* pIndex, int& iUpdate ); void HandleMySqlExtendedUpdate ( AttrUpdateArgs& tArgs, const cServedIndexRefPtr_c& pDesc, int& iUpdated, bool bNeedWlock ); enum class RotateFrom_e : BYTE; bool PreloadKlistTarget ( const CSphString& sBase, RotateFrom_e eFrom, StrVec_t& dKlistTarget ); ServedIndexRefPtr_c MakeCloneForRotation ( const cServedIndexRefPtr_c& pSource, const CSphString& sIndex ); bool ConfigureDistributedIndex ( std::function<bool ( const CSphString& )>&& fnCheck, DistributedIndex_t& tIdx, const char * szIndexName, const CSphConfigSection& hIndex, CSphString & sError, StrVec_t* pWarnings = nullptr ); void ConfigureLocalIndex ( ServedDesc_t* pIdx, const CSphConfigSection& hIndex, bool bMutableOpt, StrVec_t* pWarnings ); volatile bool& sphGetSeamlessRotate() noexcept; ///////////////////////////////////////////////////////////////////////////// // SERVED INDEX DESCRIPTORS STUFF ///////////////////////////////////////////////////////////////////////////// struct AgentConn_t; struct DocstoreAndTag_t { union { const DocstoreReader_i * m_pDocstore = nullptr; const AgentConn_t * m_pAgent; }; int m_iTag = 0; // real tag, but high bit is never set. bool m_bTag = false; // boolean tag for remotes inline void Assign ( const DocstoreAndTag_t& rhs ) { m_iTag = rhs.m_iTag; m_bTag = rhs.m_bTag; if ( m_bTag ) m_pAgent = rhs.m_pAgent; else m_pDocstore = rhs.m_pDocstore; } inline const DocstoreReader_i * Docstore() const { return m_bTag ? nullptr : m_pDocstore; } inline const AgentConn_t * Agent () const { return m_bTag ? m_pAgent : nullptr; } }; /// result from one backend (sorter). With own schema and m.b. docstore. Avoid copying of the data. struct OneResultset_t final : public DocstoreAndTag_t { CSphSchema m_tSchema; CSphSwapVector<CSphMatch> m_dMatches; bool m_bTagsAssigned = false; int FillFromSorter ( ISphMatchSorter * pQueue ); void ClampMatches ( int iLimit ); void ClampAllMatches (); ~OneResultset_t(); }; /// specialized swapper inline void Swap ( OneResultset_t & a, OneResultset_t & b ) { a.m_tSchema.Swap( b.m_tSchema ); a.m_dMatches.SwapData ( b.m_dMatches ); Swap ( a.m_bTagsAssigned, b.m_bTagsAssigned ); Swap ( a.m_pDocstore, b.m_pDocstore ); Swap ( a.m_iTag, b.m_iTag ); Swap ( a.m_bTag, b.m_bTag ); } /// result set aggregated across indexes struct AggrResult_t final: CSphQueryResultMeta { CSphSchema m_tSchema; ///< result schema CSphSwapVector<OneResultset_t> m_dResults; ///< everything from backends (local or remote) StrVec_t m_dZeroCount; int m_iOffset = 0; ///< requested offset into matches array int m_iCount = 0; ///< count which will be actually served (computed from total, offset and limit) int m_iSuccesses = 0; bool m_bTagsAssigned = false; // if matches in chunk(s) have assigned tags Debug (bool m_bSingle = false;) // single = only one chunk. False = many chunks Debug (bool m_bOneSchema = false;) // either chunk's schemas are valid, or single result's schema in game. Debug (bool m_bTagsCompacted = false;) // whether tags range is compact or has gaps Debug (bool m_bIdxByTag = false;) // if m_dResults[iTag].m_iTag==iTag is true for all results StrVec_t m_dIndexNames; int GetLength() const; inline bool IsEmpty() const { return GetLength()==0; } bool AddResultset ( ISphMatchSorter * pQueue, const DocstoreReader_i * pDocstore, int iTag, int iCutoff ); void AddEmptyResultset ( const DocstoreReader_i * pDocstore, int iTag ); void ClampMatches ( int iLimit ); void ClampAllMatches(); }; class SearchHandler_c; class PubSearchHandler_c { public: PubSearchHandler_c ( int iQueries, std::unique_ptr<QueryParser_i> pQueryParser, QueryType_e eQueryType, bool bMaster ); ~PubSearchHandler_c(); void RunQueries (); ///< run all queries, get all results void SetQuery ( int iQuery, const CSphQuery & tQuery, std::unique_ptr<ISphTableFunc> pTableFunc ); void SetProfile ( QueryProfile_c * pProfile ); void SetStmt ( SqlStmt_t & tStmt ); AggrResult_t * GetResult ( int iResult ); void PushIndex ( const CSphString& sIndex, const cServedIndexRefPtr_c& pDesc ); void RunCollect( const CSphQuery& tQuery, const CSphString& sIndex, CSphString* pErrors, CSphVector<BYTE>* pCollectedDocs ); private: std::unique_ptr<SearchHandler_c> m_pImpl; }; class CSphSessionAccum { std::optional<RtAccum_t> m_tAcc; public: RtAccum_t * GetAcc ( RtIndex_i * pIndex, CSphString & sError ); RtAccum_t * GetAcc (); RtIndex_i * GetIndex (); }; // from mysqld_error.h enum class EMYSQL_ERR : WORD { UNKNOWN_COM_ERROR = 1047, SERVER_SHUTDOWN = 1053, PARSE_ERROR = 1064, NO_SUCH_THREAD = 1094, FIELD_SPECIFIED_TWICE = 1110, NO_SUCH_TABLE = 1146, TOO_MANY_USER_CONNECTIONS = 1203 }; class RowBuffer_i; class StmtErrorReporter_i { public: virtual ~StmtErrorReporter_i() = default; virtual void Ok ( int iAffectedRows, const CSphString & sWarning, int64_t iLastInsertId ) = 0; virtual void Ok ( int iAffectedRows, int nWarnings=0 ) = 0; virtual void ErrorEx ( EMYSQL_ERR eErr, const char * sError ) = 0; void Error ( const char * sTemplate, ... ); virtual RowBuffer_i * GetBuffer() = 0; virtual bool IsError() const { return false; } virtual const char * GetError() const { return nullptr; } }; class QueryParser_i; class RequestBuilder_i; class ReplyParser_i; std::unique_ptr<QueryParser_i> CreateQueryParser ( bool bJson ); std::unique_ptr<RequestBuilder_i> CreateRequestBuilder ( Str_t sQuery, const SqlStmt_t & tStmt ); std::unique_ptr<ReplyParser_i> CreateReplyParser ( bool bJson, int & iUpdated, int & iWarnings ); StmtErrorReporter_i * CreateHttpErrorReporter(); enum class EHTTP_STATUS : BYTE { _100, _200, _206, _400, _403, _404, _405, _409, _413, _415, _500, _501, _503, _526, }; enum class EHTTP_ENDPOINT : BYTE { INDEX, SQL, JSON_SEARCH, JSON_INDEX, JSON_CREATE, JSON_INSERT, JSON_REPLACE, JSON_UPDATE, JSON_DELETE, JSON_BULK, PQ, CLI, CLI_JSON, ES_BULK, TOTAL }; bool CheckCommandVersion ( WORD uVer, WORD uDaemonVersion, ISphOutputBuffer & tOut ); bool IsMaxedOut (); bool IsReadOnly (); void sphFormatFactors ( StringBuilder_c& dOut, const unsigned int * pFactors, bool bJson ); void sphHandleMysqlInsert ( StmtErrorReporter_i & tOut, const SqlStmt_t & tStmt ); void sphHandleMysqlUpdate ( StmtErrorReporter_i & tOut, const SqlStmt_t & tStmt, Str_t sQuery ); void sphHandleMysqlDelete ( StmtErrorReporter_i & tOut, const SqlStmt_t & tStmt, Str_t sQuery ); void sphHandleMysqlBegin ( StmtErrorReporter_i& tOut, Str_t sQuery ); void sphHandleMysqlCommitRollback ( StmtErrorReporter_i& tOut, Str_t sQuery, bool bCommit ); bool sphCheckWeCanModify (); bool sphCheckWeCanModify ( StmtErrorReporter_i & tOut ); bool sphCheckWeCanModify ( RowBuffer_i& tOut ); bool PollOptimizeRunning ( const CSphString & sIndex ); int GetLogFD (); const CSphString& sphGetLogFile() noexcept; void sphProcessHttpQueryNoResponce ( const CSphString& sEndpoint, const CSphString& sQuery, CSphVector<BYTE> & dResult ); void sphHttpErrorReply ( CSphVector<BYTE> & dData, EHTTP_STATUS eCode, const char * szError ); void LoadCompatHttp ( const char * sData ); void SaveCompatHttp ( JsonEscapedBuilder & tOut ); void SetupCompatHttp(); bool SetLogManagement ( const CSphString & sVal, CSphString & sError ); bool IsLogManagementEnabled (); std::unique_ptr<PubSearchHandler_c> CreateMsearchHandler ( std::unique_ptr<QueryParser_i> pQueryParser, QueryType_e eQueryType, JsonQuery_c & tQuery ); int64_t GetDocID ( const char * szID ); void ExecuteApiCommand ( SearchdCommand_e eCommand, WORD uCommandVer, int iLength, InputBuffer_c & tBuf, GenericOutputBuffer_c & tOut ); void HandleCommandPing ( ISphOutputBuffer & tOut, WORD uVer, InputBuffer_c & tReq ); void BuildStatusOneline ( StringBuilder_c& sOut ); namespace session { bool IsAutoCommit ( const ClientSession_c* ); bool IsInTrans ( const ClientSession_c* ); bool Execute ( Str_t sQuery, RowBuffer_i& tOut ); void SetFederatedUser(); void SetUser ( const CSphString & sUser ); void SetAutoCommit ( bool bAutoCommit ); void SetInTrans ( bool bInTrans ); bool IsAutoCommit(); bool IsInTrans(); QueryProfile_c* StartProfiling ( ESphQueryState ); void SaveLastProfile(); VecTraits_T<int64_t> LastIds(); void SetOptimizeById ( bool bOptimizeById ); bool GetOptimizeById(); void SetDeprecatedEOF ( bool bDeprecatedEOF ); bool GetDeprecatedEOF(); } void LogSphinxqlError ( const char * sStmt, const Str_t & sError ); void LogSphinxqlError ( const Str_t & sStmt, const Str_t & sError ); int GetDaemonLogBufSize (); enum class BuddyQuery_e { SQL, HTTP }; void LogBuddyQuery ( const Str_t sQuery, BuddyQuery_e tType ); // that is used from sphinxql command over API void RunSingleSphinxqlCommand ( Str_t sCommand, GenericOutputBuffer_c & tOut ); std::unique_ptr<ISphTableFunc> CreateRemoveRepeats(); struct PercolateOptions_t { enum MODE { unknown = 0, sparsed = 1, sharded = 2 }; bool m_bGetDocs = false; bool m_bVerbose = false; bool m_bJsonDocs = true; bool m_bGetQuery = false; bool m_bSkipBadJson = false; // don't fail whole call if one doc is bad; warn instead. int m_iShift = 0; MODE m_eMode = unknown; CSphString m_sIdAlias; CSphString m_sIndex; }; struct CPqResult; // defined in sphinxpq.h bool PercolateParseFilters ( const char * sFilters, ESphCollation eCollation, const CSphSchema & tSchema, CSphVector<CSphFilterSettings> & dFilters, CSphVector<FilterTreeItem_t> & dFilterTree, CSphString & sError ); void PercolateMatchDocuments ( const BlobVec_t &dDocs, const PercolateOptions_t &tOpts, CSphSessionAccum &tAcc, CPqResult &tResult ); void SendErrorReply ( ISphOutputBuffer & tOut, const char * sTemplate, ... ); void SetLogHttpFilter ( const CSphString & sVal ); int HttpGetStatusCodes ( EHTTP_STATUS eStatus ) noexcept; EHTTP_STATUS HttpGetStatusCodes ( int iStatus ) noexcept; void HttpBuildReply ( CSphVector<BYTE> & dData, EHTTP_STATUS eCode, const char * sBody, int iBodyLen, bool bHtml ); void HttpBuildReplyHead ( CSphVector<BYTE> & dData, EHTTP_STATUS eCode, const char * sBody, int iBodyLen, bool bHeadReply ); void HttpErrorReply ( CSphVector<BYTE> & dData, EHTTP_STATUS eCode, const char * szError ); using HttpOptionsHash_t = SmallStringHash_T<CSphString>; struct http_parser; enum class Replace_e : bool { NoPlus = false, WithPlus = true }; void UriPercentReplace ( Str_t& sEntity, Replace_e ePlus = Replace_e::WithPlus ); void DumpHttp ( int iReqType, const CSphString & sURL, Str_t sBody ); enum MysqlColumnType_e { MYSQL_COL_DECIMAL = 0, MYSQL_COL_LONG = 3, MYSQL_COL_FLOAT = 4, MYSQL_COL_DOUBLE = 5, MYSQL_COL_LONGLONG = 8, MYSQL_COL_STRING = 254, MYSQL_COL_UINT64 = 508 }; inline constexpr MysqlColumnType_e ESphAttr2MysqlColumn ( ESphAttr eAttrType ) { switch ( eAttrType ) { case SPH_ATTR_INTEGER: case SPH_ATTR_TIMESTAMP: case SPH_ATTR_BOOL: return MYSQL_COL_LONG; case SPH_ATTR_FLOAT: return MYSQL_COL_FLOAT; case SPH_ATTR_DOUBLE: return MYSQL_COL_DOUBLE; case SPH_ATTR_BIGINT: return MYSQL_COL_LONGLONG; case SPH_ATTR_UINT64: return MYSQL_COL_UINT64; default: return MYSQL_COL_STRING; } } // streamed version - used to map columns with streamed select; hacks mysqldump inline constexpr MysqlColumnType_e ESphAttr2MysqlColumnStreamed ( ESphAttr eAttrType ) { switch ( eAttrType ) { case SPH_ATTR_INTEGER: case SPH_ATTR_TIMESTAMP: case SPH_ATTR_BOOL: return MYSQL_COL_LONG; case SPH_ATTR_FLOAT: return MYSQL_COL_FLOAT; case SPH_ATTR_DOUBLE: return MYSQL_COL_DOUBLE; case SPH_ATTR_BIGINT: return MYSQL_COL_LONGLONG; case SPH_ATTR_UINT64: return MYSQL_COL_UINT64; case SPH_ATTR_UINT32SET: case SPH_ATTR_UINT32SET_PTR: case SPH_ATTR_FLOAT_VECTOR: case SPH_ATTR_FLOAT_VECTOR_PTR: case SPH_ATTR_INT64SET: case SPH_ATTR_INT64SET_PTR: return MYSQL_COL_LONG; // long is treated as a number without interpretation (just copied from input to output) case SPH_ATTR_JSON: case SPH_ATTR_JSON_PTR: return MYSQL_COL_DECIMAL; // decimal is treaded as string without internal escaping default: return MYSQL_COL_STRING; } } class RowBuffer_i : public ISphNoncopyable { public: virtual ~RowBuffer_i() {} virtual void PutFloatAsString ( float fVal, const char * sFormat=nullptr ) = 0; virtual void PutDoubleAsString ( double fVal, const char * szFormat=nullptr ) = 0; virtual void PutPercentAsString ( int64_t iVal, int64_t iBase ) { StringBuilder_c sTime; if ( iBase ) sTime.Sprintf ( "%0.2F%%", iVal*10000/iBase ); else sTime << "100%"; PutString ( sTime ); } virtual void PutNumAsString ( int64_t iVal ) = 0; virtual void PutNumAsString ( uint64_t uVal ) = 0; virtual void PutNumAsString ( int iVal ) = 0; virtual void PutNumAsString ( DWORD uVal ) = 0; // pack raw array (i.e. packed length, then blob) virtual void PutArray ( const ByteBlob_t&, bool bSendEmpty = false ) = 0; // pack string virtual void PutString ( Str_t sMsg ) = 0; virtual void PutMicrosec ( int64_t iUsec ) = 0; virtual void PutNULL() = 0; /// more high level. Processing the whole tables. // sends collected data, then reset virtual bool Commit() = 0; // wrappers for popular packets virtual void Eof ( bool bMoreResults, int iWarns, const char* szMeta ) = 0; inline void Eof ( bool bMoreResults , int iWarns ) { return Eof ( bMoreResults, iWarns, nullptr); } inline void Eof ( bool bMoreResults ) { return Eof ( bMoreResults, 0 ); } inline void Eof () { return Eof ( false ); } virtual void Error ( const char * sError, EMYSQL_ERR iErr = EMYSQL_ERR::PARSE_ERROR ) = 0; virtual void Ok ( int iAffectedRows=0, int iWarns=0, const char * sMessage=nullptr, bool bMoreResults=false, int64_t iLastInsertId=0 ) = 0; // Header of the table virtual void HeadBegin () = 0; virtual bool HeadEnd ( bool bMoreResults=false, int iWarns=0 ) = 0; // add the next column. The EOF after the full set will be fired automatically virtual void HeadColumn ( const char * sName, MysqlColumnType_e uType=MYSQL_COL_STRING ) = 0; virtual void Add ( BYTE uVal ) = 0; virtual bool SomethingWasSent() { return false; } // common implementations void PutArray ( const StringBuilder_c & dData, bool bSendEmpty=true ) { PutArray ( (ByteBlob_t)dData, bSendEmpty ); } void PutString ( const char* szMsg ) { PutString ( FromSz ( szMsg ) ); } void PutString ( const CSphString & sMsg ) { PutString ( sMsg.cstr() ); } void PutString ( const StringBuilder_c & sMsg ) { PutString ( (Str_t)sMsg ); } void PutStringf ( const char * szFmt, ... ) { StringBuilder_c sRight; va_list ap; va_start ( ap, szFmt ); sRight.vSprintf ( szFmt, ap ); va_end ( ap ); PutString ( sRight ); } void PutTimeAsString ( int64_t tmVal, const char* szSuffix = nullptr ) { if ( tmVal==-1 ) { PutString ( "none" ); return; } StringBuilder_c sTime; if ( szSuffix ) sTime.Sprintf ("%t%s", tmVal, szSuffix); else sTime.Sprintf ( "%t", tmVal ); PutString ( sTime ); } void PutTimestampAsString ( int64_t tmTimestamp ) { StringBuilder_c sTime; sTime.Sprintf ( "%T", tmTimestamp ); PutString ( sTime ); } void ErrorEx ( const char * sTemplate, ... ) { char sBuf[1024]; va_list ap; va_start ( ap, sTemplate ); vsnprintf ( sBuf, sizeof(sBuf), sTemplate, ap ); va_end ( ap ); Error ( sBuf, EMYSQL_ERR::PARSE_ERROR ); } void ErrorAbsent ( const char * sTemplate, ... ) { char sBuf[1024]; va_list ap; va_start ( ap, sTemplate ); vsnprintf ( sBuf, sizeof ( sBuf ), sTemplate, ap ); va_end ( ap ); Error ( sBuf, EMYSQL_ERR::NO_SUCH_TABLE ); } // popular pattern of 2 columns of data bool DataTuplet ( const char * pLeft, const char * pRight ) { PutString ( pLeft ); PutString ( pRight ); return Commit (); } template <typename NUM> bool DataTuplet ( const char * pLeft, NUM tRight ) { PutString ( pLeft ); PutNumAsString ( tRight ); return Commit(); } bool DataTupletf ( const char * pLeft, const char * sFmt, ... ) { StringBuilder_c sRight; PutString ( pLeft ); va_list ap; va_start ( ap, sFmt ); sRight.vSprintf ( sFmt, ap ); va_end ( ap ); PutString ( sRight ); return Commit(); } // Fire the header for table with given string columns bool HeadOfStrings ( std::initializer_list<const char*> dNames ) { HeadBegin (); for ( const char* szCol : dNames ) HeadColumn ( szCol ); return HeadEnd (); } bool HeadOfStrings ( const VecTraits_T<CSphString>& sNames ) { HeadBegin (); for ( const auto& sName : sNames ) HeadColumn ( sName.cstr() ); return HeadEnd (); } // table of 2 columns (we really often use them!) bool HeadTuplet ( const char * pLeft, const char * pRight ) { HeadBegin (); HeadColumn ( pLeft ); HeadColumn ( pRight ); return HeadEnd(); } bool DataRow ( const VecTraits_T<CSphString>& dRow ) { for ( const auto& dValue : dRow ) PutString ( dValue ); return Commit(); } void DataTable ( const VectorLike& dData ) { if ( !HeadOfStrings ( dData.Header () ) ) return; auto iStride = dData.Header().GetLength(); for ( int i=0, iLen = dData.GetLength(); i<iLen; i+=iStride ) if ( !DataRow ( dData.Slice ( i, iStride ) ) ) break; Eof(); } virtual const CSphString & GetError() const { return m_sError; } virtual bool IsError() const { return m_bError; } void Reset() { m_bError = false; m_sError = ""; } protected: bool m_bError = false; CSphString m_sError; }; #endif // _searchdaemon_
54,231
C++
.h
1,478
34.570365
224
0.711933
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,151
searchnode.h
manticoresoftware_manticoresearch/src/searchnode.h
// // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #ifndef _searchnode_ #define _searchnode_ #include "sphinxquery.h" enum { MAX_BLOCK_DOCS = 32 }; /// query debugging printouts #define QDEBUG 0 struct TermPos_t { WORD m_uQueryPos; WORD m_uAtomPos; }; /// word in the query struct ExtQword_t { CSphString m_sWord; ///< word CSphString m_sDictWord; ///< word as processed by dict int m_iDocs; ///< matching documents int m_iHits; ///< matching hits float m_fIDF; ///< IDF value float m_fBoost; ///< IDF multiplier int m_iQueryPos; ///< position in the query bool m_bExpanded; ///< added by prefix expansion bool m_bExcluded; ///< excluded by the query (eg. bb in (aa AND NOT bb)) }; struct QwordsHash_fn { static inline int Hash ( const CSphString & sKey ) { return sphCRC32 ( sKey.cstr() ); } }; /// query words set using ExtQwordsHash_t = CSphOrderedHash<ExtQword_t, CSphString, QwordsHash_fn, 256>; struct ExtHit_t; struct ExtDoc_t; struct RowIdBoundaries_t; /// generic match streamer class ExtNode_i { public: virtual ~ExtNode_i () {} static ExtNode_i * Create ( const XQNode_t * pNode, const ISphQwordSetup & tSetup, bool bUseBM25, const RowIdBoundaries_t * pBoundaries ); static ExtNode_i * Create ( const XQKeyword_t & tWord, const XQNode_t * pNode, const ISphQwordSetup & tSetup, bool bUseBM25, bool bRowidLimits ); static ExtNode_i * Create ( ISphQword * pQword, const XQNode_t * pNode, const ISphQwordSetup & tSetup, bool bUseBM25, bool bRowidLimits ); static ExtNode_i * Create ( const XQKeyword_t & tWord, const ISphQwordSetup & tSetup, DictRefPtr_c pZonesDict, bool bUseBM25, bool bRowidLimits ); virtual void Reset ( const ISphQwordSetup & tSetup ) = 0; virtual void HintRowID ( RowID_t tRowID ) = 0; virtual const ExtDoc_t * GetDocsChunk() = 0; virtual const ExtHit_t * GetHits ( const ExtDoc_t * pDocs ) = 0; virtual int GetQwords ( ExtQwordsHash_t & hQwords ) = 0; virtual void SetQwordsIDF ( const ExtQwordsHash_t & hQwords ) = 0; virtual void GetTerms ( const ExtQwordsHash_t & hQwords, CSphVector<TermPos_t> & dTermDupes ) const = 0; virtual bool GotHitless () = 0; virtual int GetDocsCount() const { return INT_MAX; } virtual int GetHitsCount() const { return 0; } virtual uint64_t GetWordID () const = 0; ///< for now, only used for duplicate keyword checks in quorum operator virtual void SetAtomPos ( int iPos ) = 0; virtual int GetAtomPos() const = 0; virtual void SetCollectHits() {} // call this if ranker needs hits virtual NodeEstimate_t Estimate ( int64_t iTotalDocs ) const = 0; virtual void SetRowidBoundaries ( const RowIdBoundaries_t & tBoundaries ) = 0; virtual void DebugDump ( int iLevel ) = 0; virtual bool TimeExceeded() const = 0; virtual int64_t GetMaxTimeout() const = 0; }; class RowidIterator_i; std::unique_ptr<ExtNode_i> CreatePseudoFTNode ( ExtNode_i * pNode, RowidIterator_i * pIterator ); class NodeCacheContainer_c; /// intra-batch node cache class CSphQueryNodeCache { friend class NodeCacheContainer_c; public: CSphQueryNodeCache ( int iCells, int MaxCachedDocs, int MaxCachedHits ); ~CSphQueryNodeCache(); ExtNode_i * CreateProxy ( ExtNode_i * pChild, const XQNode_t * pRawChild, const ISphQwordSetup & tSetup ); protected: NodeCacheContainer_c * m_pPool {nullptr}; int m_iMaxCachedDocs {0}; int m_iMaxCachedHits {0}; }; #endif // _searchnode_
3,837
C++
.h
95
38.463158
149
0.720011
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,152
columnarsort.h
manticoresoftware_manticoresearch/src/columnarsort.h
// // Copyright (c) 2021-2024, Manticore Software LTD (https://manticoresearch.com) // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #ifndef _columnarsort_ #define _columnarsort_ #include "sphinxsort.h" ISphMatchSorter * CreateColumnarProxySorter ( ISphMatchSorter * pSorter, int iMaxMatches, const ISphSchema & tSchema, const CSphMatchComparatorState & tState, ESphSortFunc eSortFunc, bool bNeedFactors, bool bComputeItems, bool bMulti ); #endif // _columnarsort_
715
C++
.h
14
49.785714
236
0.780488
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,153
libutils.h
manticoresoftware_manticoresearch/src/libutils.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #pragma once #include "sphinxstd.h" #if _WIN32 #define RTLD_LAZY 0 #define RTLD_NOW 0 #define RTLD_LOCAL 0 #define RTLD_GLOBAL 0 void * dlsym ( void * lib, const char * name ); void * dlopen ( const char * libname, int ); int dlclose ( void * lib ); const char * dlerror(); #else // !_WIN32 #include "config.h" #if HAVE_DLOPEN # include <dlfcn.h> #endif // HAVE_DLOPEN #endif // _WIN32 #if HAVE_DLOPEN #include <utility> class ScopedHandle_c final { public: explicit ScopedHandle_c ( void * pHandle ) : m_pHandle ( pHandle ) {} ~ScopedHandle_c() { if ( m_pHandle ) dlclose ( m_pHandle ); } void * Leak() { return std::exchange ( m_pHandle, nullptr ); } void * Get() { return m_pHandle; } private: void * m_pHandle = nullptr; }; template <typename T> bool LoadFunc ( T & pFunc, void * pHandle, const char * szFunc, const CSphString & sLib, CSphString & sError ) { pFunc = (T) dlsym ( pHandle, szFunc ); if ( !pFunc ) { sError.SetSprintf ( "symbol '%s' not found in '%s'", szFunc, sLib.cstr() ); dlclose ( pHandle ); return false; } return true; } #else template <typename T> bool LoadFunc ( T & pFunc, void * pHandle, const char * szFunc, const CSphString & sLib, CSphString & sError ) { return false; } #endif // HAVE_DLOPEN CSphString TryDifferentPaths ( const CSphString & sLibfile, const CSphString & sFullpath, int iVersion );
1,871
C++
.h
69
25.347826
110
0.702461
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,154
searchdhttp.h
manticoresoftware_manticoresearch/src/searchdhttp.h
// // Copyright (c) 2008-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org // #pragma once #include "sphinxstd.h" #include "searchdaemon.h" #include "http/http_parser.h" using OptionsHash_t = SmallStringHash_T<CSphString>; class AsyncNetInputBuffer_c; class HttpRequestParser_c : public ISphNoncopyable { public: HttpRequestParser_c(); void Reinit(); bool ParseHeader ( ByteBlob_t tData ); bool ProcessClientHttp ( AsyncNetInputBuffer_c& tIn, CSphVector<BYTE>& dResult ); int ParsedBodyLength() const; bool Expect100() const; bool KeepAlive() const; const char* Error() const; bool IsBuddyQuery () const; static void ParseList ( Str_t sData, OptionsHash_t & hOptions ); private: // callbacks int ParserUrl ( Str_t sData ); int ParserHeaderField ( Str_t sData ); int ParserHeaderValue ( Str_t sData ); int ParserBody ( Str_t sData ); int ParseHeaderCompleted (); int MessageComplete(); void FinishParserUrl(); void FinishParserKeyVal(); private: // callbacks static int cbParserUrl ( http_parser* pParser, const char* sAt, size_t iLen ); static int cbParserHeaderField ( http_parser* pParser, const char* sAt, size_t iLen ); static int cbParserHeaderValue ( http_parser* pParser, const char* sAt, size_t iLen ); static int cbParseHeaderCompleted ( http_parser* pParser ); static int cbParserBody ( http_parser* pParser, const char* sAt, size_t iLen ); static int cbMessageComplete ( http_parser* pParser ); static int cbMessageBegin ( http_parser* pParser ); static int cbMessageStatus ( http_parser* pParser, const char* sAt, size_t iLen ); private: bool m_bKeepAlive = false; const char* m_szError = nullptr; CSphString m_sEndpoint; StringBuilder_c m_sUrl; StringBuilder_c m_sCurField; StringBuilder_c m_sCurValue; OptionsHash_t m_hOptions; http_method m_eType = HTTP_GET; bool m_bHeaderDone = false; bool m_bBodyDone = false; CSphVector<Str_t> m_dParsedBodies; int m_iParsedBodyLength; int m_iLastParsed = 0; http_parser_settings m_tParserSettings; http_parser m_tParser; }; void HttpBuildReply ( CSphVector<BYTE>& dData, EHTTP_STATUS eCode, Str_t sReply, bool bHtml ); /////////////////////////////////////////////////////////////////////// /// Stream reader class CharStream_c { protected: bool m_bDone = false; AsyncNetInputBuffer_c * m_pIn; CSphString m_sError; public: CharStream_c ( AsyncNetInputBuffer_c * pIn ) : m_pIn ( pIn ) {} virtual ~CharStream_c() = default; // return next chunk of data virtual Str_t Read() = 0; // return all available data virtual Str_t ReadAll() = 0; inline bool Eof() const noexcept { return m_bDone; } bool GetError() const; const CSphString & GetErrorMessage() const; }; struct HttpProcessResult_t { EHTTP_ENDPOINT m_eEndpoint { EHTTP_ENDPOINT::TOTAL }; EHTTP_STATUS m_eReplyHttpCode = EHTTP_STATUS::_200; bool m_bOk { false }; CSphString m_sError; }; void ReplyBuf ( Str_t sResult, EHTTP_STATUS eStatus, bool bNeedHttpResponse, CSphVector<BYTE> & dData ); HttpProcessResult_t ProcessHttpQuery ( CharStream_c & tSource, Str_t & sSrcQuery, OptionsHash_t & hOptions, CSphVector<BYTE> & dResult, bool bNeedHttpResponse, http_method eRequestType ); namespace bson { class Bson_c; } void ConvertJsonDataset ( const JsonObj_c & tRoot, const char * sStmt, RowBuffer_i & tOut ); using SplitAction_fn = std::function<void(const char *, int)>; void SplitNdJson ( Str_t sBody, SplitAction_fn && fnAction); bool HttpSetLogVerbosity ( const CSphString & sVal ); void LogReplyStatus100(); bool Ends ( const Str_t tVal, const char * sSuffix ); enum class HttpErrorType_e; class HttpHandler_c { public: HttpHandler_c() = default; virtual ~HttpHandler_c() = default; virtual bool Process () = 0; void SetErrorFormat ( bool bNeedHttpResponse ); CSphVector<BYTE> & GetResult(); const CSphString & GetError () const; EHTTP_STATUS GetStatusCode () const; protected: bool m_bNeedHttpResponse {false}; CSphVector<BYTE> m_dData; CSphString m_sError; EHTTP_STATUS m_eHttpCode = EHTTP_STATUS::_200; void ReportError ( const char * szError, EHTTP_STATUS eStatus ); void ReportError ( EHTTP_STATUS eStatus ); void FormatError ( EHTTP_STATUS eStatus, const char * sError, ... ); void BuildReply ( const CSphString & sResult, EHTTP_STATUS eStatus ); void BuildReply ( const char* szResult, EHTTP_STATUS eStatus ); void BuildReply ( Str_t sResult, EHTTP_STATUS eStatus ); void BuildReply ( const StringBuilder_c & sResult, EHTTP_STATUS eStatus ); bool CheckValid ( const ServedIndex_c* pServed, const CSphString& sIndex, IndexType_e eType ); void ReportError ( const char * sError, HttpErrorType_e eType, EHTTP_STATUS eStatus, const char * sIndex=nullptr ); }; class HttpCompatBaseHandler_c : public HttpHandler_c { public: HttpCompatBaseHandler_c ( Str_t sBody, int iReqType, const SmallStringHash_T<CSphString> & hOpts ); protected: Str_t GetBody() const { return m_sBody; } int GetRequestType() const { return m_iReqType; } const CSphString & GetFullURL() const { return m_hOpts["full_url"]; } const SmallStringHash_T<CSphString> & GetOptions() const { return m_hOpts; } const StrVec_t & GetUrlParts() const { return m_dUrlParts; } bool IsHead() { return GetRequestType()==HTTP_HEAD; } void BuildReplyHead ( Str_t sRes, EHTTP_STATUS eStatus ); Str_t m_sBody; int m_iReqType { 0 }; const SmallStringHash_T<CSphString> & m_hOpts; StrVec_t m_dUrlParts; }; std::unique_ptr<HttpHandler_c> CreateCompatHandler ( Str_t sBody, int iReqType, const SmallStringHash_T<CSphString> & hOpts ); enum class HttpErrorType_e { Unknown, Parse, IllegalArgument, ActionRequestValidation, IndexNotFound, ContentParse, VersionConflictEngine, DocumentMissing, ResourceAlreadyExists, AliasesNotFound }; const char * GetErrorTypeName ( HttpErrorType_e eType );
6,202
C++
.h
165
35.733333
187
0.752
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,155
columnarmisc.h
manticoresoftware_manticoresearch/src/columnarmisc.h
// // Copyright (c) 2021-2024, Manticore Software LTD (https://manticoresearch.com) // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #ifndef _columnarmisc_ #define _columnarmisc_ #include "columnarlib.h" #include "schema/locator.h" #include "sphinxexpr.h" using ScopedTypedIterator_t = std::pair<std::unique_ptr<columnar::Iterator_i>,ESphAttr>; template <typename PITERATOR> bool AdvanceIterator ( PITERATOR& pIterator, RowID_t tRowID ) { assert(pIterator); return pIterator->AdvanceTo(tRowID)==tRowID; } CSphVector<ScopedTypedIterator_t> CreateAllColumnarIterators ( const columnar::Columnar_i * pColumnar, const ISphSchema & tSchema ); SphAttr_t SetColumnarAttr ( int iAttr, ESphAttr eType, columnar::Builder_i * pBuilder, std::unique_ptr<columnar::Iterator_i> & pIterator, RowID_t tRowID, CSphVector<int64_t> & dTmp ); void SetDefaultColumnarAttr ( int iAttr, ESphAttr eType, columnar::Builder_i * pBuilder ); struct PlainOrColumnar_t { CSphAttrLocator m_tLocator; int m_iColumnarId = -1; ESphAttr m_eType = SPH_ATTR_NONE; PlainOrColumnar_t() = default; PlainOrColumnar_t ( const CSphColumnInfo & tAttr, int iColumnar ); SphAttr_t Get ( RowID_t tRowID, const CSphRowitem * pRow, CSphVector<ScopedTypedIterator_t> & dIterators ) const; int Get ( RowID_t tRowID, const CSphRowitem * pRow, const BYTE * pPool, CSphVector<ScopedTypedIterator_t> & dIterators, const uint8_t * & pData ) const; }; namespace SI { class Builder_i; } #endif // _columnarmisc_
1,737
C++
.h
39
42.794872
183
0.7623
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,156
searchdssl.h
manticoresoftware_manticoresearch/src/searchdssl.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // /// @file searchdssl.h /// SSL #pragma once #include "networking_daemon.h" #if WITH_SSL // set SSL key, certificate and ca-certificate to be used in SSL, if required. // does NOT anyway initialize SSL library or call any of it's funcitons. void SetServerSSLKeys ( const CSphString & sSslCert, const CSphString & sSslKey, const CSphString & sSslCa ); // Try to initialize SSL, if not yet done. Returns whether it is usable or not (i.e. - no lib, no keys, any error). // used to set 'switch-to-ssl' bit in mysql handshake depending from whether we can do it, or not. bool CheckWeCanUseSSL ( CSphString * pError=nullptr ); // Replace pSource with it's SSL version. // any data not consumed from original source will be considered as part of ssl handshake. bool MakeSecureLayer ( std::unique_ptr<AsyncNetBuffer_c> & pSource ); #else // these stubs work together with NOT including searchdsll.cpp into the final build inline void SetServerSSLKeys ( const CSphString &, const CSphString &, const CSphString & ) {} inline bool CheckWeCanUseSSL ( CSphString * pError=nullptr ) { if ( pError ) *pError="daemon built without SSL support"; return false; } inline bool MakeSecureLayer ( std::unique_ptr<AsyncNetBuffer_c> & ) { return false; } #endif
1,751
C++
.h
36
46.722222
116
0.746487
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,157
conversion.h
manticoresoftware_manticoresearch/src/conversion.h
// // Copyright (c) 2021-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #pragma once #include "sphinxdefs.h" DWORD sphToDword ( const char * s ); int64_t sphToInt64 ( const char * szNumber, CSphString * pError=nullptr ); uint64_t sphToUInt64 ( const char * szNumber, CSphString * pError=nullptr ); uint64_t StrToDocID ( const char * szNumber, CSphString & sError ); float sphToFloat ( const char * s ); /// float vs dword conversion FORCE_INLINE DWORD sphF2DW ( float f ) { union { float f; DWORD d; } u; u.f = f; return u.d; } /// dword vs float conversion FORCE_INLINE float sphDW2F ( DWORD d ) { union { float f; DWORD d; } u; u.d = d; return u.f; } /// double to bigint conversion FORCE_INLINE uint64_t sphD2QW ( double f ) { union { double f; uint64_t d; } u; u.f = f; return u.d; } /// bigint to double conversion FORCE_INLINE double sphQW2D ( uint64_t d ) { union { double f; uint64_t d; } u; u.d = d; return u.f; } template <typename T> FORCE_INLINE T ConvertType ( SphAttr_t tValue ) { return (T)tValue; } template <> FORCE_INLINE float ConvertType<float> ( SphAttr_t tValue ) { return sphDW2F ( (DWORD)tValue ); } template <> FORCE_INLINE double ConvertType<double> ( SphAttr_t tValue ) { return sphQW2D ( (uint64_t)tValue ); }
1,660
C++
.h
41
39.170732
102
0.716594
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,158
sphinxsort.h
manticoresoftware_manticoresearch/src/sphinxsort.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #ifndef _sphinxsort_ #define _sphinxsort_ #include "sortsetup.h" #include "queuecreator.h" namespace columnar { class Columnar_i; } class MatchProcessor_i { public: virtual ~MatchProcessor_i () {} virtual void Process ( CSphMatch * pMatch ) = 0; virtual void Process ( VecTraits_T<CSphMatch *> & dMatches ) = 0; virtual bool ProcessInRowIdOrder() const = 0; }; using GetBlobPoolFromMatch_fn = std::function< const BYTE* ( const CSphMatch * )>; using GetColumnarFromMatch_fn = std::function< columnar::Columnar_i * ( const CSphMatch * )>; /// generic match sorter interface class ISphMatchSorter { public: virtual ~ISphMatchSorter() {} /// check if this sorter does groupby virtual bool IsGroupby() const = 0; /// set match comparator state virtual void SetState ( const CSphMatchComparatorState & tState ) = 0; /// get match comparator stat virtual const CSphMatchComparatorState & GetState() const = 0; /// set group comparator state virtual void SetGroupState ( const CSphMatchComparatorState & ) {} /// set blob pool pointer (for string+groupby sorters) virtual void SetBlobPool ( const BYTE * ) {} /// set columnar (to work with columnar attributes) virtual void SetColumnar ( columnar::Columnar_i * pColumnar ) = 0; /// set sorter schema virtual void SetSchema ( ISphSchema * pSchema, bool bRemapCmp ) = 0; /// get incoming schema virtual const ISphSchema * GetSchema() const = 0; /// base push /// returns false if the entry was rejected as duplicate /// returns true otherwise (even if it was not actually inserted) virtual bool Push ( const CSphMatch & tEntry ) = 0; /// push multiple matches at once virtual void Push ( const VecTraits_T<const CSphMatch> & dMatches ) = 0; /// submit pre-grouped match. bNewSet indicates that the match begins the bunch of matches got from one source virtual bool PushGrouped ( const CSphMatch & tEntry, bool bNewSet ) = 0; /// get rough entries count, due of aggregate filtering phase virtual int GetLength() = 0; /// get total count of non-duplicates Push()ed through this queue virtual int64_t GetTotalCount() const = 0; /// process collected entries up to length count virtual void Finalize ( MatchProcessor_i & tProcessor, bool bCallProcessInResultSetOrder, bool bFinalizeMatches ) = 0; /// store all entries into specified location and remove them from the queue /// entries are stored in properly sorted order /// return sorted entries count, might be less than length due of aggregate filtering phase virtual int Flatten ( CSphMatch * pTo ) = 0; /// get a pointer to the worst element, NULL if there is no fixed location virtual const CSphMatch * GetWorst() const { return nullptr; } /// returns whether the sorter can be cloned to distribute processing over multi threads /// (delete and update sorters are too complex by side effects and can't be cloned) virtual bool CanBeCloned() const { return true; } /// make same sorter (for MT processing) virtual ISphMatchSorter * Clone() const = 0; /// move resultset into target virtual void MoveTo ( ISphMatchSorter * pRhs, bool bCopyMeta ) = 0; /// makes the same sorter virtual void CloneTo ( ISphMatchSorter * pTrg ) const = 0; /// set attributes list these should copied into result set \ final matches virtual void SetFilteredAttrs ( const sph::StringSet & hAttrs, bool bAddDocid ) = 0; /// transform collected matches into standalone (copy all pooled attrs to ptrs, drop unused) /// param fnBlobPoolFromMatch provides pool pointer from currently processed match pointer. virtual void TransformPooled2StandalonePtrs ( GetBlobPoolFromMatch_fn fnBlobPoolFromMatch, GetColumnarFromMatch_fn fnGetColumnarFromMatch, bool bFinalizeSorters ) = 0; virtual void SetRandom ( bool bRandom ) = 0; virtual bool IsRandom() const = 0; virtual int GetMatchCapacity() const = 0; virtual RowTagged_t GetJustPushed() const = 0; virtual VecTraits_T<RowTagged_t> GetJustPopped() const = 0; /// whether we can do implicit cutoff or not (update/delete sorters should disable cutoff) virtual bool IsCutoffDisabled() const { return false; } // tells the sorter whether we are working on a raw index and it can use columnar storage // or it should use the values stored in the matches // used by columnar aggregate functions virtual void SetMerge ( bool bMerge ) = 0; /// is it a sorter that uses precalculated data and does not require real matches? virtual bool IsPrecalc() const { return false; } virtual bool IsJoin() const { return false; } virtual bool FinalizeJoin ( CSphString & sError, CSphString & sWarning ) { return true; } /// add optional description to display in meta virtual void AddDesc ( CSphVector<IteratorDesc_t> & dDesc ) const {} }; struct CmpPSortersByRandom_fn { inline static bool IsLess ( const ISphMatchSorter * a, const ISphMatchSorter * b ) { assert ( a ); assert ( b ); return a->IsRandom()<b->IsRandom(); } }; void SetAccurateAggregationDefault ( bool bEnabled ); bool GetAccurateAggregationDefault(); void SetDistinctThreshDefault ( int iThresh ); int GetDistinctThreshDefault(); int ApplyImplicitCutoff ( const CSphQuery & tQuery, const VecTraits_T<ISphMatchSorter*> & dSorters, bool bFT ); ISphMatchSorter * CreateCollectQueue ( int iMaxMatches, CSphVector<BYTE> & tCollection ); ISphMatchSorter * CreateDirectSqlQueue ( RowBuffer_i * pOutput, void ** ppOpaque1, void ** ppOpaque2, const StrVec_t & dColumns ); ISphMatchSorter * CreatePlainSorter ( ESphSortFunc eMatchFunc, bool bKbuffer, int iMaxMatches, bool bFactors ); struct CSphGroupSorterSettings; struct PrecalculatedSorterResults_t; ISphMatchSorter * CreateSorter ( ESphSortFunc eMatchFunc, ESphSortFunc eGroupFunc, const CSphQuery * pQuery, const CSphGroupSorterSettings & tSettings, bool bHasPackedFactors, bool bHasAggregates, const PrecalculatedSorterResults_t & tPrecalc ); #endif // _sphinxsort_
6,416
C++
.h
123
50.121951
245
0.762286
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,159
sphinxqcache.h
manticoresoftware_manticoresearch/src/sphinxqcache.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #ifndef _sphinxqcache_ #define _sphinxqcache_ #include "sphinxsearch.h" #include "sphinxstd.h" /// cached match is a simple {docid,weight} pair struct QcacheMatch_t { RowID_t m_tRowID; DWORD m_uWeight; }; /// query cache entry /// a compressed list of {docid,weight} pairs class QcacheEntry_c : public ISphRefcountedMT { friend class QcacheRanker_c; ~QcacheEntry_c() override {} public: int64_t m_iIndexId = -1; int64_t m_tmStarted { sphMicroTimer() }; int m_iElapsedMsec = 0; CSphVector<uint64_t> m_dFilters; ///< hashes of the filters that were applied to cached query uint64_t m_Key = 0; int m_iMruPrev = -1; int m_iMruNext = -1; private: static const int MAX_FRAME_SIZE = 32; // commonly used members int m_iTotalMatches = 0;///< total matches CSphTightVector<BYTE> m_dData; ///< compressed frames CSphTightVector<int> m_dWeights; ///< weights table // entry build-time only members CSphVector<QcacheMatch_t> m_dFrame; ///< current compression frame OpenHashTable_T<int, int> m_hWeights; ///< hashed weights RowID_t m_tLastRowID = INVALID_ROWID; ///< last encoded rowid public: void Append ( RowID_t uRowid, DWORD uWeight ); void Finish(); int64_t GetSize() const { return sizeof(*this) + m_dFilters.AllocatedBytes() + m_dData.AllocatedBytes() + m_dWeights.AllocatedBytes(); } void RankerReset(); private: void FlushFrame(); }; using QcacheEntryRefPtr_t = CSphRefcountedPtr<QcacheEntry_c>; /// query cache status struct QcacheStatus_t { // settings that can be changed int64_t m_iMaxBytes; ///< max RAM bytes int m_iThreshMs; ///< minimum wall time to cache, in msec int m_iTtlS; ///< cached query TTL, in msec // report-only statistics int m_iCachedQueries; ///< cached queries counts int64_t m_iUsedBytes; ///< used RAM bytes int64_t m_iHits; ///< cache hits }; void QcacheAdd ( const CSphQuery & q, QcacheEntry_c * pResult, const ISphSchema & tSorterSchema ); QcacheEntry_c * QcacheFind ( int64_t iIndexId, const CSphQuery & q, const ISphSchema & tSorterSchema ); std::unique_ptr<ISphRanker> QcacheRanker ( QcacheEntry_c * pEntry, const ISphQwordSetup & tSetup ); const QcacheStatus_t & QcacheGetStatus(); void QcacheSetup ( int64_t iMaxBytes, int iThreshMsec, int iTtlSec ); void QcacheDeleteIndex ( int64_t iIndexId ); #endif // _sphinxqcache_
2,896
C++
.h
73
37.986301
142
0.715609
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,160
compressed_zstd_mysql.h
manticoresoftware_manticoresearch/src/compressed_zstd_mysql.h
// // Copyright (c) 2021-2024, Manticore Software LTD (https://manticoresearch.com) // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #pragma once #include "networking_daemon.h" #if WITH_ZSTD bool IsZstdCompressionAvailable(); // Replace pSource with it's compressed version. // Mysql proto will be wrapped into compressed. void MakeZstdMysqlCompressedLayer ( std::unique_ptr<AsyncNetBuffer_c>& pSource, int iLevel ); #else inline bool IsZstdCompressionAvailable() { return false; } inline void MakeZstdMysqlCompressedLayer ( std::unique_ptr<AsyncNetBuffer_c>& pSource, int iLevel ) { }; #endif
846
C++
.h
20
41
104
0.776829
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,161
indexformat.h
manticoresoftware_manticoresearch/src/indexformat.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #ifndef _indexformat_ #define _indexformat_ #include "sphinxstd.h" #include "sphinxsearch.h" #include "datareader.h" #include "fileutils.h" #include "indexing_sources/source_stats.h" #include "dict/dict_entry.h" #include "dict/infix/infix_builder.h" const int DOCLIST_HINT_THRESH = 256; const DWORD HITLESS_DOC_MASK = 0x7FFFFFFF; const DWORD HITLESS_DOC_FLAG = 0x80000000; #define UnzipWordidBE UnzipOffsetBE class DiskIndexQwordSetup_c; /// query word from the searcher's point of view class DiskIndexQwordTraits_c : public ISphQword { public: /// tricky bit /// m_uHitPosition is always a current position in the .spp file /// base ISphQword::m_iHitlistPos carries the inlined hit data when m_iDocs==1 /// but this one is always a real position, used for delta coding SphOffset_t m_uHitPosition = 0; CSphMatch m_tDoc; ///< current match (partial) FileBlockReaderPtr_c m_rdDoclist; ///< my doclist accessor FileBlockReaderPtr_c m_rdHitlist; ///< my hitlist accessor DiskIndexQwordTraits_c ( bool bUseMini, bool bExcluded ); void SetDocReader ( DataReaderFactory_c * pReader ); void SetHitReader ( DataReaderFactory_c * pReader ); void ResetDecoderState(); virtual bool Setup ( const DiskIndexQwordSetup_c * pSetup ) = 0; protected: Hitpos_t m_uInlinedHit {0}; DWORD m_uHitState = 0; Hitpos_t m_iHitPos {EMPTY_HIT}; ///< current hit postition, from hitlist static const int MINIBUFFER_LEN = 1024; BYTE m_dHitlistBuf[MINIBUFFER_LEN]; BYTE m_dDoclistBuf[MINIBUFFER_LEN]; BYTE * m_pHitsBuf = nullptr; BYTE * m_pDocsBuf = nullptr; #ifndef NDEBUG bool m_bHitlistOver = true; #endif }; struct CSphWordlistCheckpoint { union { SphWordID_t m_uWordID; const char * m_szWord; }; SphOffset_t m_iWordlistOffset; }; int DoclistHintUnpack ( DWORD uDocs, BYTE uHint ); // dictionary header struct DictHeader_t { int m_iDictCheckpoints = 0; ///< how many dict checkpoints (keyword blocks) are there SphOffset_t m_iDictCheckpointsOffset = 0; ///< dict checkpoints file position int m_iInfixCodepointBytes = 0; ///< max bytes per infix codepoint (0 means no infixes) int64_t m_iInfixBlocksOffset = 0; ///< infix blocks file position (stored as unsigned 32bit int as keywords dictionary is pretty small) int m_iInfixBlocksWordsSize = 0; ///< infix checkpoints size }; class CheckpointReader_c; // FIXME: eliminate this, move it to proper dict impls class CWordlist : public ISphWordlist, public DictHeader_t, public ISphWordlistSuggest { public: // !COMMIT slow data CSphMappedBuffer<BYTE> m_tBuf; ///< my cache CSphFixedVector<CSphWordlistCheckpoint> m_dCheckpoints {0}; ///< checkpoint offsets ~CWordlist () override; void Reset(); bool Preread ( const CSphString & sName, bool bWordDict, int iSkiplistBlockSize, CSphString & sError ); const CSphWordlistCheckpoint * FindCheckpointCrc ( SphWordID_t iWordID ) const; const CSphWordlistCheckpoint * FindCheckpointWrd ( const char * sWord, int iWordLen, bool bStarMode ) const; bool GetWord ( const BYTE * pBuf, SphWordID_t iWordID, DictEntry_t & tWord ) const; const BYTE * AcquireDict ( const CSphWordlistCheckpoint * pCheckpoint ) const; void GetPrefixedWords ( const char * sSubstring, int iSubLen, const char * sWildcard, Args_t & tArgs ) const override; void GetInfixedWords ( const char * sSubstring, int iSubLen, const char * sWildcard, Args_t & tArgs ) const override; void ScanRegexWords ( const VecTraits_T<RegexTerm_t> & dTerms, const ISphWordlist::Args_t & tArgs, const VecExpandConv_t & dConverters ) const override; void SuffixGetChekpoints ( const SuggestResult_t & tRes, const char * sSuffix, int iLen, CSphVector<DWORD> & dCheckpoints ) const override; void SetCheckpoint ( SuggestResult_t & tRes, DWORD iCP ) const override; bool ReadNextWord ( SuggestResult_t & tRes, DictWord_t & tWord ) const override; SphOffset_t GetWordsEnd() const { return m_iWordsEnd; } void DebugPopulateCheckpoints(); private: bool m_bWordDict = false; CSphVector<InfixBlock_t> m_dInfixBlocks {0}; CSphFixedVector<BYTE> m_pWords {0}; ///< arena for checkpoint's words BYTE * m_pInfixBlocksWords = nullptr; ///< arena for infix checkpoint's words int m_iSkiplistBlockSize {0}; SphOffset_t m_iWordsEnd = 0; ///< end of wordlist CheckpointReader_c * m_pCpReader = nullptr; }; /// dict=keywords block reader class KeywordsBlockReader_c : public DictEntry_t { public: KeywordsBlockReader_c ( const BYTE * pBuf, int iSkiplistBlockSize ); void Reset ( const BYTE * pBuf ); bool UnpackWord(); const char * GetWord() const { return (const char*)m_sWord.data(); } int GetWordLen() const { return m_iLen; } private: const BYTE * m_pBuf; std::array<BYTE, MAX_KEYWORD_BYTES> m_sWord; int m_iLen; BYTE m_uHint = 0; int m_iSkiplistBlockSize = 0; }; // header of a disk index or chunk struct BuildHeader_t : public CSphSourceStats, public DictHeader_t { BuildHeader_t() = default; explicit BuildHeader_t ( const CSphSourceStats & tStat ) { m_iTotalDocuments = tStat.m_iTotalDocuments; m_iTotalBytes = tStat.m_iTotalBytes; } int64_t m_iDocinfo {0}; int64_t m_iDocinfoIndex {0}; int64_t m_iMinMaxIndex {0}; }; struct WriteHeader_t { const CSphIndexSettings * m_pSettings; const CSphSchema * m_pSchema; TokenizerRefPtr_c m_pTokenizer; DictRefPtr_c m_pDict; const ISphFieldFilter * m_pFieldFilter; const int64_t * m_pFieldLens; const SIContainer_c * m_pSI = nullptr; }; void IndexWriteHeader ( const BuildHeader_t & tBuildHeader, const WriteHeader_t & tWriteHeader, JsonEscapedBuilder& sJson, bool bForceWordDict, bool SkipEmbeddDict=false ); #endif // _indexformat_
6,313
C++
.h
147
40.938776
172
0.736894
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,162
attrindex_merge.h
manticoresoftware_manticoresearch/src/attrindex_merge.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #pragma once #include "sphinx.h" #include "indexformat.h" struct BuildBufferSettings_t; class AttrMerger_c { class Impl_c; std::unique_ptr<Impl_c> m_pImpl; public: AttrMerger_c ( MergeCb_c& tMonitor, CSphString& sError, int64_t iTotalDocs, const BuildBufferSettings_t & tSettings ); ~AttrMerger_c(); bool Prepare ( const CSphIndex * pSrcIndex, const CSphIndex * pDstIndex ); bool CopyAttributes ( const CSphIndex & tIndex, const VecTraits_T<RowID_t> & dRowMap, DWORD uAlive ); bool FinishMergeAttributes ( const CSphIndex * pDstIndex, BuildHeader_t & tBuildHeader, StrVec_t* pCreatedFiles ); }; bool SiRecreate ( MergeCb_c & tMonitor, const CSphIndex & tIndex, int64_t iNumDocs, StrVec_t & dOldFiles, StrVec_t & dNewFiles, CSphString & sError );
1,236
C++
.h
27
44.259259
150
0.760399
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,163
queryfilter.h
manticoresoftware_manticoresearch/src/queryfilter.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #pragma once #include "tokenizer/tokenizer.h" #include "sphinxint.h" struct ISphQueryFilter { TokenizerRefPtr_c m_pTokenizer; DictRefPtr_c m_pDict; const CSphIndexSettings* m_pSettings = nullptr; GetKeywordsSettings_t m_tFoldSettings; virtual ~ISphQueryFilter() = default; void GetKeywords ( CSphVector<CSphKeywordInfo> & dKeywords, ExpansionContext_t & tCtx ); virtual void AddKeywordStats ( BYTE* sWord, const BYTE* sTokenized, int iQpos, CSphVector<CSphKeywordInfo>& dKeywords ) = 0; }; struct CSphTemplateQueryFilter: public ISphQueryFilter { void AddKeywordStats ( BYTE* sWord, const BYTE* sTokenized, int iQpos, CSphVector<CSphKeywordInfo>& dKeywords ) final; }; class ISphQwordSetup; class ISphQword; struct CSphPlainQueryFilter : public ISphQueryFilter { const ISphQwordSetup * m_pTermSetup; ISphQword * m_pQueryWord; void AddKeywordStats ( BYTE * sWord, const BYTE * sTokenized, int iQpos, CSphVector <CSphKeywordInfo> & dKeywords ) override; }; struct KeywordSorter_fn { bool IsLess ( const CSphKeywordInfo & a, const CSphKeywordInfo & b ) const { return ( ( a.m_iQpos<b.m_iQpos ) || ( a.m_iQpos==b.m_iQpos && a.m_iHits>b.m_iHits ) || ( a.m_iQpos==b.m_iQpos && a.m_iHits==b.m_iHits && a.m_sNormalized<b.m_sNormalized ) ); } }; void UniqKeywords ( CSphVector<CSphKeywordInfo> & dSrc );
1,808
C++
.h
46
37.565217
126
0.760571
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,164
sphinxql_debug.h
manticoresoftware_manticoresearch/src/sphinxql_debug.h
// // Copyright (c) 2021-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #pragma once #include "std/ints.h" #include "std/string.h" #include "searchdsql.h" namespace DebugCmd { enum class Cmd_e : BYTE { SHUTDOWN = 0, CRASH, TOKEN, MALLOC_STATS, MALLOC_TRIM, PROCDUMP, SETGDB, GDBSTATUS, SLEEP, TASKS, SCHED, MERGE, DROP, FILES, CLOSE, COMPRESS, DEDUP, SPLIT, WAIT, WAIT_STATUS, META, TRACE, CURL, PAUSE, INVALID_CMD, PARSE_SYNTAX_ERROR, }; struct DebugCommand_t { Cmd_e m_eCommand {Cmd_e::PARSE_SYNTAX_ERROR}; CSphString m_sParam; CSphString m_sParam2; int64_t m_iPar1 = -1; int64_t m_iPar2; const char * m_szStmt; SmallStringHash_T<ParsedOption_t> m_hOptions; bool bOpt ( const char * szName, bool bDefault = false ) const; int64_t iOpt ( const char * szName, int64_t iDefault = 0 ) const; float fOpt ( const char * szName, float fDefault = 0.0 ) const; CSphString sOpt ( const char * szName, const char* szDefault = nullptr ) const; [[nodiscard]] inline bool Valid() const noexcept { return m_eCommand != Cmd_e::PARSE_SYNTAX_ERROR; }; }; } // namespace DebugCmd; ParseResult_e ParseDebugCmd ( Str_t sQuery, CSphVector<SqlStmt_t>& dStmt, CSphString& sError );
1,612
C++
.h
62
24.225806
102
0.738312
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,165
schematransform.h
manticoresoftware_manticoresearch/src/schematransform.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #pragma once #include "sphinxsort.h" class TransformedSchemaBuilder_c { public: TransformedSchemaBuilder_c ( const ISphSchema & tOldSchema, CSphSchema & tNewSchema ); void AddAttr ( const CSphString & sName ); void Finalize(); private: const ISphSchema & m_tOldSchema; CSphSchema & m_tNewSchema; void ReplaceColumnarAttrWithExpression ( CSphColumnInfo & tAttr, int iLocator ); }; void RemapNullMask ( VecTraits_T<CSphMatch> & dMatches, const CSphSchema & tOldSchema, CSphSchema & tNewSchema ); int GetStringRemapCount ( const ISphSchema & tDstSchema, const ISphSchema & tSrcSchema ); MatchProcessor_i * CreateMatchSchemaTransform ( const ISphSchema * pOldSchema, const ISphSchema * pNewSchema, GetBlobPoolFromMatch_fn fnGetBlobPool, GetColumnarFromMatch_fn fnGetColumnar );
1,274
C++
.h
27
45.592593
189
0.781275
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,166
sphinxsearch.h
manticoresoftware_manticoresearch/src/sphinxsearch.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #ifndef _sphinxsearch_ #define _sphinxsearch_ #include "sphinxquery.h" #include "sphinxint.h" #include "client_task_info.h" ////////////////////////////////////////////////////////////////////////// /// term modifiers enum TermPosFilter_e { TERM_POS_NONE = 0, TERM_POS_FIELD_LIMIT = 1, TERM_POS_FIELD_START = 2, TERM_POS_FIELD_END = 3, TERM_POS_FIELD_STARTEND = 4, TERM_POS_ZONES = 5, }; /// decoder state saved at a certain offset struct SkiplistEntry_t { RowID_t m_tBaseRowIDPlus1; ///< delta decoder rowid base (stored as base rowid + 1) int64_t m_iOffset; ///< offset in the doclist file (relative to the doclist start) int64_t m_iBaseHitlistPos; ///< delta decoder hitlist offset base }; bool operator < ( const SkiplistEntry_t & a, RowID_t b ); bool operator == ( const SkiplistEntry_t & a, RowID_t b ); bool operator < ( RowID_t a, const SkiplistEntry_t & b ); struct DictEntry_t; struct SkipData_t { CSphVector<SkiplistEntry_t> m_dSkiplist; void Read ( const BYTE * pSkips, const DictEntry_t & tRes, int iDocs, int iSkipBlockSize ); }; class RtIndex_c; struct RtGuard_t; /// term, searcher view class ISphQword { public: // setup by query parser CSphString m_sWord; ///< my copy of word CSphString m_sDictWord; ///< word after being processed by dict (eg. stemmed) SphWordID_t m_uWordID = 0; ///< word ID, from dictionary TermPosFilter_e m_iTermPos = TERM_POS_NONE; int m_iAtomPos = 0; ///< word position, from query float m_fBoost = 1.0f;///< IDF keyword boost (multiplier) bool m_bExpanded = false; ///< added by prefix expansion bool m_bExcluded = false; ///< excluded by the query (rval to operator NOT) // setup by QwordSetup() int m_iDocs = 0; ///< document count, from wordlist int m_iHits = 0; ///< hit count, from wordlist bool m_bHasHitlist = true; ///< hitlist presence flag SkipData_t * m_pSkipData = nullptr; bool m_bSkipFromCache = false; // iterator state FieldMask_t m_dQwordFields; ///< current match fields DWORD m_uMatchHits = 0; ///< current match hits count SphOffset_t m_iHitlistPos = 0; ///< current position in hitlist, from doclist protected: bool m_bAllFieldsKnown = false; ///< whether the all match fields is known, or only low 32. public: ISphQword () { m_dQwordFields.UnsetAll(); } virtual ~ISphQword () { assert ( !m_bSkipFromCache ); SafeDelete(m_pSkipData); } virtual RowID_t AdvanceTo ( RowID_t tRowID ); virtual bool HintRowID ( RowID_t ) { return false; } virtual const CSphMatch & GetNextDoc() = 0; virtual void SeekHitlist ( SphOffset_t uOff ) = 0; virtual Hitpos_t GetNextHit () = 0; virtual void CollectHitMask (); virtual void Reset(); int GetAtomPos() const; virtual bool SetupScan ( const RtIndex_c * pIndex, int iSegment, const RtGuard_t& tGuard ) { return false; } }; /// term setup, searcher view class CSphQueryNodeCache; class ISphZoneCheck; struct CSphQueryStats; class ISphQwordSetup : ISphNoncopyable { public: const CSphIndex * m_pIndex {nullptr}; int m_iDynamicRowitems {0}; int64_t m_iMaxTimer {0}; CSphString * m_pWarning {nullptr}; CSphQueryContext * m_pCtx {nullptr}; CSphQueryNodeCache * m_pNodeCache {nullptr}; mutable ISphZoneCheck * m_pZoneChecker {nullptr}; CSphQueryStats * m_pStats {nullptr}; mutable bool m_bSetQposMask {false}; DictRefPtr_c m_pDict; bool m_bHasWideFields { false }; virtual ~ISphQwordSetup () {} virtual ISphQword * QwordSpawn ( const XQKeyword_t & tWord ) const = 0; virtual bool QwordSetup ( ISphQword * pQword ) const = 0; inline void SetDict ( DictRefPtr_c pDict ) { m_pDict = std::move ( pDict ); } inline DictRefPtr_c Dict() const { return m_pDict; } virtual ISphQword * ScanSpawn() const = 0; }; /// generic ranker interface class ISphRanker : public ISphExtra { public: virtual CSphMatch * GetMatchesBuffer() = 0; virtual int GetMatches () = 0; virtual void Reset ( const ISphQwordSetup & tSetup ) = 0; virtual bool IsCache() const { return false; } virtual void FinalizeCache ( const ISphSchema & ) {} virtual NodeEstimate_t Estimate ( int64_t iTotalDocs ) const = 0; }; /// factory std::unique_ptr<ISphRanker> sphCreateRanker ( const XQQuery_t & tXQ, const CSphQuery & tQuery, CSphQueryResultMeta & tMeta, const ISphQwordSetup & tTermSetup, const CSphQueryContext & tCtx, const ISphSchema & tSorterSchema ); class QwordScan_c : public ISphQword { public: QwordScan_c ( int iRowsCount ); const CSphMatch & GetNextDoc() final; void SeekHitlist ( SphOffset_t uOff ) override {} Hitpos_t GetNextHit () override { return EMPTY_HIT; } protected: RowID_t m_iRowsCount = INVALID_ROWID; bool m_bDone = false; CSphMatch m_tDoc; virtual bool IsAliveRow ( RowID_t ) const { return true; } }; ////////////////////////////////////////////////////////////////////////// /// hit mark, used for snippets generation struct SphHitMark_t { DWORD m_uPosition; DWORD m_uSpan; bool operator == ( const SphHitMark_t & rhs ) const { return m_uPosition==rhs.m_uPosition && m_uSpan==rhs.m_uSpan; } }; /// hit marker, used for snippets generation class CSphHitMarker { public: class ExtNode_i * m_pRoot; public: CSphHitMarker() : m_pRoot ( NULL ) {} ~CSphHitMarker(); void Mark ( CSphVector<SphHitMark_t> & ); static CSphHitMarker * Create ( const XQNode_t * pRoot, const ISphQwordSetup & tSetup ); }; ////////////////////////////////////////////////////////////////////////// CSphString sphXQNodeToStr ( const XQNode_t * pNode ); Bson_t sphExplainQuery ( const XQNode_t * pNode, const CSphSchema & tSchema, const StrVec_t & dZones ); namespace sph { void RenderBsonPlan ( StringBuilder_c& tRes, const bson::NodeHandle_t & dBson, bool bDot ); CSphString RenderBsonPlanBrief ( const bson::NodeHandle_t & dBson ); } struct ExplainQueryArgs_t { const char * m_szQuery = nullptr; const CSphSchema * m_pSchema = nullptr; DictRefPtr_c m_pDict; std::unique_ptr<ISphFieldFilter> m_pFieldFilter; const CSphIndexSettings * m_pSettings = nullptr; TokenizerRefPtr_c m_pQueryTokenizer; const ISphWordlist * m_pWordlist = nullptr; int m_iExpandKeywords = 0; int m_iExpansionLimit = 0; bool m_bExpandPrefix = false; cRefCountedRefPtrGeneric_t m_pIndexData; const CSphBitvec * m_pMorphFields { nullptr }; }; Bson_t Explain ( ExplainQueryArgs_t & tArgs ); class WordlistStub_c : public ISphWordlist { public: WordlistStub_c() {} void GetPrefixedWords ( const char * , int , const char * , ISphWordlist::Args_t & ) const override {} void GetInfixedWords ( const char * , int , const char * , ISphWordlist::Args_t & ) const override {} void ScanRegexWords ( const VecTraits_T<RegexTerm_t> & dTerms, const ISphWordlist::Args_t & tArgs, const VecExpandConv_t & dConverters ) const override {} }; #endif // _sphinxsearch_
7,348
C++
.h
199
35.035176
225
0.703845
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,167
sortsetup.h
manticoresoftware_manticoresearch/src/sortsetup.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #ifndef _sortsetup_ #define _sortsetup_ #include "match.h" #include "sphinx.h" /// match comparator state struct CSphMatchComparatorState { static const int MAX_ATTRS = 5; ESphSortKeyPart m_eKeypart[MAX_ATTRS]; ///< sort-by key part type CSphAttrLocator m_tLocator[MAX_ATTRS]; ///< sort-by attr locator int m_dAttrs[MAX_ATTRS]; ///< sort-by attr index DWORD m_uAttrDesc = 0; ///< sort order mask (if i-th bit is set, i-th attr order is DESC) DWORD m_iNow = 0; ///< timestamp (for timesegments sorting mode) SphStringCmp_fn m_fnStrCmp = nullptr; ///< string comparator CSphBitvec m_dRemapped { CSphMatchComparatorState::MAX_ATTRS }; CSphMatchComparatorState(); /// check if any of my attrs are bitfields bool UsesBitfields() const; void FixupLocators ( const ISphSchema * pOldSchema, const ISphSchema * pNewSchema, bool bRemapKeyparts ); FORCE_INLINE int CmpStrings ( const CSphMatch & a, const CSphMatch & b, int iAttr ) const { assert ( iAttr>=0 && iAttr<MAX_ATTRS ); assert ( m_eKeypart[iAttr]==SPH_KEYPART_STRING || m_eKeypart[iAttr]==SPH_KEYPART_STRINGPTR ); assert ( m_fnStrCmp ); const BYTE * aa = (const BYTE*) a.GetAttr ( m_tLocator[iAttr] ); const BYTE * bb = (const BYTE*) b.GetAttr ( m_tLocator[iAttr] ); if ( aa==nullptr || bb==nullptr ) { if ( aa==bb ) return 0; if ( aa==nullptr ) return -1; return 1; } return m_fnStrCmp ( {aa, 0}, {bb, 0}, m_eKeypart[iAttr]==SPH_KEYPART_STRINGPTR ); } }; struct ExtraSortExpr_t { CSphRefcountedPtr<ISphExpr> m_pExpr; JsonKey_t m_tKey; ESphAttr m_eType = SPH_ATTR_NONE; }; /// parses sort clause, using a given schema /// fills eFunc and tState and optionally sError, returns result code ESortClauseParseResult sphParseSortClause ( const CSphQuery & tQuery, const char * sClause, const ISphSchema & tSchema, ESphSortFunc & eFunc, CSphMatchComparatorState & tState, CSphVector<ExtraSortExpr_t> & dExtraExprs, bool bComputeItems, const JoinArgs_t * pJoinArgs, CSphString & sError ); #endif // _sortsetup_
2,539
C++
.h
58
41.534483
292
0.719092
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,168
loop_profiler.h
manticoresoftware_manticoresearch/src/loop_profiler.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // // specific profiler with vtune used for profiling daemon's network loop #pragma once // vtune #ifdef USE_VTUNE #include "ittnotify.h" #if _WIN32 #pragma comment(linker, "/defaultlib:libittnotify.lib") #pragma message("Automatically linking with libittnotify.lib") #endif #endif extern bool g_bVtune; extern int64_t g_tmStarted; struct LoopProfiler_t { #ifdef USE_VTUNE __itt_domain * m_pDomain; __itt_string_handle * m_pTaskPoll; __itt_string_handle * m_pTaskTick; __itt_string_handle * m_pTaskActions; __itt_string_handle * m_pTaskAT; __itt_string_handle * m_pTaskAR; __itt_string_handle * m_pTaskRemove; __itt_string_handle * m_pTaskNext; __itt_string_handle * m_pTaskExt; __itt_string_handle * m_pTaskClean; __itt_string_handle * m_pTaskStat; #endif bool m_bEnable; int64_t m_tmTotal = 0; int m_iPerfEv=0, m_iPerfNext=0, m_iPerfExt=0, m_iPerfClean=0; LoopProfiler_t () { m_bEnable = g_bVtune; #ifdef USE_VTUNE __itt_thread_set_name ( "net-loop" ); m_pDomain = __itt_domain_create ( "Task Domain" ); m_pTaskPoll = __itt_string_handle_create ( "poll" ); m_pTaskTick = __itt_string_handle_create ( "tick" ); m_pTaskActions = __itt_string_handle_create ( "actions" ); m_pTaskAT = __itt_string_handle_create ( "Ta" ); m_pTaskAR = __itt_string_handle_create ( "ra" ); m_pTaskRemove = __itt_string_handle_create ( "remove" ); m_pTaskNext = __itt_string_handle_create ( "next" ); m_pTaskExt = __itt_string_handle_create ( "ext" ); m_pTaskClean = __itt_string_handle_create ( "clean" ); m_pTaskStat = __itt_string_handle_create ( "stat" ); if ( !m_bEnable ) m_pDomain->flags = 0; else __itt_resume (); #endif } void End () { EndTask(); #ifdef USE_VTUNE if ( m_bEnable ) { int64_t tmNow = sphMicroTimer(); int64_t tmDelta = tmNow - m_tmTotal; int64_t tmPassed = tmNow - g_tmStarted; sphLogDebug ( "loop=%.3f, (act=%d, next=%d, ext=%d, cln=%d), passed=%.3f", ((float)tmDelta)/1000.0f, m_iPerfEv, m_iPerfNext, m_iPerfExt, m_iPerfClean, ((float)tmPassed)/1000000.0f ); } #endif } void EndTask () { #ifdef USE_VTUNE if ( m_bEnable ) __itt_task_end ( m_pDomain ); #endif } void Start () { #ifdef USE_VTUNE if ( m_bEnable ) { __itt_task_begin ( m_pDomain, __itt_null, __itt_null, m_pTaskTick ); m_tmTotal = sphMicroTimer(); m_iPerfEv = m_iPerfNext = m_iPerfExt = m_iPerfClean = 0; } #endif } void StartPoll () { #ifdef USE_VTUNE if ( m_bEnable ) __itt_task_begin ( m_pDomain, __itt_null, __itt_null, m_pTaskPoll ); #endif } void StartTick () { #ifdef USE_VTUNE if ( m_bEnable ) __itt_task_begin ( m_pDomain, __itt_null, __itt_null, m_pTaskActions ); #endif } void StartRemove () { #ifdef USE_VTUNE if ( m_bEnable ) __itt_task_begin ( m_pDomain, __itt_null, __itt_null, m_pTaskRemove ); #endif } void StartExt () { #ifdef USE_VTUNE if ( m_bEnable ) __itt_task_begin ( m_pDomain, __itt_null, __itt_null, m_pTaskExt ); #endif } void StartAt() { #ifdef USE_VTUNE if ( m_bEnable ) __itt_task_begin ( m_pDomain, __itt_null, __itt_null, m_pTaskAT ); #endif } void StartAr() { #ifdef USE_VTUNE if ( m_bEnable ) __itt_task_begin ( m_pDomain, __itt_null, __itt_null, m_pTaskAR ); #endif } void StartClean() { #ifdef USE_VTUNE if ( m_bEnable ) __itt_task_begin ( m_pDomain, __itt_null, __itt_null, m_pTaskClean ); #endif } void StartNext() { #ifdef USE_VTUNE if ( m_bEnable ) __itt_task_begin ( m_pDomain, __itt_null, __itt_null, m_pTaskNext ); #endif } void StartStat() { #ifdef USE_VTUNE if ( m_bEnable ) __itt_task_begin ( m_pDomain, __itt_null, __itt_null, m_pTaskStat ); #endif } };
4,136
C++
.h
159
23.849057
103
0.673804
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,169
columnarexpr.h
manticoresoftware_manticoresearch/src/columnarexpr.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #ifndef _columnarexpr_ #define _columnarexpr_ #include "sphinxdefs.h" #include "sphinxexpr.h" class ConstList_c; ISphExpr * CreateExpr_ColumnarMva32In ( const CSphString & sName, ConstList_c * pConsts ); ISphExpr * CreateExpr_ColumnarMva64In ( const CSphString & sName, ConstList_c * pConsts ); ISphExpr * CreateExpr_ColumnarStringIn ( const CSphString & sName, ConstList_c * pConsts, ESphCollation eCollation ); ISphExpr * CreateExpr_ColumnarStringLength ( const CSphString & sName ); ISphExpr * CreateExpr_ColumnarMva32Length ( const CSphString & sName ); ISphExpr * CreateExpr_ColumnarMva64Length ( const CSphString & sName ); ISphExpr * CreateExpr_ColumnarMva32Aggr ( ISphExpr * pExpr, ESphAggrFunc eFunc ); ISphExpr * CreateExpr_ColumnarMva64Aggr ( ISphExpr * pExpr, ESphAggrFunc eFunc ); ISphExpr * CreateExpr_GetColumnarInt ( const CSphString & sName, bool bStored ); ISphExpr * CreateExpr_GetColumnarFloat ( const CSphString & sName, bool bStored ); ISphExpr * CreateExpr_GetColumnarString ( const CSphString & sName, bool bStored ); ISphExpr * CreateExpr_GetColumnarMva ( const CSphString & sName, bool bStored ); #endif // _columnarexpr_
1,631
C++
.h
29
55
117
0.780564
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,170
sortergroup.h
manticoresoftware_manticoresearch/src/sortergroup.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #pragma once #include "queuecreator.h" class ISphMatchComparator; ISphMatchSorter * CreateGroupSorter ( ESphSortFunc eGroupFunc, const ISphMatchComparator * pComp, const CSphQuery * pQuery, const CSphGroupSorterSettings & tSettings, bool bHasPackedFactors, bool bHasAggregates, const PrecalculatedSorterResults_t & tPrecalc );
806
C++
.h
15
52.533333
260
0.788071
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,171
event.h
manticoresoftware_manticoresearch/src/event.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // /// @file event.h - declares and implements generic low-level event, mutex-type agnostic. #pragma once #include "config.h" #include "sphinxstd.h" #include <mutex> // exception on event create instead of ec (usually we invoke sphDie, let's try exceptions in some places) class SystemError_c : public std::exception { int m_iErrorCode ; mutable CSphString m_sWhat; public: explicit SystemError_c ( int iEc ) noexcept : m_iErrorCode ( iEc ) {} explicit SystemError_c ( const char * szWhat ) : m_iErrorCode ( 0 ) { m_sWhat.SetSprintf ( "%s", szWhat ); } SystemError_c ( int iEc, const char* szWhat ) : m_iErrorCode ( iEc ) { m_sWhat.SetSprintf ( "%s, error %d", szWhat, iEc ); } ~SystemError_c () noexcept override {} int Errno () const noexcept { return m_iErrorCode; } const char* sWhat() const noexcept { return m_sWhat.scstr(); } }; namespace sph { #if _WIN32 class Event_c : public ISphNoncopyable { HANDLE m_Events[2]; // 0-th with manual reset, to signal all. 1-st with auto reset, to signal one. DWORD m_uState; public: // Constructor. Event_c () : m_uState ( 0 ) { m_Events[0] = CreateEvent ( NULL, TRUE, FALSE, NULL ); if ( !m_Events[0] ) throw SystemError_c ( GetLastError(), "event creation failed" ); m_Events[1] = CreateEvent ( NULL, FALSE, FALSE, NULL ); if ( !m_Events[1] ) { CloseHandle ( m_Events[0]); throw SystemError_c ( GetLastError (), "event creation failed" ); } } // Destructor. ~Event_c () { CloseHandle ( m_Events[0] ); CloseHandle ( m_Events[1] ); } // Signal all waiters. template<typename Lock> void SignalAll ( Lock & dLock ) { assert ( dLock.Locked ()); m_uState |= 1; SetEvent ( m_Events[0] ); } // Unlock the mutex and signal one waiter. template<typename Lock> void UnlockAndSignalOne ( Lock & dLock ) { assert ( dLock.Locked ()); m_uState |= 1; bool bHaveWaiters = (m_uState>1); dLock.Unlock (); if ( bHaveWaiters ) SetEvent ( m_Events[1] ); } // If there's a waiter, unlock the mutex and signal it. template<typename Lock> bool MaybeUnlockAndSignalOne ( Lock & dLock ) { assert ( dLock.Locked ()); m_uState |= 1; if ( m_uState>1 ) { dLock.Unlock (); SetEvent ( m_Events[1] ); return true; } return false; } // Reset the event. template<typename Lock> void Clear ( Lock & dLock ) { assert ( dLock.Locked ()); ResetEvent ( m_Events[0] ); m_uState &= ~size_t ( 1 ); } // Wait for the event to become signalled. template<typename Lock> void Wait ( Lock & dLock ) { assert ( dLock.Locked ()); while ((m_uState & 1)==0) { m_uState += 2; dLock.Unlock (); WaitForMultipleObjects ( 2, m_Events, FALSE, INFINITE ); dLock.Lock (); m_uState -= 2; } } // Timed wait for the event to become signalled. template<typename Lock> bool WaitForUsec ( Lock & dLock, long iUsec ) { assert ( dLock.Locked ()); if ((m_uState & 1)==0 ) { m_uState += 2; dLock.Unlock (); DWORD uMsec = iUsec>0 ? (iUsec<1000 ? 1 : iUsec / 1000) : 0; WaitForMultipleObjects ( 2, m_Events, FALSE, uMsec ); dLock.Lock (); m_uState -= 2; } return (m_uState & 1)!=0; } }; #else class Event_c : public ISphNoncopyable { pthread_cond_t m_tCond; DWORD m_uState; // bit 0 - when signalled; bit 1 - in waiting. public: Event_c () : m_uState ( 0) { #if (defined(__MACH__) && defined(__APPLE__)) int iError = pthread_cond_init ( &m_tCond, nullptr ); #else pthread_condattr_t attr; pthread_condattr_init(&attr); int iError = pthread_condattr_setclock(&attr, CLOCK_MONOTONIC); if (iError == 0) iError = pthread_cond_init(&m_tCond, &attr); #endif if ( iError!=0 ) throw SystemError_c (iError, "event creation failed"); } // Destructor. ~Event_c () { pthread_cond_destroy ( &m_tCond ); } // Signal all waiters. template<typename Lock> void SignalAll ( Lock & dLock ) REQUIRES (dLock) { assert ( dLock.Locked ()); m_uState |= 1; pthread_cond_broadcast ( &m_tCond ); // Ignore EINVAL. } // Unlock the mutex and signal one waiter. template<typename Lock> void UnlockAndSignalOne ( Lock & dLock ) RELEASE ( dLock ) { assert ( dLock.Locked ()); m_uState |= 1; bool bHaveWaiters = (m_uState>1); dLock.Unlock (); if ( bHaveWaiters ) pthread_cond_signal ( &m_tCond ); // Ignore EINVAL. } // If there's a waiter, unlock the mutex and signal it. template<typename Lock> bool MaybeUnlockAndSignalOne ( Lock & dLock ) REQUIRES ( dLock ) RELEASE ( dLock ) TRY_ACQUIRE ( false, dLock ) { assert ( dLock.Locked ()); m_uState |= 1; if ( m_uState>1 ) { dLock.Unlock (); pthread_cond_signal ( &m_tCond ); // Ignore EINVAL. return true; } return false; } // Reset the event. template<typename Lock> void Clear ( Lock & dLock ) REQUIRES ( dLock ) { assert ( dLock.Locked ()); m_uState &= ~size_t ( 1 ); } // Wait for the event to become signalled. template<typename Lock> void Wait ( Lock & dLock ) REQUIRES ( dLock ) { assert ( dLock.Locked ()); while ((m_uState & 1)==0) { m_uState += 2; pthread_cond_wait ( &m_tCond, &dLock.mutex () ); // Ignore EINVAL. m_uState -= 2; } } // Timed wait for the event to become signalled. template<typename Lock> bool WaitForUsec ( Lock & dLock, long iUsec ) REQUIRES ( dLock ) { assert ( dLock.Locked ()); if ((m_uState & 1)==0 ) { m_uState += 2; timespec ts; #if (defined(__MACH__) && defined(__APPLE__)) ts.tv_sec = iUsec / 1000000; ts.tv_nsec = (iUsec % 1000000) * 1000; pthread_cond_timedwait_relative_np ( &m_tCond, &dLock.mutex (), &ts ); // Ignore EINVAL. #else if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) { ts.tv_sec += iUsec / 1000000; ts.tv_nsec += (iUsec % 1000000) * 1000; ts.tv_sec += ts.tv_nsec / 1000000000; ts.tv_nsec = ts.tv_nsec % 1000000000; pthread_cond_timedwait ( &m_tCond, &dLock.mutex (), &ts ); // Ignore EINVAL. } #endif m_uState -= 2; } return (m_uState & 1)!=0; } }; #endif } // namespace sph
6,394
C++
.h
243
23.662551
106
0.657946
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,172
querycontext.h
manticoresoftware_manticoresearch/src/querycontext.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #pragma once #include "sphinx.h" #include "sphinxfilter.h" struct ContextCalcItem_t { CSphAttrLocator m_tLoc; // result locator ESphAttr m_eType = SPH_ATTR_NONE; // result type ISphExprRefPtr_c m_pExpr; // evaluator (non-owned) }; FORCE_INLINE void CalcContextItem ( CSphMatch & tMatch, const ContextCalcItem_t & tCalc ) { switch ( tCalc.m_eType ) { case SPH_ATTR_BOOL: case SPH_ATTR_INTEGER: case SPH_ATTR_TIMESTAMP: tMatch.SetAttr ( tCalc.m_tLoc, tCalc.m_pExpr->IntEval(tMatch) ); break; case SPH_ATTR_BIGINT: case SPH_ATTR_UINT64: case SPH_ATTR_JSON_FIELD: tMatch.SetAttr ( tCalc.m_tLoc, tCalc.m_pExpr->Int64Eval(tMatch) ); break; case SPH_ATTR_STRINGPTR: tMatch.SetAttr ( tCalc.m_tLoc, (SphAttr_t)tCalc.m_pExpr->StringEvalPacked ( tMatch ) ); break; case SPH_ATTR_FACTORS: case SPH_ATTR_FACTORS_JSON: tMatch.SetAttr ( tCalc.m_tLoc, (SphAttr_t)tCalc.m_pExpr->FactorEvalPacked ( tMatch ) ); // FIXME! a potential leak of *previous* value? break; case SPH_ATTR_INT64SET_PTR: case SPH_ATTR_UINT32SET_PTR: case SPH_ATTR_FLOAT_VECTOR_PTR: tMatch.SetAttr ( tCalc.m_tLoc, (SphAttr_t)tCalc.m_pExpr->Int64Eval ( tMatch ) ); break; case SPH_ATTR_DOUBLE: tMatch.SetAttrDouble ( tCalc.m_tLoc, tCalc.m_pExpr->Eval(tMatch) ); break; default: tMatch.SetAttrFloat ( tCalc.m_tLoc, tCalc.m_pExpr->Eval(tMatch) ); break; } } FORCE_INLINE void CalcContextItems ( CSphMatch & tMatch, const VecTraits_T<ContextCalcItem_t> & dItems ) { for ( auto & i : dItems ) CalcContextItem ( tMatch, i ); } class ISphRanker; class Docstore_i; struct CreateFilterContext_t; using UservarIntSetValues_c = CSphVector<SphAttr_t>; using UservarIntSet_c = SharedPtr_t<UservarIntSetValues_c>; /// per-query search context /// everything that index needs to compute/create to process the query class CSphQueryContext : public ISphNoncopyable { public: // searching-only, per-query const CSphQuery & m_tQuery; int m_iWeights = 0; ///< search query field weights count int m_dWeights [ SPH_MAX_FIELDS ]; ///< search query field weights DWORD m_uPackedFactorFlags { SPH_FACTOR_DISABLE }; ///< whether we need to calculate packed factors (and some extra options) std::unique_ptr<ISphFilter> m_pFilter; std::unique_ptr<ISphFilter> m_pWeightFilter; bool m_bSkipQCache = false; ///< whether do not cache this query CSphVector<ContextCalcItem_t> m_dCalcFilter; ///< items to compute for filtering CSphVector<ContextCalcItem_t> m_dCalcSort; ///< items to compute for sorting/grouping CSphVector<ContextCalcItem_t> m_dCalcFinal; ///< items to compute when finalizing result set IntVec_t m_dCalcFilterPtrAttrs; ///< items to free after computing filter stage IntVec_t m_dCalcSortPtrAttrs; ///< items to free after computing sort stage const void * m_pIndexData = nullptr; ///< backend specific data QueryProfile_c * m_pProfile = nullptr; const SmallStringHash_T<int64_t> * m_pLocalDocs = nullptr; int64_t m_iTotalDocs = 0; int64_t m_iIndexTotalDocs = 0; explicit CSphQueryContext ( const CSphQuery & tQuery ) : m_tQuery ( tQuery ) {} ~CSphQueryContext () { ResetFilters(); } void BindWeights ( const CSphQuery & tQuery, const CSphSchema & tSchema, CSphString & sWarning ); bool SetupCalc ( CSphQueryResultMeta & tMeta, const ISphSchema & tInSchema, const ISphSchema & tSchema, const BYTE * pBlobPool, const columnar::Columnar_i * pColumnar, const CSphVector<const ISphSchema *> & dInSchemas ); bool CreateFilters ( CreateFilterContext_t & tCtx, CSphString &sError, CSphString &sWarning ); void CalcFilter ( CSphMatch & tMatch ) const { CalcContextItems ( tMatch, m_dCalcFilter ); } void CalcSort ( CSphMatch & tMatch ) const { CalcContextItems ( tMatch, m_dCalcSort ); } void CalcFinal ( CSphMatch & tMatch ) const { CalcContextItems ( tMatch, m_dCalcFinal ); } void CalcItem ( CSphMatch & tMatch, const ContextCalcItem_t & tCalc ) const { CalcContextItem ( tMatch, tCalc ); } void FreeDataFilter ( CSphMatch & tMatch ) const; void FreeDataSort ( CSphMatch & tMatch ) const; // note that RT index bind pools at segment searching, not at time it setups context void ExprCommand ( ESphExprCommand eCmd, void * pArg ); void SetBlobPool ( const BYTE * pBlobPool ); void SetColumnar ( const columnar::Columnar_i * pColumnar ); void SetDocstore ( const Docstore_i * pDocstore, int64_t iDocstoreSessionId ); void SetupExtraData ( ISphRanker * pRanker, ISphMatchSorter * pSorter ); void ResetFilters(); private: CSphVector<UservarIntSet_c> m_dUserVals; void AddToFilterCalc ( const ContextCalcItem_t & tCalc ); void AddToSortCalc ( const ContextCalcItem_t & tCalc ); };
5,223
C++
.h
110
45.363636
221
0.738095
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,173
pollable_event.h
manticoresoftware_manticoresearch/src/pollable_event.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #pragma once #include "std/generics.h" #include "std/string.h" // an event we use to wake up pollers (also used in net events in threadpool) struct PollableEvent_t : ISphNoncopyable { public: PollableEvent_t (); virtual ~PollableEvent_t (); inline bool IsPollable () const { return m_iPollablefd!=-1; } void Close(); /// fire an event bool FireEvent () const; /// remove fired event void DisposeEvent () const; public: int m_iPollablefd = -1; ///< listener's fd, to be used in pollers CSphString m_sError; protected: int m_iSignalEvent = -1; ///< firing fd, writing here will wake up m_iPollablefd static int PollableErrno(); };
1,129
C++
.h
33
32.606061
81
0.738051
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,174
exprdatetime.h
manticoresoftware_manticoresearch/src/exprdatetime.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #ifndef _exprdatetime_ #define _exprdatetime_ #include "datetime.h" class ISphExpr; void SetGroupingInUTC ( bool bGroupingInUtc ); bool GetGroupingInUTC(); ISphExpr * CreateExprNow ( int iNow ); ISphExpr * CreateExprDateFormat ( ISphExpr * pArg, ISphExpr * pFmt ); ISphExpr * CreateExprCurTime ( bool bUTC, bool bDate ); ISphExpr * CreateExprCurDate(); ISphExpr * CreateExprTime ( ISphExpr * pArg ); ISphExpr * CreateExprDate ( ISphExpr * pArg ); ISphExpr * CreateExprDayName ( ISphExpr * pArg ); ISphExpr * CreateExprMonthName ( ISphExpr * pArg ); ISphExpr * CreateExprTimeDiff ( ISphExpr * pFirst, ISphExpr * pSecond ); ISphExpr * CreateExprDateDiff ( ISphExpr * pFirst, ISphExpr * pSecond ); ISphExpr * CreateExprDateAdd ( ISphExpr * pFirst, ISphExpr * pSecond, TimeUnit_e eUnit, bool bAdd ); ISphExpr * CreateExprDay ( ISphExpr * pExpr ); ISphExpr * CreateExprWeek ( ISphExpr * pFirst, ISphExpr * pSecond ); ISphExpr * CreateExprMonth ( ISphExpr * pExpr ); ISphExpr * CreateExprYear ( ISphExpr * pExpr ); ISphExpr * CreateExprYearMonth ( ISphExpr * pExpr ); ISphExpr * CreateExprYearMonthDay ( ISphExpr * pExpr ); ISphExpr * CreateExprYearWeek ( ISphExpr * pExpr ); ISphExpr * CreateExprHour ( ISphExpr * pExpr ); ISphExpr * CreateExprMinute ( ISphExpr * pExpr ); ISphExpr * CreateExprSecond ( ISphExpr * pExpr ); ISphExpr * CreateExprDayOfWeek ( ISphExpr * pExpr ); ISphExpr * CreateExprDayOfYear ( ISphExpr * pExpr ); ISphExpr * CreateExprQuarter ( ISphExpr * pExpr ); #endif // _exprdatetime_
1,985
C++
.h
42
46.095238
100
0.759298
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,175
columnarrt.h
manticoresoftware_manticoresearch/src/columnarrt.h
// // Copyright (c) 2021-2024, Manticore Software LTD (https://manticoresearch.com) // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #ifndef _columnarrt_ #define _columnarrt_ #include <cstdint> #include "sphinxdefs.h" #include "sphinxstd.h" #include "columnarlib.h" #include "fileio.h" class CSphSchema; class ColumnarRT_i : public columnar::Columnar_i { public: virtual int64_t AllocatedBytes() const = 0; virtual void Save ( Writer_i & tWriter ) = 0; }; class MemoryReader_c; class MemoryWriter_c; class ColumnarAttrRT_i; class ColumnarBuilderRT_i : public columnar::Builder_i { public: virtual void Save ( MemoryWriter_c & tWriter ) = 0; virtual CSphVector<std::unique_ptr<ColumnarAttrRT_i>> & GetAttrs() = 0; virtual const CSphVector<std::unique_ptr<ColumnarAttrRT_i>>& GetAttrs() const = 0; }; // used in accumulator. loads whole storage (no schema to save memory) std::unique_ptr<ColumnarBuilderRT_i> CreateColumnarBuilderRT ( MemoryReader_c& tReader ); // create an empty builder, create storage from schema std::unique_ptr<ColumnarBuilderRT_i> CreateColumnarBuilderRT ( const CSphSchema & tSchema ); // initialize columnar from accumulator; setup schema // columnar reader will take ownership of attributes in columnar builder (and remove them from builder) std::unique_ptr<ColumnarRT_i> CreateColumnarRT ( const CSphSchema & tSchema, ColumnarBuilderRT_i* pBuilder ); // columnar reader will NOT take ownership of attributes in columnar builder std::unique_ptr<ColumnarRT_i> CreateLightColumnarRT ( const CSphSchema& tSchema, const ColumnarBuilderRT_i* pBuilder ); // used by ram segments and binlog std::unique_ptr<ColumnarRT_i> CreateColumnarRT ( const CSphSchema & tSchema, CSphReader & tReader, CSphString & sError ); void RemoveColumnarDuplicates ( std::unique_ptr<ColumnarBuilderRT_i> & pBuilder, const CSphFixedVector<RowID_t> & dRowMap, const CSphSchema & tSchema ); #endif // _columnarrt_
2,179
C++
.h
46
45.978261
152
0.777358
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,176
docstore.h
manticoresoftware_manticoresearch/src/docstore.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #ifndef _docstore_ #define _docstore_ #include "sphinxstd.h" #include "sphinxdefs.h" #include "sphinx.h" class DocstoreAddField_i { public: virtual ~DocstoreAddField_i() {} virtual int AddField ( const CSphString & sName, DocstoreDataType_e eType ) = 0; virtual void RemoveField ( const CSphString & sName, DocstoreDataType_e eType ) = 0; }; class DocstoreGetField_i { public: virtual ~DocstoreGetField_i() {} virtual int GetFieldId ( const CSphString & sName, DocstoreDataType_e eType ) const = 0; }; class DocstoreFields_i : public DocstoreAddField_i, public DocstoreGetField_i { public: virtual int GetNumFields() const = 0; }; // an interface for plain index (disk chunk) document storage class Docstore_i : public DocstoreGetField_i { public: virtual void CreateReader ( int64_t iSessionId ) const = 0; virtual DocstoreDoc_t GetDoc ( RowID_t tRowID, const VecTraits_T<int> * pFieldIds, int64_t iSessionId, bool bPack ) const = 0; virtual DocstoreSettings_t GetDocstoreSettings() const = 0; }; class DocstoreBuilder_i : public DocstoreAddField_i, public DocstoreGetField_i { public: struct Doc_t { CSphVector<VecTraits_T<BYTE>> m_dFields; Doc_t(); Doc_t ( const DocstoreDoc_t & tDoc ); }; virtual void AddDoc ( RowID_t tRowID, const Doc_t & tDoc ) = 0; virtual void Finalize() = 0; }; class CSphReader; class CSphWriter; class MemoryReader_c; class MemoryWriter_c; // an interface for RT index document storage class DocstoreRT_i : public Docstore_i, public DocstoreBuilder_i { public: virtual bool Load ( CSphReader & tReader ) = 0; virtual void Save ( Writer_i & tWriter ) = 0; virtual void Load ( MemoryReader_c & tReader ) = 0; virtual void Save ( MemoryWriter_c & tWriter ) = 0; virtual void AddPackedDoc ( RowID_t tRowID, const DocstoreRT_i * pSrcDocstore, RowID_t tSrcRowID ) = 0; virtual int64_t AllocatedBytes() const = 0; virtual bool CheckFieldsLoaded ( CSphString & sError ) const = 0; virtual void SwapRows ( RowID_t tDstID, RowID_t tSrcID ) = 0; virtual void DropTail ( RowID_t tTailID ) = 0; }; class DocstoreSession_c { public: struct InfoDocID_t { const DocstoreReader_i * m_pDocstore = nullptr; int64_t m_iSessionId = 0; }; struct InfoRowID_t { const Docstore_i * m_pDocstore = nullptr; int64_t m_iSessionId = 0; }; DocstoreSession_c(); ~DocstoreSession_c(); int64_t GetUID() const { return m_iUID; } private: static std::atomic<int64_t> m_tUIDGenerator; int64_t m_iUID = 0; }; std::unique_ptr<Docstore_i> CreateDocstore ( int64_t iIndexId, const CSphString & sFilename, CSphString & sError ); std::unique_ptr<DocstoreBuilder_i> CreateDocstoreBuilder ( const CSphString & sFilename, const DocstoreSettings_t & tSettings, int iBufferSize, CSphString & sError ); std::unique_ptr<DocstoreRT_i> CreateDocstoreRT(); std::unique_ptr<DocstoreFields_i> CreateDocstoreFields(); void InitDocstore ( int64_t iCacheSize ); void ShutdownDocstore(); class DebugCheckError_i; class CSphAutoreader; bool CheckDocstore ( CSphAutoreader & tReader, DebugCheckError_i & tReporter, int64_t iRowsCount ); #endif
3,510
C++
.h
100
33.23
166
0.750666
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,177
compressed_http.h
manticoresoftware_manticoresearch/src/compressed_http.h
// // Copyright (c) 2021-2024, Manticore Software LTD (https://manticoresearch.com) // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #include "sphinxstd.h" bool GzipDecompress ( const ByteBlob_t sIn, CSphVector<BYTE> & dRes, CSphString & sError ); bool HasGzip();
511
C++
.h
12
41.5
91
0.748996
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,178
histogram.h
manticoresoftware_manticoresearch/src/histogram.h
// // Copyright (c) 2018-2024, Manticore Software LTD (https://manticoresearch.com) // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #ifndef _histogram_ #define _histogram_ #include "columnarmisc.h" #include "sphinx.h" class CSphReader; class CSphWriter; enum HistogramType_e { HISTOGRAM_STREAMED_UINT32, HISTOGRAM_STREAMED_INT64, HISTOGRAM_STREAMED_FLOAT }; struct HistogramRset_t { int64_t m_iTotal = 0; }; class Histogram_i { public: virtual ~Histogram_i() {} virtual void Insert ( SphAttr_t tAttrVal ) = 0; // index time insert element when values and counters could be updated virtual void UpdateCounter ( SphAttr_t tAttr ) = 0; // run-time update counters only element values are same virtual void Delete ( SphAttr_t tAttrVal ) = 0; virtual bool EstimateRsetSize ( const CSphFilterSettings & tFilter, HistogramRset_t & tEstimate ) const = 0; virtual DWORD GetNumValues() const = 0; virtual bool IsOutdated() const = 0; virtual int GetSize() const = 0; virtual HistogramType_e GetType() const = 0; virtual const CSphString & GetAttrName() const = 0; virtual void Finalize() {} virtual bool Save ( CSphWriter & tWriter ) const = 0; virtual bool Load ( CSphReader & tReader, CSphString & sError ) = 0; virtual void Dump ( StringBuilder_c & tOut ) const = 0; }; class HistogramContainer_c { public: ~HistogramContainer_c(); bool Save ( const CSphString & sFile, CSphString & sError ); bool Load ( const CSphString & sFile, CSphString & sError ); bool Add ( std::unique_ptr<Histogram_i> pHistogram ); void Remove ( const CSphString & sAttr ); Histogram_i * Get ( const CSphString & sAttr ) const; void Insert ( int iHistogram, SphAttr_t tAttr ) { m_dHistograms[iHistogram]->Insert(tAttr); } private: CSphVector<Histogram_i*> m_dHistograms; SmallStringHash_T<Histogram_i*> m_dHistogramHash; void Reset(); }; std::unique_ptr<Histogram_i> CreateHistogram ( const CSphString & sAttr, ESphAttr eAttrType, int iSize=0 ); void BuildCreateHistograms ( HistogramContainer_c & tHistograms, CSphVector<PlainOrColumnar_t> & dAttrsForHistogram, const ISphSchema & tSchema ); void BuildStoreHistograms ( RowID_t tRowID, const CSphRowitem * pRow, const BYTE * pPool, CSphVector<ScopedTypedIterator_t> & dIterators, const CSphVector<PlainOrColumnar_t> & dAttrs, HistogramContainer_c & tHistograms ); struct HistogramSource_t { Histogram_i * m_pHist { nullptr }; int m_iAttr { -1 }; ESphAttr m_eAttrType { SPH_ATTR_NONE }; }; #endif // _histogram_
2,753
C++
.h
68
38.661765
221
0.750751
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,179
docs_collector.h
manticoresoftware_manticoresearch/src/docs_collector.h
// // Copyright (c) 2008-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org // #pragma once #include "searchdaemon.h" class DocsCollector_c : public ISphNoncopyable { class Impl_c; std::unique_ptr<Impl_c> m_pImpl; public: DocsCollector_c ( const CSphQuery& tQuery, bool bJson, const CSphString& sIndex, const cServedIndexRefPtr_c& pDesc, CSphString* pError ); DocsCollector_c ( DocsCollector_c&& rhs ) noexcept; ~DocsCollector_c(); bool GetValuesChunk ( CSphVector<DocID_t>& dValues, int iValues ); // beware, that slice lives together with this class, and will become undefined once it destroyed. VecTraits_T<DocID_t> GetValuesSlice(); };
1,049
C++
.h
25
40.44
138
0.763494
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,180
sphinx.h
manticoresoftware_manticoresearch/src/sphinx.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #ifndef _sphinx_ #define _sphinx_ ///////////////////////////////////////////////////////////////////////////// #include "sphinxstd.h" #include "indexsettings.h" #include "fileutils.h" #include "collation.h" #include "binlog_defs.h" #include "task_dispatcher.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <limits.h> #include <optional> #if _WIN32 #include <winsock2.h> #include <WS2tcpip.h> #else #include <sys/types.h> #include <unistd.h> #endif #if _WIN32 #define STDOUT_FILENO fileno(stdout) #define STDERR_FILENO fileno(stderr) #endif #include "sphinxdefs.h" #include "schema/locator.h" #include "schema/schema.h" #include "indexfilebase.h" ///////////////////////////////////////////////////////////////////////////// // defined in sphinxversion.cpp in order to isolate from total rebuild on minor changes extern const char * szMANTICORE_VERSION; extern const char * szMANTICORE_NAME; extern const char * szMANTICORE_BANNER; extern const char * szMANTICORE_BANNER_TEXT; extern const char * szGIT_COMMIT_ID; extern const char * szGIT_BRANCH_ID; extern const char * szGDB_SOURCE_DIR; #define SPHINX_SEARCHD_PROTO 1 #define SPHINX_CLIENT_VERSION 1 ///////////////////////////////////////////////////////////////////////////// extern int64_t g_iIndexerCurrentDocID; extern int64_t g_iIndexerCurrentHits; extern int64_t g_iIndexerCurrentRangeMin; extern int64_t g_iIndexerCurrentRangeMax; extern int64_t g_iIndexerPoolStartDocID; extern int64_t g_iIndexerPoolStartHit; ///////////////////////////////////////////////////////////////////////////// /// millisecond-precision sleep void sphSleepMsec ( int iMsec ); /// immediately interrupt current query void sphInterruptNow(); /// check if we got interrupted bool sphInterrupted(); ////////////////////////////////////////////////////////////////////////// struct CSphMultiformContainer; class CSphWriter; /// wordforms container struct CSphWordforms; // converts stopword/wordform/exception file paths for configless mode class FilenameBuilder_i { public: virtual ~FilenameBuilder_i() {} virtual CSphString GetFullPath ( const CSphString & sName ) const = 0; }; ///////////////////////////////////////////////////////////////////////////// // DATASOURCES ///////////////////////////////////////////////////////////////////////////// /// hit processing tools /// Hitpos_t consists of three things: /// 1) high bits store field number /// 2) middle bit - field end marker /// 3) lower bits store hit position in field template < int FIELD_BITS > class Hitman_c { protected: enum { FIELD_OFF = 32 - FIELD_BITS, // 24 POS_BITS = FIELD_OFF - 1, // 23 FIELDEND_OFF = POS_BITS, // 23 FIELDEND_MASK = (1UL << POS_BITS), // 0x00800000 POS_MASK = FIELDEND_MASK - 1, // 0x007FFFFF FIELD_MASK = ~(FIELDEND_MASK|POS_MASK),// 0xFF000000 }; public: static Hitpos_t Create ( int iField, int iPos ) { return ( iField << FIELD_OFF ) + ( iPos & POS_MASK ); } static Hitpos_t Create ( int iField, int iPos, bool bEnd ) { return ( iField << FIELD_OFF ) + ( ((int)bEnd) << FIELDEND_OFF ) + ( iPos & POS_MASK ); } static inline int GetField ( Hitpos_t uHitpos ) { return uHitpos >> FIELD_OFF; } static inline void DecrementField ( Hitpos_t& uHitpos ) { assert ( uHitpos & FIELD_MASK ); uHitpos -= (1UL << FIELD_OFF); } static inline int GetPos ( Hitpos_t uHitpos ) { return uHitpos & POS_MASK; } static inline bool IsEnd ( Hitpos_t uHitpos ) { return ( uHitpos & FIELDEND_MASK )!=0; } static inline DWORD GetPosWithField ( Hitpos_t uHitpos ) { return uHitpos & ~FIELDEND_MASK; } static void AddPos ( Hitpos_t * pHitpos, int iAdd ) { // FIXME! add range checks (eg. so that 0:0-1 does not overflow) *pHitpos += iAdd; } static Hitpos_t CreateSum ( Hitpos_t uHitpos, int iAdd ) { // FIXME! add range checks (eg. so that 0:0-1 does not overflow) return ( uHitpos+iAdd ) & ~FIELDEND_MASK; } static void SetEndMarker ( Hitpos_t * pHitpos ) { *pHitpos |= FIELDEND_MASK; } }; // this could be just DWORD[] but it's methods are very handy // used to store field information e.g. which fields do we need to search in struct FieldMask_t { static const int SIZE = SPH_MAX_FIELDS/32; STATIC_ASSERT ( ( SPH_MAX_FIELDS%32 )==0, ASSUME_MAX_FIELDS_ARE_REPRESENTABLE_BY_DWORD ); DWORD m_dMask [ SIZE ]; // no custom cstr and d-tor - to be usable from inside unions // deep copy for it is ok - so, no explicit copying constructor and operator= // old-fashion layer to work with DWORD (32-bit) mask. // all bits above 32 assumed to be unset. void Assign32 ( DWORD uMask ) { UnsetAll(); m_dMask[0] = uMask; } DWORD GetMask32 () const { return m_dMask[0]; } DWORD operator[] ( int iIdx ) const { assert ( 0<=iIdx && iIdx<SIZE ); return m_dMask [ iIdx ]; } DWORD & operator[] ( int iIdx ) { assert ( 0<=iIdx && iIdx<SIZE ); return m_dMask [ iIdx ]; } // set n-th bit void Set ( int iIdx ) { assert ( 0<=iIdx && iIdx<(int)sizeof(m_dMask)*8 ); m_dMask [ iIdx/32 ] |= 1 << ( iIdx%32 ); } // set all bits void SetAll() { memset ( m_dMask, 0xff, sizeof(m_dMask) ); } // unset n-th bit, or all void Unset ( int iIdx ) { assert ( 0<=iIdx && iIdx<(int)sizeof(m_dMask)*8 ); m_dMask [ iIdx/32 ] &= ~(1 << ( iIdx%32 )); } void UnsetAll() { memset ( m_dMask, 0, sizeof(m_dMask) ); } // test if n-th bit is set bool Test ( int iIdx ) const { assert ( iIdx>=0 && iIdx<(int)sizeof(m_dMask)*8 ); return ( m_dMask [ iIdx/32 ] & ( 1 << ( iIdx%32 ) ) )!=0; } // test if all bits are set or unset bool TestAll ( bool bSet ) const { DWORD uTest = bSet ? 0xffffffff : 0; for ( auto uMask : m_dMask ) if ( uMask!=uTest ) return false; return true; } void Negate() { for ( auto& uMask : m_dMask ) uMask = ~uMask; } // keep bits up to iIdx; shift bits over iIdx right by 1 void DeleteBit ( int iIdx ) { const auto iDwordIdx = iIdx / 32; const auto iDwordBitPos = iIdx % 32; DWORD uCarryBit = 0; for ( int i = SIZE-1; i>iDwordIdx; --i ) { bool bNextCarry = m_dMask[i] & 1; m_dMask[i] = uCarryBit | ( m_dMask[i] >> 1 ); uCarryBit = bNextCarry ? 0x80000000 : 0; } DWORD uShiftBit = 1 << ( iDwordBitPos ); // like: 00000000 00000000 00000100 00000000 DWORD uKeepMask = uShiftBit-1; // like: 00000000 00000000 00000011 11111111 DWORD uMoveMask = ~(uShiftBit | uKeepMask); // like: 11111111 11111111 11111000 00000000 DWORD uKept = m_dMask[iDwordIdx] & uKeepMask; m_dMask[iDwordIdx] = uCarryBit | ( ( m_dMask[iDwordIdx] & uMoveMask ) >> 1 ) | uKept; } }; struct RowTagged_t { RowID_t m_tID { INVALID_ROWID }; ///< document ID int m_iTag {0}; ///< index tag RowTagged_t() = default; RowTagged_t ( const CSphMatch & tMatch ); RowTagged_t ( RowID_t tRowID, int iTag ); bool operator== ( const RowTagged_t & tRow ) const; bool operator!= ( const RowTagged_t & tRow ) const; }; ////////////////////////////////////////////////////////////////////////// // defined in stripper/html_stripper.h class CSphHTMLStripper; struct FieldFilterOptions_t { JiebaMode_e m_eJiebaMode = JiebaMode_e::NONE; }; /// field filter class ISphFieldFilter { public: virtual ~ISphFieldFilter() = default; virtual int Apply ( const BYTE * sField, int iLength, CSphVector<BYTE> & dStorage, bool bQuery ) = 0; virtual void GetSettings ( CSphFieldFilterSettings & tSettings ) const = 0; virtual std::unique_ptr<ISphFieldFilter> Clone ( const FieldFilterOptions_t * pOptions=nullptr ) const = 0; int Apply ( const void * szField, CSphVector<BYTE> & dStorage, bool bQuery ) { return Apply ( (const BYTE*)szField, (int) strlen ( (const char*)szField ), dStorage, bQuery ); } int Apply ( ByteBlob_t sField, CSphVector<BYTE> & dStorage, bool bQuery ) { return Apply ( sField.first, sField.second, dStorage, bQuery ); } }; /// create a regexp field filter std::unique_ptr<ISphFieldFilter> sphCreateRegexpFilter ( const CSphFieldFilterSettings & tFilterSettings, CSphString & sError ); ///////////////////////////////////////////////////////////////////////////// // SEARCH QUERIES ///////////////////////////////////////////////////////////////////////////// enum class EStrCmpDir { EQ, LT, GT }; /// search query filter struct CommonFilterSettings_t { ESphFilter m_eType = SPH_FILTER_VALUES; ///< filter type union { SphAttr_t m_iMinValue = LLONG_MIN; ///< range min float m_fMinValue; ///< range min }; union { SphAttr_t m_iMaxValue = LLONG_MAX; ///< range max float m_fMaxValue; ///< range max }; bool m_bHasEqualMin = true; ///< has filter "equal" component or pure greater/less (for min) bool m_bHasEqualMax = true; ///< has filter "equal" component or pure greater/less (for max) bool m_bOpenLeft = false; bool m_bOpenRight = false; bool m_bExclude = false; ///< whether this is "include" or "exclude" filter (default is "include") EStrCmpDir m_eStrCmpDir = EStrCmpDir::EQ; ///< string comparison direction }; class CSphFilterSettings : public CommonFilterSettings_t { public: CSphString m_sAttrName = ""; ///< filtered attribute name bool m_bIsNull = false; ///< for NULL or NOT NULL bool m_bOptional = false; ESphMvaFunc m_eMvaFunc = SPH_MVAFUNC_NONE; ///< MVA and stringlist folding function CSphVector<SphAttr_t> m_dValues; ///< integer values set StrVec_t m_dStrings; ///< string values public: CSphFilterSettings () = default; // fixme! Dependency from external values implies, that CsphFilterSettings is NOT standalone, // and it's state is no way 'undependent'. It would be good to capture external values, at least // with ref-counted technique, exactly here, to locate all usecases near each other. void SetExternalValues ( const VecTraits_T<SphAttr_t>& dValues ); int GetNumValues () const { return GetValues().GetLength(); } const VecTraits_T<SphAttr_t>& GetValues () const { return m_dExtValues.IsEmpty() ? m_dValues : m_dExtValues; } bool operator == ( const CSphFilterSettings & rhs ) const; bool operator != ( const CSphFilterSettings & rhs ) const { return !( (*this)==rhs ); } uint64_t GetHash() const; private: VecTraits_T<SphAttr_t> m_dExtValues; }; // keyword info struct CSphKeywordInfo { CSphString m_sTokenized; CSphString m_sNormalized; int m_iDocs = 0; int m_iHits = 0; int m_iQpos = 0; }; inline void Swap ( CSphKeywordInfo & v1, CSphKeywordInfo & v2 ) { v1.m_sTokenized.Swap ( v2.m_sTokenized ); v1.m_sNormalized.Swap ( v2.m_sNormalized ); ::Swap ( v1.m_iDocs, v2.m_iDocs ); ::Swap ( v1.m_iHits, v2.m_iHits ); ::Swap ( v1.m_iQpos, v2.m_iQpos ); } /// query selection item struct CSphQueryItem { CSphString m_sExpr; ///< expression to compute CSphString m_sAlias; ///< alias to return ESphAggrFunc m_eAggrFunc { SPH_AGGR_NONE }; }; /// search query complex filter tree struct FilterTreeItem_t { int m_iLeft = -1; // left node at parser filter operations int m_iRight = -1; // right node at parser filter operations int m_iFilterItem = -1; // index into query filters bool m_bOr = false; bool operator == ( const FilterTreeItem_t & rhs ) const; bool operator != ( const FilterTreeItem_t & rhs ) const { return !( (*this)==rhs ); } uint64_t GetHash() const; }; /// table function interface struct CSphQuery; struct AggrResult_t; class ISphTableFunc { public: virtual ~ISphTableFunc() {} virtual bool ValidateArgs ( const StrVec_t & dArgs, const CSphQuery & tQuery, CSphString & sError ) = 0; virtual bool Process ( AggrResult_t * pResult, CSphString & sError ) = 0; virtual bool LimitPushdown ( int, int ) { return false; } // FIXME! implement this }; class QueryParser_i; enum class SecondaryIndexType_e { NONE, FILTER, LOOKUP, INDEX, ANALYZER, TOTAL }; struct IndexHint_t { CSphString m_sIndex; SecondaryIndexType_e m_eType = SecondaryIndexType_e::NONE; bool m_bForce = true; }; struct OnFilter_t { CSphString m_sIdx1; CSphString m_sAttr1; CSphString m_sIdx2; CSphString m_sAttr2; ESphAttr m_eTypeCast1 = SPH_ATTR_NONE; ESphAttr m_eTypeCast2 = SPH_ATTR_NONE; }; enum class JoinType_e { NONE, INNER, LEFT }; const int DEFAULT_MAX_MATCHES = 1000; const int DEFAULT_QUERY_TIMEOUT = 0; const int DEFAULT_QUERY_RETRY = -1; const int DEFAULT_QUERY_EXPANSION_LIMIT = -1; /// search query. Pure struct, no member functions struct CSphQuery { CSphString m_sIndexes {"*"}; ///< indexes to search CSphString m_sQuery; ///< cooked query string for the engine (possibly transformed during legacy matching modes fixup) CSphString m_sRawQuery; ///< raw query string from the client for searchd log, agents, etc int m_iOffset=0; ///< offset into result set (as X in MySQL LIMIT X,Y clause) int m_iLimit=20; ///< limit into result set (as Y in MySQL LIMIT X,Y clause) CSphVector<DWORD> m_dWeights; ///< user-supplied per-field weights. may be NULL. default is NULL ESphMatchMode m_eMode = SPH_MATCH_EXTENDED; ///< match mode. default is "match all" ESphRankMode m_eRanker = SPH_RANK_DEFAULT; ///< ranking mode, default is proximity+BM25 CSphString m_sRankerExpr; ///< ranking expression for SPH_RANK_EXPR CSphString m_sUDRanker; ///< user-defined ranker name CSphString m_sUDRankerOpts; ///< user-defined ranker options ESphSortOrder m_eSort = SPH_SORT_RELEVANCE; ///< sort mode CSphString m_sSortBy; ///< attribute to sort by int64_t m_iRandSeed = -1; ///< random seed for ORDER BY RAND(), -1 means do not set int m_iMaxMatches = DEFAULT_MAX_MATCHES; ///< max matches to retrieve, default is 1000. more matches use more memory and CPU time to hold and sort them bool m_bExplicitMaxMatches = false; ///< did we specify the max_matches explicitly? CSphString m_sKNNAttr; ///< which attr to use for KNN search (enables KNN if not empty) int m_iKNNK = 0; ///< KNN K int m_iKnnEf = 0; ///< KNN ef CSphVector<float> m_dKNNVec; ///< KNN anchor vector JiebaMode_e m_eJiebaMode = JiebaMode_e::NONE; ///< separate optional jieba mode for searches bool m_bSortKbuffer = false; ///< whether to use PQ or K-buffer sorting algorithm bool m_bZSlist = false; ///< whether the ranker has to fetch the zonespanlist with this query bool m_bSimplify = false; ///< whether to apply boolean simplification bool m_bPlainIDF = false; ///< whether to use PlainIDF=log(N/n) or NormalizedIDF=log((N-n+1)/n) bool m_bGlobalIDF = false; ///< whether to use local indexes or a global idf file bool m_bNormalizedTFIDF = true; ///< whether to scale IDFs by query word count, so that TF*IDF is normalized std::optional<bool> m_bLocalDF; ///< whether to use calculate DF among local indexes bool m_bLowPriority = false; ///< set low thread priority for this query DWORD m_uDebugFlags = 0; QueryOption_e m_eExpandKeywords = QUERY_OPT_DEFAULT; ///< control automatic query-time keyword expansion int m_iExpansionLimit = DEFAULT_QUERY_EXPANSION_LIMIT; ///< whether to limit wildcard expansion, default use index settings bool m_bAccurateAggregation = false; ///< setting via options bool m_bExplicitAccurateAggregation = false; ///< whether anything was set via options int m_iDistinctThresh = 3500; ///< distinct accuracy thresh bool m_bExplicitDistinctThresh = false; ///< whether thresh was set via options int m_iMaxMatchThresh = 16384; int m_iNow = 0; ///< timestamp on query receive for all 'now' expressions to have the same base CSphVector<CSphFilterSettings> m_dFilters; ///< filters CSphVector<FilterTreeItem_t> m_dFilterTree; CSphVector<IndexHint_t> m_dIndexHints; ///< secondary index hints JoinType_e m_eJoinType = JoinType_e::NONE; ///< JOIN type CSphString m_sJoinIdx; ///< index to perform join on CSphString m_sJoinQuery; ///< fulltext query for JOIN CSphVector<OnFilter_t> m_dOnFilters; ///< JOIN ON condition filters CSphString m_sGroupBy; ///< group-by attribute name(s) CSphString m_sFacetBy; ///< facet-by attribute name(s) ESphGroupBy m_eGroupFunc = SPH_GROUPBY_ATTR; ///< function to pre-process group-by attribute value with CSphString m_sGroupSortBy { "@groupby desc" }; ///< sorting clause for groups in group-by mode CSphString m_sGroupDistinct; ///< count distinct values for this attribute int m_iCutoff = -1; ///< matches count threshold to stop searching at (<=0 means to search until all matches are found) int m_iRetryCount = DEFAULT_QUERY_RETRY; ///< retry count, for distributed queries. (-1 means 'use default') int m_iRetryDelay = DEFAULT_QUERY_RETRY; ///< retry delay, for distributed queries. (-1 means 'use default') int m_iAgentQueryTimeoutMs = DEFAULT_QUERY_TIMEOUT; ///< agent query timeout override, for distributed queries bool m_bGeoAnchor = false; ///< do we have an anchor CSphString m_sGeoLatAttr; ///< latitude attr name CSphString m_sGeoLongAttr; ///< longitude attr name float m_fGeoLatitude = 0.0f; ///< anchor latitude float m_fGeoLongitude = 0.0f; ///< anchor longitude CSphVector<CSphNamedInt> m_dIndexWeights; ///< per-index weights CSphVector<CSphNamedInt> m_dFieldWeights; ///< per-field weights DWORD m_uMaxQueryMsec = 0; ///< max local index search time, in milliseconds (default is 0; means no limit) int m_iMaxPredictedMsec = 0; ///< max predicted (!) search time limit, in milliseconds (0 means no limit) CSphString m_sComment; ///< comment to pass verbatim in the log file CSphString m_sSelect; ///< select-list (attributes and/or expressions) CSphString m_sOrderBy; ///< order-by clause CSphString m_sOuterOrderBy; ///< temporary (?) subselect hack int m_iOuterOffset = 0; ///< keep and apply outer offset at master int m_iOuterLimit = 0; bool m_bHasOuter = false; bool m_bIgnoreNonexistent = false; ///< whether to warning or not about non-existent columns in select list bool m_bIgnoreNonexistentIndexes = false; ///< whether to error or not about non-existent indexes in index list bool m_bStrict = false; ///< whether to warning or not about incompatible types bool m_bSync = false; ///< whether or not use synchronous operations (optimize, etc.) bool m_bNotOnlyAllowed = false; ///< whether allow single full-text not operator CSphString m_sStore; ///< don't delete result, just store in given uservar by name CSphFilterSettings m_tHaving; ///< post aggregate filtering (got applied only on master) int m_iSQLSelectStart = -1; ///< SQL parser helper int m_iSQLSelectEnd = -1; ///< SQL parser helper int m_iGroupbyLimit = 1; ///< number of elems within group CSphVector<CSphQueryItem> m_dItems; ///< parsed select-list CSphVector<CSphQueryItem> m_dRefItems; ///< select-list prior replacing by facet ESphCollation m_eCollation = SPH_COLLATION_DEFAULT; ///< ORDER BY collation bool m_bAgent = false; ///< agent mode (may need extra cols on output) CSphString m_sQueryTokenFilterLib; ///< token filter library name CSphString m_sQueryTokenFilterName; ///< token filter name CSphString m_sQueryTokenFilterOpts; ///< token filter options bool m_bFacet = false; ///< whether this a facet query bool m_bFacetHead = false; QueryType_e m_eQueryType {QUERY_API}; ///< queries from sphinxql require special handling const QueryParser_i * m_pQueryParser = nullptr; ///< queries do not own this parser // JSON output StrVec_t m_dIncludeItems; StrVec_t m_dExcludeItems; const void* m_pCookie = nullptr; ///< opaque mark, used to manage lifetime of the vec of queries int m_iConcurrency = 0; ///< limit N of threads to run query with. 0 means 'no limit' CSphVector<CSphString> m_dStringSubkeys; CSphVector<int64_t> m_dIntSubkeys; Dispatcher::Template_t m_tMainDispatcher; Dispatcher::Template_t m_tPseudoShardingDispatcher; }; /// parse select list string into items bool ParseSelectList ( CSphString &sError, CSphQuery &pResult ); /// some low-level query stats struct CSphQueryStats { int64_t * m_pNanoBudget = nullptr;///< pointer to max_predicted_time budget (counted in nanosec) DWORD m_iFetchedDocs = 0; ///< processed documents DWORD m_iFetchedHits = 0; ///< processed hits (aka positions) DWORD m_iSkips = 0; ///< number of Skip() calls void Add ( const CSphQueryStats & tStats ); }; struct IteratorDesc_t { CSphString m_sAttr; CSphString m_sType; int m_iUsed = 1; }; struct IteratorStats_t { CSphVector<IteratorDesc_t> m_dIterators; int m_iTotal = 0; void Merge ( const IteratorStats_t & tSrc ); }; struct ExpansionStats_t { int m_iTerms = 0; int m_iMerged = 0; }; /// search query meta-info class CSphQueryResultMeta { public: int m_iQueryTime = 0; ///< query time, milliseconds int m_iRealQueryTime = 0; ///< query time, measured just from start to finish of the query. In milliseconds int64_t m_iCpuTime = 0; ///< user time, microseconds int m_iMultiplier = 1; ///< multi-query multiplier, -1 to indicate error using WordStat_t = std::pair<int64_t, int64_t>; SmallStringHash_T<WordStat_t> m_hWordStats; ///< hash of i-th search term (normalized word form) int m_iMatches = 0; ///< total matches returned (upto MAX_MATCHES) int64_t m_iTotalMatches = 0; ///< total matches found (unlimited) bool m_bTotalMatchesApprox = false; ///< whether m_iTotalMatches shows exact or approximate numbers CSphIOStats m_tIOStats; ///< i/o stats for the query int64_t m_iAgentCpuTime = 0; ///< agent cpu time (for distributed searches) CSphIOStats m_tAgentIOStats; ///< agent IO stats (for distributed searches) int64_t m_iPredictedTime = 0; ///< local predicted time int64_t m_iAgentPredictedTime = 0; ///< distributed predicted time DWORD m_iAgentFetchedDocs = 0; ///< distributed fetched docs DWORD m_iAgentFetchedHits = 0; ///< distributed fetched hits DWORD m_iAgentFetchedSkips = 0; ///< distributed fetched skips CSphQueryStats m_tStats; ///< query prediction counters bool m_bHasPrediction = false; ///< is prediction counters set? CSphString m_sError; ///< error message CSphString m_sWarning; ///< warning message QueryProfile_c * m_pProfile = nullptr; ///< filled when query profiling is enabled; NULL otherwise IteratorStats_t m_tIteratorStats; ///< iterators used while calculating the query bool m_bBigram = false; ///< whatever to remove bigram symbol on adding word to stat ExpansionStats_t m_tExpansionStats; ///< full text query statistics for expanded and merged terms virtual ~CSphQueryResultMeta () {} ///< dtor void AddStat ( const CSphString & sWord, int64_t iDocs, int64_t iHits ); void AddStat ( const ExpansionStats_t & tExpansionStats ); void MergeWordStats ( const CSphQueryResultMeta& tOther );// sort wordstat to achieve reproducable result over different runs CSphFixedVector<SmallStringHash_T<CSphQueryResultMeta::WordStat_t>::KeyValue_t *> MakeSortedWordStat () const; }; /// search query result (meta-info) class QueryProfile_c; class DocstoreReader_i; class CSphQueryResult { public: CSphQueryResultMeta * m_pMeta = nullptr; ///< not owned const BYTE * m_pBlobPool = nullptr; ///< pointer to blob attr storage. Used only during calculations. const DocstoreReader_i* m_pDocstore = nullptr; ///< pointer to docstore reader fixme! not need in aggr columnar::Columnar_i * m_pColumnar = nullptr; }; ///////////////////////////////////////////////////////////////////////////// // ATTRIBUTE UPDATE QUERY ///////////////////////////////////////////////////////////////////////////// struct CSphAttrUpdate { CSphVector<TypedAttribute_t> m_dAttributes; ///< update schema, attributes to update CSphVector<DWORD> m_dPool; ///< update values pool CSphVector<BYTE> m_dBlobs; ///< update pool for blob attrs CSphVector<DocID_t> m_dDocids; ///< document IDs vector CSphVector<int> m_dRowOffset; ///< document row offsets in the pool (1 per doc, or empty, means 0 always) bool m_bIgnoreNonexistent = false; ///< whether to warn about non-existen attrs, or just silently ignore them bool m_bStrict = false; ///< whether to check for incompatible types first, or just ignore them bool m_bReusable = true; ///< whether update is standalone and never rewritten, or need deep-copy inline int GetRowOffset (int i) const { return m_dRowOffset.IsEmpty() ? 0 : m_dRowOffset[i]; } }; using AttrUpdateSharedPtr_t = SharedPtr_t<CSphAttrUpdate>; inline AttrUpdateSharedPtr_t MakeReusableUpdate ( AttrUpdateSharedPtr_t& pUpdate ) { if ( pUpdate->m_bReusable ) return pUpdate; AttrUpdateSharedPtr_t pNewUpdate { new CSphAttrUpdate }; *pNewUpdate = *pUpdate; pNewUpdate->m_bReusable = true; return pNewUpdate; } struct AttrUpdateInc_t // for cascade (incremental) update { AttrUpdateSharedPtr_t m_pUpdate; ///< the unchangeable update pool CSphBitvec m_dUpdated; ///< bitmask of updated rows int m_iAffected = 0; ///< num of updated rows. explicit AttrUpdateInc_t ( AttrUpdateSharedPtr_t pUpd ) : m_pUpdate ( std::move(pUpd) ) , m_dUpdated ( m_pUpdate->m_dDocids.GetLength() ) {} void MarkUpdated ( int iUpd ) { if ( m_dUpdated.BitGet ( iUpd ) ) return; ++m_iAffected; m_dUpdated.BitSet ( iUpd ); } bool AllApplied () const { assert ( m_dUpdated.GetSize() >= m_iAffected ); return m_dUpdated.GetSize() == m_iAffected; } }; void CommitUpdateAttributes ( int64_t * pTID, const char* szName, const CSphAttrUpdate & tUpd ); ///////////////////////////////////////////////////////////////////////////// // FULLTEXT INDICES ///////////////////////////////////////////////////////////////////////////// /// progress info class MergeCb_c { std::atomic<bool> * m_pStop = nullptr; public: enum Event_e : BYTE { E_IDLE, E_COLLECT_START, // begin collecting alive docs on merge; payload is chunk ID E_COLLECT_FINISHED, // collecting alive docs on merge is finished; payload is chunk ID E_MERGEATTRS_START, E_MERGEATTRS_PULSE, E_MERGEATTRS_FINISHED, E_KEYWORDS, E_FINISHED, }; explicit MergeCb_c ( std::atomic<bool>* pStop = nullptr ) : m_pStop ( pStop ) {} virtual ~MergeCb_c() = default; virtual void SetEvent ( Event_e eEvent, int64_t iPayload ) {} inline bool NeedStop () const noexcept { return sphInterrupted() || ( m_pStop && m_pStop->load ( std::memory_order_relaxed ) ); } }; class CSphIndexProgress : private MergeCb_c { MergeCb_c * m_pMergeHook; private: virtual void ShowImpl ( bool bPhaseEnd ) const {}; public: enum Phase_e { PHASE_COLLECT, ///< document collection phase PHASE_SORT, ///< final sorting phase PHASE_LOOKUP, ///< docid lookup construction PHASE_MERGE, ///< index merging PHASE_SI_BUILD, ///< secondary index build PHASE_JSONSI_BUILD, ///< json secondary index build PHASE_UNKNOWN, }; Phase_e m_ePhase; ///< current indexing phase union { int64_t m_iDocuments; ///< PHASE_COLLECT: documents collected so far int64_t m_iDocids; ///< PHASE_LOOKUP: docids added to lookup so far int64_t m_iHits; ///< PHASE_SORT: hits sorted so far int64_t m_iWords; ///< PHASE_MERGE: words merged so far }; union { int64_t m_iBytes; ///< PHASE_COLLECT: bytes collected so far; int64_t m_iDocidsTotal; ///< PHASE_LOOKUP: total docids int64_t m_iHitsTotal; ///< PHASE_SORT: hits total }; public: explicit CSphIndexProgress( MergeCb_c * pMergeHook = nullptr ) { if ( pMergeHook ) m_pMergeHook = pMergeHook; else m_pMergeHook = static_cast<MergeCb_c *>(this); PhaseBegin ( PHASE_UNKNOWN ); } inline void PhaseBegin ( Phase_e ePhase ) { m_ePhase = ePhase; m_iDocuments = m_iBytes = 0; } inline void PhaseEnd() const { if ( m_ePhase!=PHASE_UNKNOWN ) ShowImpl ( true ); } inline void Show() const { ShowImpl ( false ); } // cb MergeCb_c& GetMergeCb() const { return *m_pMergeHook; } }; /// JSON key lookup stuff struct JsonKey_t { CSphString m_sKey; ///< name string DWORD m_uMask = 0; ///< Bloom mask for this key int m_iLen = 0; ///< name length, in bytes JsonKey_t () = default; explicit JsonKey_t ( const char * sKey, int iLen ); }; /// forward refs to internal searcher classes class ISphQword; class ISphQwordSetup; class CSphQueryContext; class ISphFilter; struct GetKeywordsSettings_t; struct SuggestArgs_t; struct SuggestResult_t; struct ISphKeywordsStat { virtual ~ISphKeywordsStat() {} virtual bool FillKeywords ( CSphVector <CSphKeywordInfo> & dKeywords ) const = 0; }; struct CSphIndexStatus { int64_t m_iRamUse = 0; int64_t m_iRamRetired = 0; int64_t m_iMapped = 0; // total size of mmapped files union { int64_t m_iMappedResident = 0; // size of mmaped which are in core int64_t m_iStackNeed; // for pq - max size of stack for eval node over all index on *this* node }; union { int64_t m_iMappedDocs = 0; // size of mmapped doclists int64_t m_iStackBase; // for pq - base size over necessary }; int64_t m_iMappedResidentDocs = 0; // size of mmaped resident doclists int64_t m_iMappedHits = 0; // size of mmapped hitlists int64_t m_iMappedResidentHits = 0; // size of mmaped resident doclists int64_t m_iDiskUse = 0; // place occupied by index on disk (despite if it fetched into mem or not) int64_t m_iRamChunkSize = 0; // not used for plain int m_iNumRamChunks = 0; // not used for plain int m_iNumChunks = 0; // not used for plain int64_t m_iMemLimit = 0; // not used for plain int64_t m_iTID = 0; int64_t m_iSavedTID = 0; int64_t m_iDead = 0; double m_fSaveRateLimit {0.0}; // not used for plain. Part of m_iMemLimit to be achieved before flushing int m_iLockCount = 0; // not used for plain. N of active locks (i.e. - if N>0, saving is prohibited) int m_iOptimizesCount = 0; // not used for plain. N of currently run optimizes. }; struct CSphMultiQueryArgs : public ISphNoncopyable { const int m_iIndexWeight; int m_iTag = 0; DWORD m_uPackedFactorFlags { SPH_FACTOR_DISABLE }; bool m_bLocalDF = false; const SmallStringHash_T<int64_t> * m_pLocalDocs = nullptr; int64_t m_iTotalDocs = 0; bool m_bModifySorterSchemas = true; bool m_bFinalizeSorters = true; int m_iThreads = 1; int m_iTotalThreads = 1; CSphMultiQueryArgs ( int iIndexWeight ); }; struct RowToUpdateData_t { RowID_t m_tRow; /// row in the index int m_iIdx; /// idx in updateset }; using RowsToUpdateData_t = CSphVector<RowToUpdateData_t>; using RowsToUpdate_t = VecTraits_T<RowToUpdateData_t>; struct PostponedUpdate_t { AttrUpdateSharedPtr_t m_pUpdate; RowsToUpdateData_t m_dRowsToUpdate; }; struct UpdateContext_t; using BlockerFn = std::function<bool()>; // common attribute update code for both RT and plain indexes // an index or a part of an index that has its own row ids class IndexSegment_c { mutable IndexSegment_c* m_pKillHook = nullptr; // if set, killed docids will be emerged also here. protected: enum { ATTRS_UPDATED = ( 1UL<<0 ), ATTRS_BLOB_UPDATED = ( 1UL<<1 ), ATTRS_ROWMAP_UPDATED = ( 1UL<<2 ) }; private: virtual bool Update_WriteBlobRow ( UpdateContext_t & tCtx, RowID_t tRowID, ByteBlob_t tBlob, int nBlobAttrs, const CSphAttrLocator & tBlobRowLoc, bool & bCritical, CSphString & sError ) {return false;}; static bool Update_InplaceJson ( const RowsToUpdate_t& dRows, UpdateContext_t & tCtx, CSphString & sError, bool bDryRun ); bool Update_Blobs ( const RowsToUpdate_t& dRows, UpdateContext_t & tCtx, bool & bCritical, CSphString & sError ); static void Update_Plain ( const RowsToUpdate_t& dRows, UpdateContext_t & tCtx ); public: virtual int Kill ( DocID_t /*tDocID*/ ) { return 0; } virtual int KillMulti ( const VecTraits_T<DocID_t> & /*dKlist*/ ) { return 0; }; virtual int KillDupes () { return 0; } virtual int CheckThenKillMulti ( const VecTraits_T<DocID_t>& dKlist, BlockerFn&& /*fnWatcher*/ ) { return KillMulti ( dKlist ); }; virtual ~IndexSegment_c() = default; inline void SetKillHook ( IndexSegment_c * pKillHook ) const noexcept { m_pKillHook = pKillHook; } inline bool HasKillHook () const noexcept { return m_pKillHook!=nullptr; } inline void KillHook ( DocID_t tDocID ) const noexcept { if ( HasKillHook() ) m_pKillHook->Kill ( tDocID ); } public: bool Update_UpdateAttributes ( const RowsToUpdate_t& dRows, UpdateContext_t& tCtx, bool& bCritical, CSphString& sError ); /// apply serie of updates, assuming them prepared (no need to full-scan attributes), and index is offline, i.e. no concurrency virtual void UpdateAttributesOffline ( VecTraits_T<PostponedUpdate_t>& dPostUpdates ) {} inline void ResetPostponedUpdates() { m_bAttrsBusy = false; m_dPostponedUpdates.Reset(); } public: // stuff for dispatch races between changes and updates mutable std::atomic<bool> m_bAttrsBusy { false }; CSphVector<PostponedUpdate_t> m_dPostponedUpdates; }; bool Update_CheckAttributes ( const CSphAttrUpdate& tUpd, const ISphSchema& tSchema, CSphString& sError ); // helper - collects killed documents struct KillAccum_t final : public IndexSegment_c { CSphVector<DocID_t> m_dDocids; int Kill ( DocID_t tDocID ) final { m_dDocids.Add ( tDocID ); return 1; } }; class Histogram_i; class HistogramContainer_c; struct UpdatedAttribute_t { CSphAttrLocator m_tLocator; CSphRefcountedPtr<ISphExpr> m_pExpr; Histogram_i * m_pHistogram {nullptr}; ESphAttr m_eAttrType {SPH_ATTR_NONE}; TypeConversion_e m_eConversion {CONVERSION_NONE}; bool m_bExisting {false}; int m_iSchemaAttr = -1; }; struct UpdateContext_t { AttrUpdateInc_t & m_tUpd; const ISphSchema & m_tSchema; const HistogramContainer_c * m_pHistograms {nullptr}; CSphRowitem * m_pAttrPool {nullptr}; BYTE * m_pBlobPool {nullptr}; int m_iStride {0}; CSphFixedVector<UpdatedAttribute_t> m_dUpdatedAttrs; // manipulation schema (1 item per column of schema) CSphBitvec m_dSchemaUpdateMask; DWORD m_uUpdateMask {0}; bool m_bBlobUpdate {false}; int m_iJsonWarnings {0}; UpdateContext_t ( AttrUpdateInc_t & tUpd, const ISphSchema & tSchema ); void PrepareListOfUpdatedAttributes ( CSphString& sError ); bool HandleJsonWarnings ( int iUpdated, CSphString& sWarning, CSphString& sError ) const; CSphRowitem* GetDocinfo ( RowID_t tRowID ) const; }; class DocstoreAddField_i; void SetupDocstoreFields ( DocstoreAddField_i & tFields, const CSphSchema & tSchema ); bool CheckStoredFields ( const CSphSchema & tSchema, const CSphIndexSettings & tSettings, CSphString & sError ); class DiskIndexQwordTraits_c; DiskIndexQwordTraits_c * sphCreateDiskIndexQword ( bool bInlineHits ); /// returns ranker name as string const char * sphGetRankerName ( ESphRankMode eRanker ); struct DocstoreDoc_t { CSphVector<CSphVector<BYTE>> m_dFields; }; // used to fetch documents from docstore by docids class DocstoreReader_i { public: virtual ~DocstoreReader_i() = default; virtual void CreateReader ( int64_t iSessionId ) const {} virtual bool GetDoc ( DocstoreDoc_t & tDoc, DocID_t tDocID, const VecTraits_T<int> * pFieldIds, int64_t iSessionId, bool bPack ) const = 0; virtual int GetFieldId ( const CSphString & sName, DocstoreDataType_e eType ) const = 0; }; bool IsMlock ( FileAccess_e eType ); bool IsOndisk ( FileAccess_e eType ); Bson_t EmptyBson(); // returns correct size even if iBuf is 0 int GetReadBuffer ( int iBuf ); class ISphMatchSorter; class CSphSource; struct CSphSourceStats; class DebugCheckError_i; struct AttrAddRemoveCtx_t; class Docstore_i; class SIContainer_c; enum ESphExt : BYTE; /// generic fulltext index interface class CSphIndex : public ISphKeywordsStat, public IndexSegment_c, public DocstoreReader_i, public IndexFileBase_c { public: CSphIndex ( CSphString sIndexName, CSphString sFilename ); ~CSphIndex() override; const CSphString & GetLastError() const { return m_sLastError; } const CSphString & GetLastWarning() const { return m_sLastWarning; } virtual const CSphSchema & GetMatchSchema() const { return m_tSchema; } ///< match schema as returned in result set (possibly different from internal storage schema!) void SetInplaceSettings ( int iHitGap, float fRelocFactor, float fWriteFactor ); // fixme! build only void SetFieldFilter ( std::unique_ptr<ISphFieldFilter> pFilter ); const ISphFieldFilter * GetFieldFilter() const { return m_pFieldFilter.get(); } void SetTokenizer ( TokenizerRefPtr_c pTokenizer ); void SetupQueryTokenizer(); TokenizerRefPtr_c GetTokenizer () const; TokenizerRefPtr_c GetQueryTokenizer () const; TokenizerRefPtr_c& ModifyTokenizer (); void SetDictionary ( DictRefPtr_c pDict ); DictRefPtr_c GetDictionary () const; virtual void SetKeepAttrs ( const CSphString & , const StrVec_t & ) {} // fixme! build only virtual void Setup ( const CSphIndexSettings & tSettings ); const CSphIndexSettings & GetSettings () const { return m_tSettings; } virtual bool IsRT() const { return false; } virtual bool IsPQ() const { return false; } void SetBinlog ( bool bBinlog ) { m_bBinlog = bBinlog; } virtual int64_t * GetFieldLens() const { return nullptr; } virtual bool IsStarDict ( bool bWordDict ) const; int64_t GetIndexId() const { return m_iIndexId; } void SetMutableSettings ( const MutableIndexSettings_c & tSettings ); const MutableIndexSettings_c & GetMutableSettings () const { return m_tMutableSettings; } virtual std::pair<int64_t,int> GetPseudoShardingMetric ( const VecTraits_T<const CSphQuery> & dQueries, const VecTraits_T<int64_t> & dMaxCountDistinct, int iThreads, bool & bForceSingleThread ) const { return { 0, 0 }; } virtual bool MustRunInSingleThread ( const VecTraits_T<const CSphQuery> & dQueries, bool bHasSI, const VecTraits_T<int64_t> & dMaxCountDistinct, bool & bForceSingleThread ) const; virtual int64_t GetCountDistinct ( const CSphString & sAttr, CSphString & sModifiedAttr ) const { return -1; } // returns values if index has some meta on its attributes virtual int64_t GetCountFilter ( const CSphFilterSettings & tFilter, CSphString & sModifiedAttr ) const { return -1; } // returns values if index has some meta on its attributes virtual int64_t GetCount() const { return -1; } public: /// build index by indexing given sources virtual int Build ( const CSphVector<CSphSource*> & dSources, int iMemoryLimit, int iWriteBuffer, CSphIndexProgress & ) = 0; // fixme! build only /// build index by mering current index with given index virtual bool Merge ( CSphIndex * pSource, const VecTraits_T<CSphFilterSettings> & dFilters, bool bSupressDstDocids, CSphIndexProgress & tProgress ) = 0; // fixme! build only public: /// check all data files, preload schema, and preallocate enough RAM to load memory-cached data virtual bool Prealloc ( bool bStripPath, FilenameBuilder_i * pFilenameBuilder, StrVec_t & dWarnings ) = 0; /// deallocate all previously preallocated shared data virtual void Dealloc () = 0; /// precache everything which needs to be precached virtual void Preread () = 0; /// set new index base path, and physically rename index files too enum RenameResult_e { RE_OK, RE_FAIL, RE_FATAL }; virtual RenameResult_e RenameEx ( CSphString sNewBase ) = 0; bool Rename ( CSphString sNewBase ) { return RenameEx (std::move(sNewBase))==RE_OK; } /// obtain exclusive lock on this index virtual bool Lock () = 0; /// dismiss exclusive lock and unlink lock file virtual void Unlock () = 0; /// called when index is loaded and prepared to work virtual void PostSetup(); public: /// return index document, bytes totals (FIXME? remove this in favor of GetStatus() maybe?) virtual const CSphSourceStats & GetStats () const = 0; /// return additional index info virtual void GetStatus ( CSphIndexStatus* ) const = 0; public: virtual bool EarlyReject ( CSphQueryContext * pCtx, CSphMatch & tMatch ) const = 0; void SetCacheSize ( int iMaxCachedDocs, int iMaxCachedHits ); /// one regular query vs many sorters (like facets, or similar for common-tree optimization) virtual bool MultiQuery ( CSphQueryResult & tResult, const CSphQuery & tQuery, const VecTraits_T<ISphMatchSorter *> & dSorters, const CSphMultiQueryArgs & tArgs ) const = 0; /// many regular queries with one sorter attached to each query. /// returns true if at least one query succeeded. The failed queries indicated with pResult->m_iMultiplier==-1 virtual bool MultiQueryEx ( int iQueries, const CSphQuery * pQueries, CSphQueryResult* pResults, ISphMatchSorter ** ppSorters, const CSphMultiQueryArgs & tArgs ) const = 0; virtual bool GetKeywords ( CSphVector <CSphKeywordInfo> & dKeywords, const char * szQuery, const GetKeywordsSettings_t & tSettings, CSphString * pError ) const = 0; virtual void GetSuggest ( const SuggestArgs_t & , SuggestResult_t & ) const {} virtual Bson_t ExplainQuery ( const CSphString & sQuery ) const { return EmptyBson(); } public: /// returns non-negative amount of actually found and updated records on success /// on failure, -1 is returned and GetLastError() contains error message int UpdateAttributes ( AttrUpdateSharedPtr_t pUpd, bool & bCritical, CSphString & sError, CSphString & sWarning ); int UpdateAttributes ( AttrUpdateInc_t & tUpd, bool & bCritical, CSphString & sError, CSphString & sWarning ); /// update accumulating state virtual int CheckThenUpdateAttributes ( AttrUpdateInc_t& tUpd, bool& bCritical, CSphString& sError, CSphString& sWarning ) = 0; virtual Binlog::CheckTnxResult_t ReplayTxn ( CSphReader & tReader, CSphString & sError, BYTE uOp, Binlog::CheckTxn_fn&& fnCheck ) = 0; Binlog::CheckTnxResult_t ReplayUpdate ( CSphReader &, CSphString &, Binlog::CheckTxn_fn && ); /// saves memory-cached attributes, if there were any updates to them /// on failure, false is returned and GetLastError() contains error message virtual bool SaveAttributes ( CSphString & sError ) const = 0; virtual DWORD GetAttributeStatus () const = 0; virtual bool AddRemoveAttribute ( bool bAddAttr, const AttrAddRemoveCtx_t & tCtx, CSphString & sError ) = 0; virtual bool AddRemoveField ( bool bAdd, const CSphString & sFieldName, DWORD, CSphString & sError ) = 0; virtual void FlushDeadRowMap ( bool bWaitComplete ) const {} virtual bool LoadKillList ( CSphFixedVector<DocID_t> * pKillList, KillListTargets_c & tTargets, CSphString & sError ) const { return true; } virtual bool AlterKillListTarget ( KillListTargets_c & tTargets, CSphString & sError ) { return false; } virtual void KillExistingDocids ( CSphIndex * pTarget ) const {} virtual bool IsAlive ( DocID_t tDocID ) const { return false; } bool GetDoc ( DocstoreDoc_t & tDoc, DocID_t tDocID, const VecTraits_T<int> * pFieldIds, int64_t iSessionId, bool bPack ) const override { return false; } int GetFieldId ( const CSphString & sName, DocstoreDataType_e eType ) const override { return -1; } public: /// internal debugging hook, DO NOT USE virtual void DebugDumpHeader ( FILE * fp, const CSphString& sHeaderName, bool bConfig ) = 0; /// internal debugging hook, DO NOT USE virtual void DebugDumpDocids ( FILE * fp ) = 0; /// internal debugging hook, DO NOT USE virtual void DebugDumpHitlist ( FILE * fp, const char * sKeyword, bool bID ) = 0; /// internal debugging hook, DO NOT USE virtual void DebugDumpDict ( FILE * fp, bool bDumpOnly ) = 0; /// internal debugging hook, DO NOT USE virtual int DebugCheck ( DebugCheckError_i & , FilenameBuilder_i * ) = 0; virtual void SetDebugCheck ( bool bCheckIdDups, int iCheckChunk ) {} /// getter for name. Notice, const char* returned as it is mostly used for printing name const char * GetName () const { return m_sIndexName.cstr(); } void SetName ( CSphString sNewName ) { m_sIndexName = std::move ( sNewName ); } /// get actual index files list virtual void GetIndexFiles ( StrVec_t& dFiles, StrVec_t& dExt, const FilenameBuilder_i* = nullptr ) const {} /// internal make document id list from external docinfo, DO NOT USE virtual CSphVector<SphAttr_t> BuildDocList () const; virtual void GetFieldFilterSettings ( CSphFieldFilterSettings & tSettings ) const; // used for query optimizer calibration virtual HistogramContainer_c * Debug_GetHistograms() const { return nullptr; } virtual const SIContainer_c * Debug_GetSI() const { return nullptr; } virtual Docstore_i * GetDocstore() const { return nullptr; } virtual columnar::Columnar_i * GetColumnar() const { return nullptr; } virtual const DWORD * GetRawAttrs() const { return nullptr; } virtual const BYTE * GetRawBlobAttrs() const { return nullptr; } virtual bool AlterSI ( CSphString & sError ) { return true; } const CSphBitvec & GetMorphFields () const { return m_tMorphFields; } public: int64_t m_iTID = 0; ///< last committed transaction id int m_iChunk = 0; int m_iExpansionLimit = 0; protected: int64_t m_iIndexId; ///< internal (per daemon) unique index id, introduced for caching CSphSchema m_tSchema; CSphString m_sLastError; CSphString m_sLastWarning; bool m_bInplaceSettings = false; // fixme! build only int m_iHitGap = 0; // fixme! build only float m_fRelocFactor { 0.0f }; // fixme! build only float m_fWriteFactor { 0.0f }; // fixme! build only bool m_bBinlog = true; protected: CSphIndexSettings m_tSettings; MutableIndexSettings_c m_tMutableSettings; std::unique_ptr<ISphFieldFilter> m_pFieldFilter; TokenizerRefPtr_c m_pTokenizer; TokenizerRefPtr_c m_pQueryTokenizer; TokenizerRefPtr_c m_pQueryTokenizerJson; DictRefPtr_c m_pDict; CSphBitvec m_tMorphFields; int m_iMaxCachedDocs = 0; int m_iMaxCachedHits = 0; private: CSphString m_sIndexName; ///< index ID in binlogging; otherwise used only in messages. Use GetName()! public: virtual void SetGlobalIDFPath ( const CSphString & sPath ) { m_sGlobalIDFPath = sPath; } float GetGlobalIDF ( const CSphString & sWord, int64_t iDocsLocal, bool bPlainIDF ) const; bool HasGlobalIDF () const; protected: CSphString m_sGlobalIDFPath; }; const CSphSourceStats& GetStubStats(); bool CheckDocsCount ( int64_t iDocs, CSphString & sError ); // dummy implementation which makes most of the things optional (makes all non-disk idxes much simpler) class CSphIndexStub : public CSphIndex { public: FWD_CTOR ( CSphIndexStub, CSphIndex ) int Build ( const CSphVector<CSphSource *> &, int, int, CSphIndexProgress& ) override { return 0; } bool Merge ( CSphIndex *, const VecTraits_T<CSphFilterSettings> &, bool, CSphIndexProgress & ) override { return false; } bool Prealloc ( bool, FilenameBuilder_i *, StrVec_t & ) override { return false; } void Dealloc () override {} void Preread () override {} RenameResult_e RenameEx ( CSphString ) override { return RE_FAIL; } bool Lock () override { return true; } void Unlock () override {} bool EarlyReject ( CSphQueryContext * , CSphMatch & ) const override { return false; } const CSphSourceStats & GetStats () const override { return GetStubStats(); } void GetStatus ( CSphIndexStatus* ) const override {} bool GetKeywords ( CSphVector <CSphKeywordInfo> & , const char * , const GetKeywordsSettings_t & tSettings, CSphString * ) const override { return false; } bool FillKeywords ( CSphVector <CSphKeywordInfo> & ) const override { return true; } int CheckThenUpdateAttributes ( AttrUpdateInc_t&, bool &, CSphString & , CSphString & ) override { return -1; } Binlog::CheckTnxResult_t ReplayTxn ( CSphReader &, CSphString &, BYTE, Binlog::CheckTxn_fn&& ) override { return {}; } bool SaveAttributes ( CSphString & ) const override { return true; } DWORD GetAttributeStatus () const override { return 0; } bool AddRemoveAttribute ( bool, const AttrAddRemoveCtx_t & tCtx, CSphString & sError ) override { return true; } bool AddRemoveField ( bool, const CSphString &, DWORD, CSphString & ) override { return true; } void DebugDumpHeader ( FILE *, const CSphString&, bool ) override {} void DebugDumpDocids ( FILE * ) override {} void DebugDumpHitlist ( FILE * , const char * , bool ) override {} int DebugCheck ( DebugCheckError_i & , FilenameBuilder_i * ) override { return 0; } void DebugDumpDict ( FILE *, bool bDumpOnly ) override {} Bson_t ExplainQuery ( const CSphString & sQuery ) const override { return EmptyBson (); } bool MultiQuery ( CSphQueryResult & , const CSphQuery & , const VecTraits_T<ISphMatchSorter *> &, const CSphMultiQueryArgs & ) const override { return false; } bool MultiQueryEx ( int iQueries, const CSphQuery * pQueries, CSphQueryResult* pResults, ISphMatchSorter ** ppSorters, const CSphMultiQueryArgs & tArgs ) const override { // naive stub implementation without common subtree cache and/or any other optimizations bool bResult = false; for ( int i=0; i<iQueries; ++i ) if ( MultiQuery ( pResults[i], pQueries[i], { ppSorters+i, 1}, tArgs ) ) bResult = true; else pResults[i].m_pMeta->m_iMultiplier = -1; // -1 means 'error' return bResult; } }; // update attributes with index pointer attached struct CSphAttrUpdateEx { AttrUpdateSharedPtr_t m_pUpdate; ///< the unchangeable update pool CSphIndex * m_pIndex = nullptr; ///< the index on which the update should happen CSphString * m_pError = nullptr; ///< the error, if any CSphString * m_pWarning = nullptr; ///< the warning, if any int m_iAffected = 0; ///< num of updated rows. }; class RowBuffer_i; struct SphQueueSettings_t { const ISphSchema & m_tSchema; QueryProfile_c * m_pProfiler; bool m_bComputeItems = false; CSphVector<BYTE> * m_pCollection = nullptr; ISphExprHook * m_pHook = nullptr; const CSphFilterSettings * m_pAggrFilter = nullptr; int m_iMaxMatches = DEFAULT_MAX_MATCHES; bool m_bNeedDocids = false; bool m_bGrouped = false; // are we going to push already grouped matches to it? std::function<int64_t (const CSphString &, CSphString &)> m_fnGetCountDistinct; std::function<int64_t (const CSphFilterSettings &, CSphString &)> m_fnGetCountFilter; std::function<int64_t ()> m_fnGetCount; bool m_bEnableFastDistinct = false; bool m_bForceSingleThread = false; StrVec_t m_dCreateSchema; std::unique_ptr<JoinArgs_t> m_pJoinArgs; RowBuffer_i* m_pSqlRowBuffer; void ** m_ppOpaque1 = nullptr; void ** m_ppOpaque2 = nullptr; explicit SphQueueSettings_t ( const ISphSchema & tSchema, QueryProfile_c * pProfiler = nullptr, RowBuffer_i * pSqlRowBuffer = nullptr, void ** ppOpaque1 = nullptr, void ** ppOpaque2 = nullptr ) : m_tSchema ( tSchema ) , m_pProfiler ( pProfiler ) , m_pSqlRowBuffer ( pSqlRowBuffer ) , m_ppOpaque1 ( ppOpaque1 ) , m_ppOpaque2 ( ppOpaque2 ) {} }; struct SphQueueRes_t : public ISphNoncopyable { DWORD m_uPackedFactorFlags = SPH_FACTOR_DISABLE; bool m_bZonespanlist = false; bool m_bAlowMulti = true; bool m_bJoinedGroupSort = false; }; ///////////////////////////////////////////////////////////////////////////// /// create phrase fulltext index implementation std::unique_ptr<CSphIndex> sphCreateIndexPhrase ( CSphString sIndexName, CSphString sFilename ); /// create template (tokenizer) index implementation std::unique_ptr<CSphIndex> sphCreateIndexTemplate ( CSphString sIndexName ); /// set JSON attribute indexing options /// bStrict is whether to stop indexing on error, or just ignore the attribute value /// bAutoconvNumbers is whether to auto-convert eligible (!) strings to integers and floats, or keep them as strings /// bKeynamesToLowercase is whether to convert all key names to lowercase void sphSetJsonOptions ( bool bStrict, bool bAutoconvNumbers, bool bKeynamesToLowercase ); /// setup per-keyword read buffer sizes void SetUnhintedBuffer ( int iReadUnhinted ); int GetUnhintedBuffer(); void SetPseudoSharding ( bool bSet ); bool GetPseudoSharding(); void SetPseudoShardingThresh ( int iThresh ); struct BuildBufferSettings_t; void SetMergeSettings ( const BuildBufferSettings_t & tSettings ); ////////////////////////////////////////////////////////////////////////// volatile bool & sphGetbCpuStat () noexcept; // Access to global TFO settings volatile int& sphGetTFO() noexcept; #define TFO_CONNECT 1 #define TFO_LISTEN 2 #define TFO_ABSENT (-1) ///////////////////////////////////////////////////////////////////////////// // workaround to suppress C4511/C4512 warnings (copy ctor and assignment operator) in VS 2003 #if _MSC_VER>=1300 && _MSC_VER<1400 #pragma warning(disable:4511) #pragma warning(disable:4512) #endif // suppress C4201 (nameless struct/union is a nonstandard extension) because even min-spec gcc 3.4.6 works ok #if defined(_MSC_VER) #pragma warning(disable:4201) #endif #endif // _sphinx_
53,778
C++
.h
1,200
42.725
221
0.705575
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,181
taskglobalidf.h
manticoresoftware_manticoresearch/src/taskglobalidf.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // /// @file taskglobalidf.h /// Task to check and rotate global IDF when necessary #pragma once void RotateGlobalIdf ();
597
C++
.h
15
38.666667
80
0.753448
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,182
searchdtask.h
manticoresoftware_manticoresearch/src/searchdtask.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // /// @file searchdtask.h /// Task manager #pragma once #include "sphinxutils.h" #include "threadutils.h" using TaskID = int; namespace TaskManager { struct TaskInfo_t { CSphString m_sName; // informational name (for logs, etc.) int m_iMaxRunners = 0; // max num of threads running jobs from the same task, 0=unlimited std::atomic<int> m_iCurrentRunners { 0 }; // current number of running jobs std::atomic<int> m_iAllRunners { 0 }; // current number of enqueued+running jobs std::atomic<int> m_iTotalDropped { 0 }; // current number of jobs for this task. std::atomic<int64_t> m_iTotalSpent { 0 }; // total time spend to this job std::atomic<int64_t> m_iTotalRun { 0 }; // total N of times job invoked std::atomic<int64_t> m_iLastFinished { 0 }; // timestamp when last job finished }; /*! * @brief Register global task flavour. * @param sName - informational name of the task, will be used for logging, etc. * @param iThreads - max num of parallel jobs of the class (0=infinite) * @return integer ID which has to be used to schedule/start jobs of that kind. */ TaskID RegisterGlobal ( CSphString sName, int iThreads = 0 ); /*! * @brief schedule job which will be engaged at given time (in microseconds). Scheduling will not run the * job, but just schedule it, so it doesn't honour job's queue limit (however it will be honoured when * the time to run the jub appears). * @param iTask - kind of job (registered with RegisterGlobal) * @param iTimestamp - time (absolute) when job need to be executed * @param fnJob - task route */ void ScheduleJob ( TaskID iTask, int64_t iTimeStampUS, Threads::Handler fnJob ); /*! * @brief enqueue job which will be run ASAP. For MT jobs queue's limit will be honored, so exceeding job will * be immediately dropped. For ST only if limit=0 job will be dropped, for other values it will be executed. * @param iTask - kind of job (registered with RegisterGlobal) * @param fnJob - task route */ void StartJob ( TaskID iTask, Threads::Handler fnJob ); VecTraits_T<TaskInfo_t> GetTaskInfo (); }
2,583
C++
.h
54
45.537037
111
0.725288
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,183
indexfiles.h
manticoresoftware_manticoresearch/src/indexfiles.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #pragma once #include "sphinxstd.h" #include "sphinxint.h" #include "indexfilebase.h" #include <utility> enum ESphExt : BYTE { SPH_EXT_SPH, SPH_EXT_SPA, SPH_EXT_SPB, SPH_EXT_SPC, SPH_EXT_SPI, SPH_EXT_SPD, SPH_EXT_SPP, SPH_EXT_SPK, SPH_EXT_SPE, SPH_EXT_SPM, SPH_EXT_SPT, SPH_EXT_SPHI, SPH_EXT_SPDS, SPH_EXT_SPL, SPH_EXT_SETTINGS, SPH_EXT_SPIDX, SPH_EXT_SPJIDX, SPH_EXT_SPKNN, SPH_EXT_TOTAL }; struct IndexFileExt_t { ESphExt m_eExt; const char * m_szExt; DWORD m_uMinVer; bool m_bOptional; bool m_bCopy; // file needs to be copied const char * m_szDesc; }; CSphVector<IndexFileExt_t> sphGetExts(); const char* sphGetExt ( ESphExt eExt ); /// encapsulates all common actions over index files in general (copy/rename/delete etc.) class IndexFiles_c : public IndexFileBase_c { DWORD m_uVersion = INDEX_FORMAT_VERSION; CSphString m_sIndexName; // used for information purposes (logs) CSphString m_sLastError; bool m_bFatal = false; // if fatal fail happened (unable to rename during rollback) CSphString FullPath ( const char * szExt, const CSphString& sSuffix = "", const CSphString& sBase = "" ); inline void SetName ( CSphString sIndex ) { m_sIndexName = std::move(sIndex); } public: IndexFiles_c() = default; explicit IndexFiles_c ( CSphString sBase, const char* sIndex=nullptr, DWORD uVersion = INDEX_FORMAT_VERSION ) : IndexFileBase_c { std::move ( sBase ) } , m_uVersion ( uVersion ) { if ( sIndex ) SetName ( sIndex ); } inline const char * ErrorMsg () const { return m_sLastError.cstr(); } inline bool IsFatal() const { return m_bFatal; } // read .sph and adopt index version from there. bool CheckHeader ( const char * sType="" ); // read the beginning of .spk and parse killlist targets bool ReadKlistTargets ( StrVec_t & dTargets, const char * sType="" ); DWORD GetVersion() const { return m_uVersion; } // simple make decorated path, like '.old' -> /path/to/index.old CSphString MakePath ( const char * szSuffix = "" ); static CSphString MakePath ( const char* szSuffix, const CSphString& sBase ); bool TryRename ( const CSphString& sFrom, const CSphString& sTo ); // move with auto backup and rollback bool Rename ( const CSphString& sFrom, const CSphString& sTo ); // oneshot move without backups bool TryRenameSuffix ( const CSphString& sFromSuffix, const CSphString& sToSuffix ); // move files in base between two suffixes bool TryRenameBase ( const CSphString& sToBase ); // move files to different base bool RenameLock ( const CSphString& sTo, int & iLockFD ); // safely move lock file bool RelocateToNew ( const CSphString& sNewBase ); // relocate to new base and append '.new' suffix bool RenameSuffix ( const CSphString& sFrom, const CSphString& sTo ); // move from backup to active; fail is fatal bool HasAllFiles ( const char * szType = "" ); // check that all necessary files are readable void Unlink ( const char * szType = "" ); void UnlinkExisted (); // if prev op fails with fatal error - log the message and terminate CSphString FatalMsg(const char * szMsg=nullptr); };
3,571
C++
.h
90
37.755556
129
0.7347
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,184
query_status.h
manticoresoftware_manticoresearch/src/query_status.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #pragma once #include "sphinxstd.h" // that is legacy func, extracted from daemon with it's legacy environment void QueryStatus ( CSphVariant * v );
628
C++
.h
15
40.666667
80
0.755738
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,185
compressed_zlib_mysql.h
manticoresoftware_manticoresearch/src/compressed_zlib_mysql.h
// // Copyright (c) 2021-2024, Manticore Software LTD (https://manticoresearch.com) // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #pragma once #include "networking_daemon.h" #if WITH_ZLIB bool IsZlibCompressionAvailable(); // Replace pSource with it's compressed version. // Mysql proto will be wrapped into compressed. void MakeZlibMysqlCompressedLayer ( std::unique_ptr<AsyncNetBuffer_c> & pSource ); #else inline bool IsZlibCompressionAvailable() { return false; } inline void MakeZlibMysqlCompressedLayer ( std::unique_ptr<AsyncNetBuffer_c> & pSource ) { }; #endif
824
C++
.h
20
39.9
93
0.775689
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,186
searchdbuddy.h
manticoresoftware_manticoresearch/src/searchdbuddy.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #pragma once #include "sphinxstd.h" #include "searchdhttp.h" void BuddyStart ( const CSphString & sConfigPath, const CSphString & sPluginDir, bool bHasBuddyPath, const VecTraits_T<ListenerDesc_t> & dListeners, bool bTelemetry, int iThreads, const CSphString & sConfigFilePath, const CSphString & sDataDir ); void BuddyShutdown (); bool HasBuddy(); bool IsBuddyQuery ( const OptionsHash_t & hOptions ); bool ProcessHttpQueryBuddy ( HttpProcessResult_t & tRes, Str_t sSrcQuery, OptionsHash_t& hOptions, CSphVector<BYTE>& dResult, bool bNeedHttpResponse, http_method eRequestType ); void ProcessSqlQueryBuddy ( Str_t sSrcQuery, Str_t sError, std::pair<int, BYTE> tSavedPos, BYTE& uPackedID, GenericOutputBuffer_c& tOut );
1,200
C++
.h
20
58.75
246
0.777021
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,187
queuecreator.h
manticoresoftware_manticoresearch/src/queuecreator.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #pragma once #include "sphinxsort.h" #include "grouper.h" /// additional group-by sorter settings struct CSphGroupSorterSettings { CSphAttrLocator m_tLocGroupby; ///< locator for @groupby CSphAttrLocator m_tLocCount; ///< locator for @count CSphAttrLocator m_tLocDistinct; ///< locator for @distinct CSphAttrLocator m_tLocGroupbyStr; ///< locator for @groupbystr bool m_bDistinct = false;///< whether we need distinct CSphRefcountedPtr<CSphGrouper> m_pGrouper;///< group key calculator CSphRefcountedPtr<DistinctFetcher_i> m_pDistinctFetcher; bool m_bImplicit = false;///< for queries with aggregate functions but without group by clause SharedPtr_t<ISphFilter> m_pAggrFilterTrait; ///< aggregate filter that got owned by grouper bool m_bJson = false; ///< whether we're grouping by Json attribute int m_iMaxMatches = 0; bool m_bGrouped = false; ///< are we going to push already grouped matches to it? int m_iDistinctAccuracy = 16; ///< HyperLogLog accuracy. 0 means "don't use HLL" void FixupLocators ( const ISphSchema * pOldSchema, const ISphSchema * pNewSchema ); void SetupDistinctAccuracy ( int iThresh ); }; struct PrecalculatedSorterResults_t { int64_t m_iCountDistinct = -1; int64_t m_iCountFilter = -1; int64_t m_iCount = -1; CSphString m_sAttr; }; /// creates proper queue for given query /// may return NULL on error; in this case, error message is placed in sError /// if the pUpdate is given, creates the updater's queue and perform the index update /// instead of searching ISphMatchSorter * sphCreateQueue ( const SphQueueSettings_t & tQueue, const CSphQuery & tQuery, CSphString & sError, SphQueueRes_t & tRes, StrVec_t * pExtra = nullptr, QueryProfile_c * pProfile = nullptr ); void sphCreateMultiQueue ( const SphQueueSettings_t & tQueue, const VecTraits_T<CSphQuery> & dQueries, VecTraits_T<ISphMatchSorter *> & dSorters, VecTraits_T<CSphString> & dErrors, SphQueueRes_t & tRes, StrVec_t * pExtra, QueryProfile_c * pProfile ); bool HasImplicitGrouping ( const CSphQuery & tQuery ); bool sphHasExpressions ( const CSphQuery & tQuery, const CSphSchema & tSchema ); // check query for expressions int GetAliasedAttrIndex ( const CSphString & sAttr, const CSphQuery & tQuery, const ISphSchema & tSchema ); bool IsGroupbyMagic ( const CSphString & s ); ESphAttr DetermineNullMaskType ( int iNumAttrs ); const char * GetInternalAttrPrefix(); const char * GetInternalJsonPrefix(); bool IsSortStringInternal ( const CSphString & sColumnName ); bool IsSortJsonInternal ( const CSphString & sColumnName ); CSphString SortJsonInternalSet ( const CSphString & sColumnName );
3,136
C++
.h
56
54.5
252
0.76099
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,188
memio_impl.h
manticoresoftware_manticoresearch/src/memio_impl.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org // template<typename VECTOR> inline void GetArray ( VECTOR& dBuf, MemoryReader_c& tIn ) { int iCount = tIn.GetDword(); if ( !iCount ) return; dBuf.Resize ( iCount ); tIn.GetBytes ( dBuf.Begin(), (int)dBuf.GetLengthBytes() ); } inline void GetArray ( CSphVector<CSphString>& dBuf, MemoryReader_c& tIn ) { int iCount = tIn.GetDword(); if ( !iCount ) return; dBuf.Resize ( iCount ); for ( CSphString& sVal : dBuf ) sVal = tIn.GetString(); } template<typename T> T GetVal ( MemoryReader_c& tReader ) { T tVal; tReader.GetBytes ( &tVal, sizeof ( tVal ) ); return tVal; } template<typename T> T MemoryReader_c::GetVal () { return ::GetVal<T> (*this); } template<typename T> void MemoryReader_c::GetVal ( T& tVal ) { tVal = GetVal<T>(); } inline SphOffset_t MemoryReader_c::GetOffset() { return GetVal<SphOffset_t> (); } inline DWORD MemoryReader_c::GetDword() { return GetVal<DWORD> (); } template<typename T> void PutVal ( MemoryWriter_c& tWriter, T tVal ) { tWriter.PutBytes ( (BYTE*)&tVal, sizeof ( tVal ) ); } template<typename T> void MemoryWriter_c::PutVal ( T tVal ) { ::PutVal ( *this, tVal ); } inline void MemoryWriter_c::PutDword ( DWORD uVal ) { PutVal ( uVal ); } inline void MemoryWriter_c::PutOffset ( SphOffset_t uValue ) { PutVal ( uValue ); } inline void MemoryWriter_c::PutWord ( WORD uVal ) { PutVal ( uVal ); } inline void MemoryWriter_c::PutUint64 ( uint64_t uVal ) { PutVal ( uVal ); } template<typename T> inline void SaveArray ( const VecTraits_T<T>& dBuf, MemoryWriter_c& tOut ) { tOut.PutDword ( dBuf.GetLength() ); if ( dBuf.GetLength() ) tOut.PutBytes ( dBuf.Begin(), dBuf.GetLengthBytes() ); } inline void SaveArray ( const VecTraits_T<CSphString>& dBuf, MemoryWriter_c& tOut ) { tOut.PutDword ( dBuf.GetLength() ); for ( const CSphString& sVal : dBuf ) tOut.PutString ( sVal ); }
2,330
C++
.h
93
23.483871
83
0.719694
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,189
frontendschema.h
manticoresoftware_manticoresearch/src/frontendschema.h
// // Copyright (c) 2017-2023, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #pragma once #include "searchdaemon.h" class FrontendSchemaBuilder_c { public: FrontendSchemaBuilder_c ( const AggrResult_t & tRes, const CSphQuery & tQuery, const CSphVector<CSphQueryItem> & dItems, const CSphVector<CSphQueryItem> & dQueryItems, const sph::StringSet & hExtraColumns, bool bQueryFromAPI, bool bHaveLocals ); bool Build ( bool bMaster, CSphString & sError ); void PopulateSchema ( CSphSchema & tSchema ) { tSchema.SwapAttrs(m_dFrontend); } private: const AggrResult_t & m_tRes; const CSphQuery & m_tQuery; const CSphVector<CSphQueryItem> & m_dItems; const CSphVector<CSphQueryItem> & m_dQueryItems; const sph::StringSet & m_hExtraColumns; bool m_bQueryFromAPI; bool m_bHaveLocals; bool m_bAgent; CSphVector<CSphColumnInfo> m_dFrontend; CSphVector<int> m_dKnownAttrs; CSphVector<int> m_dUnmappedAttrs; void CollectKnownItems(); void AddAttrs(); void AddNullMask(); bool CheckUnmapped ( CSphString & sError ) const; void Finalize(); void RemapGroupBy(); void RemapFacets(); };
1,542
C++
.h
39
37.74359
246
0.750837
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,190
indexfilebase.h
manticoresoftware_manticoresearch/src/indexfilebase.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #pragma once #include "std/string.h" #include <utility> enum ESphExt : BYTE; class IndexFileBase_c { CSphString m_sFileBase; // prefix (i.e. folder + index name, excluding extensions) public: IndexFileBase_c() = default; explicit IndexFileBase_c ( CSphString sFileBase ) : m_sFileBase { std::move ( sFileBase ) } {} /// set new index base path void SetFilebase ( CSphString sNewBase ) { m_sFileBase = std::move ( sNewBase ); } /// get for the base file name const char* GetFilebase() const { return m_sFileBase.cstr(); } /// build filename CSphString GetFilename ( const char* szExt ) const; CSphString GetFilename ( int iSuffix ) const; CSphString GetFilename ( ESphExt eExt ) const; CSphString GetTmpFilename ( ESphExt eExt ) const; };
1,238
C++
.h
33
35.787879
83
0.742475
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,191
digest_sha1.h
manticoresoftware_manticoresearch/src/digest_sha1.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #pragma once #include "sphinxstd.h" #include "fileio.h" #include <array> /// SHA1 digests static constexpr int HASH20_SIZE = 20; using HASH20_t = std::array<BYTE, HASH20_SIZE>; class SHA1_c { class Impl_c; std::unique_ptr<Impl_c> m_pImpl; public: SHA1_c(); ~SHA1_c(); void Init(); void Update ( const BYTE* pData, int iLen ); void Final ( HASH20_t& tDigest ); HASH20_t FinalHash(); }; // string and 20-bytes hash struct TaggedHash20_t { CSphString m_sTagName; HASH20_t m_dHashValue { 0 }; // by tag + hash explicit TaggedHash20_t ( const char* sTag = nullptr, const BYTE* pHashValue = nullptr ); TaggedHash20_t ( const char* sTag, const HASH20_t& dHashValue ); // convert to FIPS-180-1 [[nodiscard]] CSphString ToFIPS() const; // load from FIPS-180-1 int FromFIPS ( const char* sFIPS ); // compare with raw hash bool operator== ( const BYTE * pRef ) const; [[nodiscard]] inline bool Empty() const noexcept { return *this==m_dZeroHash.data(); } // helper zero hash inline static const HASH20_t m_dZeroHash {}; }; // file writer with hashing on-the-fly. class WriterWithHash_c final: public CSphWriter { public: WriterWithHash_c (); void Flush () final; void CloseFile (); // get resulting BLOB [[nodiscard]] HASH20_t GetHASHBlob () const noexcept { return m_dHashValue; } private: std::unique_ptr<SHA1_c> m_pHasher; bool m_bHashDone = false; HASH20_t m_dHashValue{}; }; //CSphString BinToHex ( const VecTraits_T<BYTE>& dHash ); CSphString BinToHex ( const HASH20_t& dHash ); CSphString BinToHexx ( const BYTE* pHash, int iLen ); CSphString CalcSHA1 ( const void* pData, int iLen ); bool CalcSHA1 ( const CSphString& sFileName, CSphString& sRes, CSphString& sError );
2,191
C++
.h
67
30.970149
90
0.732067
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,192
hazard_pointer.h
manticoresoftware_manticoresearch/src/hazard_pointer.h
// // Copyright (c) 2021-2024, Manticore Software LTD (https://manticoresearch.com) // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #pragma once #include "sphinxstd.h" #include <atomic> // Hazard pointers implementation /* * Main idea: as long as somebody uses an object, we should not delete it. * To achieve it, two things in use: * 1. When we have to delete an object, we call hazard::Retire, providing pointer to the obj, * or raw (void*) ptr and deleter function which has to be called with that ptr for cleaning. * 2. When access obj from the other thread by pointer, we access it via Guard_c::Protect. * It ensures, that pointer is saved in thread-local set of hazard pointers. * * At the moment when thread-local list of retired object full, we collect all hazard pointers from all threads * and then filter our list of retired: if an object is not pointed by anyone, it is finally removed. * * Since hazard pointer protection intended for local variables only, just few hazard slots provided for each object * (usually 1 or 2 is enough). * * Since hazard pointer is thread-local, avoid switch context having some variable protected this way, * since yielding in one thread and awaking in another will lead to race of hazard pointer in original thread, * and since it is hot place, we want to keep it simpler (avoid any mt-related problem). * * RAII wrapper hazard::Ptr_T * * Comparing to ref-counting, hazard pointers are faster, since uses just light atomic store for saving pointers, * and avoids heavy compare-and-swap as used in atomic counters. * */ namespace hazard { // 2 pointers per thread should be enough for the beginning static const int POINTERS_PER_THREAD = 2; // backend pointer type using Pointer_t = void*; // ref to fn which actualy deletes the object of given type using Deleter_fn = void ( * ) ( void * ); // Free the object. It will be deleted now or later by gc void Retire ( Pointer_t pData, Deleter_fn fnDelete, bool bNow=false ); template<typename PTR> void Retire ( PTR pData, bool bNow=false ) { Retire ( (Pointer_t) pData, Deleter_T<PTR, ETYPE::SINGLE>::Delete, bNow ); } template<typename PTR> void RetireArray ( PTR pData, bool bNow=false ) { Retire ( (Pointer_t) pData, Deleter_T<PTR, ETYPE::ARRAY>::Delete, bNow ); } // collect indexes of collection which is still used using Accessor_fn = std::function<void*(int)>; CSphVector<int> GetListOfPointed ( Accessor_fn&& fnAccess, int iCount ); template<typename T> CSphVector<int> GetListOfPointed ( const VecTraits_T<T>& dCollection ) { return GetListOfPointed ( [&] ( int iIdx ) { return &dCollection[iIdx]; }, dCollection.GetLength () ); } // RAII hazard pointer. // on d-tr pointee (if any) will be postponed for deletion template<typename PTR, typename DELETER> class ScopedPtr_T : ISphNoncopyable { using ATOMIC_PTR = std::atomic<PTR>; ATOMIC_PTR m_pPtr { nullptr }; public: ///< default ctr (for vectors) explicit ScopedPtr_T () = default; /// construction from raw pointer explicit ScopedPtr_T ( PTR pPtr ) { m_pPtr.store ( pPtr, std::memory_order_release ); } ScopedPtr_T ( ScopedPtr_T && rhs ) noexcept { Swap ( rhs ); } ~ScopedPtr_T () { Retire ( (void*)m_pPtr.load ( std::memory_order_relaxed ), DELETER::Delete ); } void Swap ( ScopedPtr_T & rhs ) noexcept { using namespace std; // just to make following line shorter m_pPtr.store ( rhs.m_pPtr.exchange ( m_pPtr.load(memory_order_acquire), memory_order_acq_rel ), memory_order_release ); } PTR operator-> () const noexcept { return m_pPtr.load ( std::memory_order_relaxed ); } explicit operator bool () const noexcept { return m_pPtr.load ( std::memory_order_relaxed )!=nullptr; } explicit operator PTR () const noexcept { return m_pPtr.load ( std::memory_order_relaxed ); } explicit operator ATOMIC_PTR& () noexcept { return m_pPtr; } // special case: assign new value and try to prune previous immediately void RetireNow ( PTR pPtr=nullptr ) { Retire ( (Pointer_t) m_pPtr.exchange ( pPtr, std::memory_order_acq_rel ), DELETER::Delete, true ); } /// assignment of a raw pointer, retires previous value ScopedPtr_T & operator= ( PTR pPtr ) { Retire ( (Pointer_t) m_pPtr.exchange ( pPtr, std::memory_order_acq_rel ), DELETER::Delete ); return *this; } }; template<typename T> using ScopedPtr_t = ScopedPtr_T<T, Deleter_T<T, ETYPE::SINGLE>>; template<typename T> using ScopedArr_t = ScopedPtr_T<T, Deleter_T<T, ETYPE::ARRAY>>; template<typename PTR> hazard::ScopedPtr_t <PTR> MakeScopedPtr ( PTR pPtr ) { return hazard::ScopedPtr_t<PTR> ( pPtr ); } // hazard pointer store struct AtomicPointer_t { std::atomic<Pointer_t> m_pData; void Set ( const void * pData ) { m_pData.store ( (Pointer_t)const_cast<void*>(pData), std::memory_order_release ); } }; // allocates hazard slot and then may protect any variable. // while it is protected, it can't be deleted in any other thread. class Guard_c : ISphNoncopyable { AtomicPointer_t* m_pGuard; public: Guard_c(); ~Guard_c(); template <typename PTR> PTR Protect ( const std::atomic<PTR>& pMtVal ) { assert ( m_pGuard ); // we need to be sure that assigned value is exactly the one existing in pMtVal // so, if after assign we found that it is changed - repeat assigning again. PTR pAssignedPtr; PTR pCurrentPtr = pMtVal.load ( std::memory_order_relaxed ); do { pAssignedPtr = pCurrentPtr; m_pGuard->Set ( pCurrentPtr ); pCurrentPtr = pMtVal.load ( std::memory_order_acquire ); } while ( pAssignedPtr!=pCurrentPtr ); return pCurrentPtr; } template<typename PTR, typename DELETER> PTR Protect ( const ScopedPtr_T<PTR,DELETER> & pMtVal ) { return Protect ( (const std::atomic<PTR>&) pMtVal ); } // simple unset current guard - to reuse the slot without reallocating. void Release () { assert ( m_pGuard ); m_pGuard->Set ( nullptr ); } }; // helper, to be called from shutdown. Try to finally delete all weak objects. // returns num of still alive. If it is non-zero - it means, some threads still alive, // and points to the objects in their hazard pointers. void Shutdown (); } // namespace hazard
6,419
C++
.h
178
34.073034
121
0.732474
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,193
networking_daemon.h
manticoresoftware_manticoresearch/src/networking_daemon.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #pragma once #include "sphinxstd.h" #include "searchdha.h" #include "netpoll.h" #include "pollable_event.h" extern int64_t g_tmWaitUS; extern int g_iThrottleAction; extern int g_iThrottleAccept; static constexpr Str_t g_sMaxedOutMessage = FROMS("maxed out, dismissing client"); struct Listener_t { int m_iSock; bool m_bTcp; Proto_e m_eProto; bool m_bVIP; bool m_bReadOnly; }; class CSphNetLoop; struct ISphNetAction : NetPollEvent_t { explicit ISphNetAction ( int iSock ) : NetPollEvent_t ( iSock ) {} /// callback for network polling when something happened on subscribed socket. /// it is called for processing result of epoll/kqueue/iocp linked with a socket /// @brief process network event (ready to read / ready to write / error) /// /// timer is always removed when processing. virtual void Process () = 0; /// invoked when CSphNetLoop with this action destroying /// Netloop itself is finished, no further actions in process. virtual void NetLoopDestroying () REQUIRES ( NetPoollingThread ) = 0; protected: ~ISphNetAction() = default; }; // event that wakes-up poll net loop from finished thread pool job // declared here to make available for testing class CSphWakeupEvent final : public PollableEvent_t, public ISphNetAction { public: CSphWakeupEvent (); void Process () final; void Wakeup (); void NetLoopDestroying() final; protected: ~CSphWakeupEvent () final; }; using WakeupEventRefPtr_c = CSphRefcountedPtr<CSphWakeupEvent>; ///////////////////////////////////////////////////////////////////////////// /// NETWORK THREAD ///////////////////////////////////////////////////////////////////////////// class CSphNetLoop : public ISphRefcountedMT { class Impl_c; std::unique_ptr<Impl_c> m_pImpl; protected: ~CSphNetLoop () override; public: CSphNetLoop (); void SetListeners ( const VecTraits_T<Listener_t>& dListeners ); void LoopNetPoll () REQUIRES ( NetPoollingThread ); void StopNetLoop (); bool AddAction ( ISphNetAction * pElem ) EXCLUDES ( NetPoollingThread ); void RemoveEvent ( NetPollEvent_t * pEvent ) REQUIRES ( NetPoollingThread ); }; CSphNetLoop* GetAvailableNetLoop(); void SetAvailableNetLoop( CSphNetLoop* ); // redirect async socket io to netloop class SockWrapper_c { class Impl_c; Impl_c * m_pImpl = nullptr; public: SockWrapper_c ( int iSocket, CSphNetLoop* pNetLoop ); ~SockWrapper_c (); int64_t SockRecv ( char * pData, int64_t iLen ); int64_t SockSend ( const char * pData, int64_t iLen ); int SockPoll ( int64_t tmTimeUntil, bool bWrite ); int64_t GetTimeoutUS() const; void SetTimeoutUS( int64_t iTimeoutUS ); int64_t GetWTimeoutUS () const; void SetWTimeoutUS ( int64_t iTimeoutUS ); int64_t GetTotalSent () const; int64_t GetTotalReceived () const; int GetSocket () const; }; /// simple network request buffer class AsyncNetInputBuffer_c : protected LazyVector_T<BYTE>, public InputBuffer_c { protected: using STORE = LazyVector_T<BYTE>; static const int NET_MINIBUFFER_SIZE = STORE::iSTATICSIZE; bool m_bIntr = false; /// lowest func to implement. /// Read to the end any chunk of iNeed..iHaveSpace bytes. Return num of bytes read, or -1 on error. /// @iNeed is strict N user expects. For example, it needs 100 bytes, 90 are in buffer, and 10 he /// needs extra. So, less than 10 bytes is fail. /// @iSpace is how many bytes (at least) available to reserve. That is to obey g_iMaxPacketSize. /// Reader should allocate need space by AllocateBuffer call, using this param or other hints virtual int ReadFromBackend ( int iNeed, int iSpace, bool bIntr ) = 0; /// for iNeed==0 just try oneshot non-blocking read try to look if anything at all arived. /// returns -1 on error, or N of appended bytes. /// iSpace limits max quantity of data (limited by g_iMaxPacketSize), however m.b. ignored by compressed backends int AppendData ( int iNeed, int iSpace, bool bIntr ); /// internal - return place available to not exceed m_iMaxPacketSize. Dispose consumed data, if necesary. int GetRoomForTail(); /// internal - discard processed data, then ensure at least iSpace is available, and return blob for it. /// ReadFromBackend on return will process results right way, nothing will be lost or ignored. VecTraits_T<BYTE> AllocateBuffer ( int iSpace ); public: AsyncNetInputBuffer_c (); /// read at least 1 byte, and up to g_iMaxPacketSize int ReadAny (); /// try to peek first bytes from socket and imagine proto from this Proto_e Probe (); /// Ensure we have iLen bytes available in buffer. If not - read new chunk from backend. /// return true on success bool ReadFrom ( int iLen, bool bIntr = true ); /// discards processed data from the buf, releasing space. /// @param iHowMany determines behaviour as /// =0 - relaxed discard. If something in buf unprocessed, just skip /// any positive - forcibly remove this many bytes back from current position, then rewind /// -1 - forcibly remove whole chunk from start to current position, then rewind void DiscardProcessed ( int iHowMany = 0 ); /// returns true, if we're interrupted by signal. Fixme! Check, if we still need to use this func. bool IsIntr () const { return m_bIntr; } /// look what is in buf, but NOT pop ByteBlob_t Tail (); /// take part or whole unused content of the buf ByteBlob_t PopTail ( int iSize=-1 ); /// write uNewVal to iPos, related to current position. Return previous byte from there. /// m.b. used to temporary zero-terminate blob for processing, and then revert back BYTE Terminate ( int iPos, BYTE uNewVal ); /// len from current position to the end of backend vector. using InputBuffer_c::HasBytes; /// set timeout for backend, in microseconds virtual void SetTimeoutUS ( int64_t iTimeoutUS ) = 0; /// get timeout from backend, in microseconds virtual int64_t GetTimeoutUS () const = 0; /// get total N of bytes received via this buffer virtual int64_t GetTotalReceived() const = 0; }; class AsyncNetBuffer_c : public AsyncNetInputBuffer_c, public GenericOutputBuffer_c { public: void SyncErrorState(); void ResetError(); }; std::unique_ptr<AsyncNetBuffer_c> MakeAsyncNetBuffer ( std::unique_ptr<SockWrapper_c> pSock ); void LogNetError ( const char * sMsg, bool bDebug=false );
6,757
C++
.h
159
40.610063
114
0.732987
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,194
indexsettings.h
manticoresoftware_manticoresearch/src/indexsettings.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #ifndef _indexsettings_ #define _indexsettings_ #include "sphinxstd.h" #include "sphinxutils.h" #include "fileutils.h" #include "sphinxexpr.h" #include "columnarlib.h" #include "sphinxdefs.h" #include "schema/columninfo.h" inline int64_t cast2signed ( SphWordID_t tVal ) { return *(int64_t*)&tVal; } class CSphWriter; class CSphReader; class FilenameBuilder_i; enum { // where was TOKENIZER_SBCS=1 once TOKENIZER_UTF8 = 2, TOKENIZER_NGRAM = 3 }; struct CSphEmbeddedFiles { bool m_bEmbeddedSynonyms = false; bool m_bEmbeddedStopwords = false; bool m_bEmbeddedWordforms = false; CSphSavedFile m_tSynonymFile; StrVec_t m_dSynonyms; CSphVector<CSphSavedFile> m_dStopwordFiles; CSphVector<SphWordID_t> m_dStopwords; StrVec_t m_dWordforms; CSphVector<CSphSavedFile> m_dWordformFiles; void Reset(); }; class SettingsFormatter_c; struct SettingsFormatterState_t; namespace bson { class Bson_c; } class SettingsWriter_c { public: virtual ~SettingsWriter_c() = default; virtual void DumpReadable ( SettingsFormatterState_t & tState, const CSphEmbeddedFiles & tEmbeddedFiles, FilenameBuilder_i * pFilenameBuilder ) const; virtual void Format ( SettingsFormatter_c & tOut, FilenameBuilder_i * pFilenameBuilder ) const = 0; }; class CSphTokenizerSettings : public SettingsWriter_c { public: int m_iType { TOKENIZER_UTF8 }; CSphString m_sCaseFolding; int m_iMinWordLen = 1; CSphString m_sSynonymsFile; CSphString m_sBoundary; CSphString m_sIgnoreChars; int m_iNgramLen = 0; CSphString m_sNgramChars; CSphString m_sBlendChars; CSphString m_sBlendMode; void Setup ( const CSphConfigSection & hIndex, CSphString & sWarning ); bool Load ( const FilenameBuilder_i * pFilenameBuilder, CSphReader & tReader, CSphEmbeddedFiles & tEmbeddedFiles, CSphString & sWarning ); bool Load ( const FilenameBuilder_i* pFilenameBuilder, const bson::Bson_c& tNode, CSphEmbeddedFiles& tEmbeddedFiles, CSphString& sWarning ); void DumpReadable ( SettingsFormatterState_t & tState, const CSphEmbeddedFiles & tEmbeddedFiles, FilenameBuilder_i * pFilenameBuilder ) const override; void Format ( SettingsFormatter_c & tOut, FilenameBuilder_i * pFilenameBuilder ) const override; }; class CSphDictSettings : public SettingsWriter_c { public: CSphString m_sMorphology; CSphString m_sMorphFields; CSphString m_sStopwords; StrVec_t m_dWordforms; int m_iMinStemmingLen = 1; bool m_bWordDict = true; bool m_bStopwordsUnstemmed = false; CSphString m_sMorphFingerprint; ///< not used for creation; only for a check when loading void Setup ( const CSphConfigSection & hIndex, FilenameBuilder_i * pFilenameBuilder, CSphString & sWarning ); void Load ( CSphReader & tReader, CSphEmbeddedFiles & tEmbeddedFiles, FilenameBuilder_i * pFilenameBuilder, CSphString & sWarning ); void Load ( const bson::Bson_c & tNode, CSphEmbeddedFiles& tEmbeddedFiles, FilenameBuilder_i * pFilenameBuilder, CSphString & sWarning ); void DumpReadable ( SettingsFormatterState_t & tState, const CSphEmbeddedFiles & tEmbeddedFiles, FilenameBuilder_i * pFilenameBuilder ) const override; void Format ( SettingsFormatter_c & tOut, FilenameBuilder_i * pFilenameBuilder ) const override; }; class Writer_i; class CSphFieldFilterSettings : public SettingsWriter_c { public: StrVec_t m_dRegexps; bool Setup ( const CSphConfigSection & hIndex, CSphString & sWarning ); void Load ( CSphReader & tReader ); void Save ( Writer_i & tWriter ) const; void Format ( SettingsFormatter_c & tOut, FilenameBuilder_i * pFilenameBuilder ) const override; }; struct KillListTarget_t { enum { USE_KLIST = 1 << 0, USE_DOCIDS = 1 << 1 }; CSphString m_sIndex; DWORD m_uFlags {USE_KLIST|USE_DOCIDS}; CSphString Format() const; }; class KillListTargets_c : public SettingsWriter_c { public: CSphVector<KillListTarget_t> m_dTargets; bool Parse ( const CSphString & sTargets, const char * szIndexName, CSphString & sError ); void Format ( SettingsFormatter_c & tOut, FilenameBuilder_i * pFilenameBuilder ) const override; }; /// indexing-related source settings /// NOTE, newly added fields should be synced with CSphSource::Setup() class CSphSourceSettings { public: int m_iMinInfixLen = 0; ///< min indexable infix length (0 means don't index infixes) int m_iMaxSubstringLen = 0; ///< max indexable infix and prefix (0 means don't limit infixes and prefixes) int m_iBoundaryStep = 0; ///< additional boundary word position increment bool m_bIndexExactWords = false; ///< exact (non-stemmed) word indexing flag int m_iOvershortStep = 1; ///< position step on overshort token (default is 1) int m_iStopwordStep = 1; ///< position step on stopword token (default is 1) bool m_bIndexSP = false; ///< whether to index sentence and paragraph delimiters bool m_bIndexFieldLens = false; ///< whether to index field lengths StrVec_t m_dPrefixFields; ///< list of prefix fields StrVec_t m_dInfixFields; ///< list of infix fields StrVec_t m_dStoredFields; ///< list of stored fields StrVec_t m_dStoredOnlyFields; ///< list of "fields" that are stored but not indexed AttrEngine_e m_eEngine = AttrEngine_e::DEFAULT; ///< attribute storage engine AttrEngine_e m_eDefaultEngine = AttrEngine_e::ROWWISE; ///< default storage engine set by daemon StrVec_t m_dColumnarAttrs; ///< list of attributes to be placed in columnar store StrVec_t m_dColumnarNonStoredAttrs; ///< list of columnar attributes that should be not added to document storage StrVec_t m_dRowwiseAttrs; ///< list of attributes to NOT be placed in columnar store StrVec_t m_dColumnarStringsNoHash; ///< list of columnar string attributes that don't need pregenerated hashes StrVec_t m_dJsonSIAttrs; ///< list of JSON attributes that need secondary indexes generated CSphVector<NamedKNNSettings_t> m_dKNN; ///< knn index settings ESphWordpart GetWordpart ( const char * sField, bool bWordDict ); int GetMinPrefixLen ( bool bWordDict ) const; void SetMinPrefixLen ( int iMinPrefixLen ); int RawMinPrefixLen () const; private: int m_iMinPrefixLen = 0; ///< min indexable prefix (0 means don't index prefixes) }; enum class Preprocessor_e { NONE, ///< no preprocessor ICU, ///< ICU chinese preprocessor JIEBA ///< Jieba chinese preprocessor }; enum class Compression_e { NONE, LZ4, LZ4HC }; CSphString CompressionToStr ( Compression_e eComp ); const DWORD DEFAULT_DOCSTORE_BLOCK = 16384; const int DEFAULT_COMPRESSION_LEVEL = 9; struct DocstoreSettings_t : public SettingsWriter_c { Compression_e m_eCompression = Compression_e::LZ4; int m_iCompressionLevel = DEFAULT_COMPRESSION_LEVEL; DWORD m_uBlockSize = DEFAULT_DOCSTORE_BLOCK; void Format ( SettingsFormatter_c & tOut, FilenameBuilder_i * pFilenameBuilder ) const override; }; enum ESphHitless { SPH_HITLESS_NONE = 0, ///< all hits are present SPH_HITLESS_SOME = 1, ///< some of the hits might be omitted (check the flag bit) SPH_HITLESS_ALL = 2 ///< no hits in this index }; enum ESphHitFormat { SPH_HIT_FORMAT_PLAIN = 0, ///< all hits are stored in hitlist SPH_HIT_FORMAT_INLINE = 1 ///< hits can be split and inlined into doclist (aka 9-23) }; enum ESphBigram : BYTE { SPH_BIGRAM_NONE = 0, ///< no bigrams SPH_BIGRAM_ALL = 1, ///< index all word pairs SPH_BIGRAM_FIRSTFREQ = 2, ///< only index pairs where one of the words is in a frequent words list SPH_BIGRAM_BOTHFREQ = 3 ///< only index pairs where both words are in a frequent words list }; enum class JiebaMode_e { NONE, ACCURATE, FULL, SEARCH, DEFAULT = ACCURATE }; class CSphIndexSettings : public CSphSourceSettings, public DocstoreSettings_t { public: ESphHitFormat m_eHitFormat = SPH_HIT_FORMAT_PLAIN; bool m_bHtmlStrip = false; CSphString m_sHtmlIndexAttrs; CSphString m_sHtmlRemoveElements; CSphString m_sZones; ESphHitless m_eHitless = SPH_HITLESS_NONE; CSphString m_sHitlessFiles; int m_iEmbeddedLimit = 0; SphOffset_t m_tBlobUpdateSpace {0}; int m_iSkiplistBlockSize {32}; KillListTargets_c m_tKlistTargets; ///< list of indexes to apply killlist to ESphBigram m_eBigramIndex = SPH_BIGRAM_NONE; CSphString m_sBigramWords; StrVec_t m_dBigramWords; DWORD m_uAotFilterMask = 0; ///< lemmatize_XX_all forces us to transform queries on the index level too Preprocessor_e m_ePreprocessor = Preprocessor_e::NONE; JiebaMode_e m_eJiebaMode = JiebaMode_e::DEFAULT; bool m_bJiebaHMM = true; CSphString m_sJiebaUserDictPath; CSphString m_sIndexTokenFilter; ///< indexing time token filter spec string (pretty useless for disk, vital for RT) bool m_bBinlog = true; bool Setup ( const CSphConfigSection & hIndex, const char * szIndexName, CSphString & sWarning, CSphString & sError ); void Format ( SettingsFormatter_c & tOut, FilenameBuilder_i * pFilenameBuilder ) const override; private: void ParseStoredFields ( const CSphConfigSection & hIndex ); bool ParseColumnarSettings ( const CSphConfigSection & hIndex, CSphString & sError ); bool ParseKNNSettings ( const CSphConfigSection & hIndex, CSphString & sError ); bool ParseSISettings ( const CSphConfigSection & hIndex, CSphString & sError ); bool ParseDocstoreSettings ( const CSphConfigSection & hIndex, CSphString & sWarning, CSphString & sError ); bool ParseCJKSegmentation ( const CSphConfigSection & hIndex, const StrVec_t & dMorphs, CSphString & sWarning, CSphString & sError ); }; enum class FileAccess_e { FILE, MMAP, MMAP_PREREAD, MLOCK, UNKNOWN }; enum class MutableName_e { EXPAND_KEYWORDS, RT_MEM_LIMIT, PREOPEN, ACCESS_PLAIN_ATTRS, ACCESS_BLOB_ATTRS, ACCESS_DOCLISTS, ACCESS_HITLISTS, ACCESS_DICT, READ_BUFFER_DOCS, READ_BUFFER_HITS, OPTIMIZE_CUTOFF, GLOBAL_IDF, TOTAL }; const int DEFAULT_READ_BUFFER = 256*1024; const int DEFAULT_READ_UNHINTED = 32768; struct FileAccessSettings_t : public SettingsWriter_c { FileAccess_e m_eAttr = FileAccess_e::MMAP_PREREAD; FileAccess_e m_eBlob = FileAccess_e::MMAP_PREREAD; FileAccess_e m_eDoclist = FileAccess_e::FILE; FileAccess_e m_eHitlist = FileAccess_e::FILE; FileAccess_e m_eDict = FileAccess_e::MMAP_PREREAD; int m_iReadBufferDocList = DEFAULT_READ_BUFFER; int m_iReadBufferHitList = DEFAULT_READ_BUFFER; bool operator== ( const FileAccessSettings_t & tOther ) const; bool operator!= ( const FileAccessSettings_t & tOther ) const; void Format ( SettingsFormatter_c & tOut, FilenameBuilder_i * pFilenameBuilder ) const override; }; class MutableIndexSettings_c : public SettingsWriter_c { public: int m_iExpandKeywords; int64_t m_iMemLimit; bool m_bPreopen = false; FileAccessSettings_t m_tFileAccess; int m_iOptimizeCutoff; CSphString m_sGlobalIDFPath; MutableIndexSettings_c(); static MutableIndexSettings_c & GetDefaults(); bool Load ( const char * sFileName, const char * sIndexName ); void Load ( const CSphConfigSection & hIndex, bool bNeedSave, StrVec_t * pWarnings ); bool Save ( CSphString & sBuf ) const; bool NeedSave() const { return m_bNeedSave; } bool HasSettings() const { return ( m_dLoaded.BitCount()>0 ); } bool IsSet ( MutableName_e eOpt ) const { return ( HasSettings() && m_dLoaded.BitGet ( (int)eOpt ) ); } void Format ( SettingsFormatter_c & tOut, FilenameBuilder_i * ) const override; void Combine ( const MutableIndexSettings_c & tOther ); private: CSphBitvec m_dLoaded; bool m_bNeedSave = false; }; struct RtTypedAttr_t { ESphAttr m_eType; const char * m_szName; }; int GetNumRtTypes(); const RtTypedAttr_t & GetRtType ( int iType ); bool StrToAttrEngine ( AttrEngine_e & eEngine, AttrEngine_e eDefault, const CSphString & sValue, CSphString & sError ); struct CreateTableAttr_t { CSphColumnInfo m_tAttr; bool m_bFastFetch = true; bool m_bStringHash = true; bool m_bIndexed = false; bool m_bKNN = false; knn::IndexSettings_t m_tKNN; }; struct NameValueStr_t { CSphString m_sName; CSphString m_sValue; }; struct CreateTableSettings_t { CSphString m_sLike; bool m_bIfNotExists = false; CSphVector<CreateTableAttr_t> m_dAttrs; CSphVector<CSphColumnInfo> m_dFields; CSphVector<NameValueStr_t> m_dOpts; }; class IndexSettingsContainer_i { public: virtual ~IndexSettingsContainer_i() {}; virtual bool Populate ( const CreateTableSettings_t & tCreateTable, bool bExtCopy ) = 0; virtual bool Add ( const char * szName, const CSphString & sValue ) = 0; virtual bool Add ( const CSphString & sName, const CSphString & sValue ) = 0; virtual CSphString Get ( const CSphString & sName ) const =0 ; virtual bool Contains ( const char * szName ) const = 0; virtual void RemoveKeys ( const CSphString & sName ) = 0; virtual bool AddOption ( const CSphString & sName, const CSphString & sValue, bool bExtCopy ) = 0; virtual bool CheckPaths() = 0; virtual bool CopyExternalFiles ( const CSphString & sIndexPath, int iSuffix ) = 0; virtual void ResetCleanup() = 0; virtual const CSphConfigSection & AsCfg() const = 0; virtual const CSphString & GetError() const = 0; }; IndexSettingsContainer_i * CreateIndexSettingsContainer (); class ISphTokenizer; class CSphDict; class CSphIndex; class Writer_i; void SaveTokenizerSettings ( Writer_i & tWriter, const TokenizerRefPtr_c& pTokenizer, int iEmbeddedLimit ); void SaveDictionarySettings ( Writer_i & tWriter, const DictRefPtr_c& pDict, bool bForceWordDict, int iEmbeddedLimit ); void DumpSettings ( StringBuilder_c & tBuf, const CSphIndex & tIndex, FilenameBuilder_i * pFilenameBuilder ); void DumpSettingsCfg ( FILE * fp, const CSphIndex & tIndex, FilenameBuilder_i * pFilenameBuilder ); void DumpReadable ( FILE * fp, const CSphIndex & tIndex, const CSphEmbeddedFiles & tEmbeddedFiles, FilenameBuilder_i * pFilenameBuilder ); /// try to set dictionary, tokenizer and misc settings for an index (if not already set) bool sphFixupIndexSettings ( CSphIndex * pIndex, const CSphConfigSection & hIndex, bool bStripFile, FilenameBuilder_i * pFilenameBuilder, StrVec_t & dWarnings, CSphString & sError ); CSphString BuildCreateTable ( const CSphString & sName, const CSphIndex * pIndex, const CSphSchema & tSchema ); // daemon-level callback using CreateFilenameBuilder_fn = std::unique_ptr<FilenameBuilder_i> (*) ( const char * szIndex ); void SetIndexFilenameBuilder ( CreateFilenameBuilder_fn pBuilder ); CreateFilenameBuilder_fn GetIndexFilenameBuilder(); const char * FileAccessName ( FileAccess_e eValue ); FileAccess_e ParseFileAccess ( CSphString sVal ); int ParseKeywordExpansion ( const char * sValue ); void SaveMutableSettings ( const MutableIndexSettings_c & tSettings, const CSphString & sSettingsFile ); FileAccess_e GetFileAccess ( const CSphConfigSection & hIndex, const char * sKey, bool bList, FileAccess_e eDefault ); // combine per-index and per-attribute engine settings AttrEngine_e CombineEngines ( AttrEngine_e eIndexEngine, AttrEngine_e eAttrEngine ); class JsonEscapedBuilder; void operator<< ( JsonEscapedBuilder& tOut, const CSphFieldFilterSettings& tFieldFilterSettings ); void operator<< ( JsonEscapedBuilder& tOut, const CSphIndexSettings& tIndexSettings ); void SaveTokenizerSettings ( JsonEscapedBuilder& tOut, const TokenizerRefPtr_c& pTokenizer, int iEmbeddedLimit ); void SaveDictionarySettings ( JsonEscapedBuilder& tOut, const DictRefPtr_c& pDict, bool bForceWordDict, int iEmbeddedLimit ); void SetDefaultAttrEngine ( AttrEngine_e eEngine ); AttrEngine_e GetDefaultAttrEngine(); bool ForceExactWords ( bool bWordDict, bool bHasMorphology, int iMinPrefixLen, int iMinInfixLen, bool bMorphFieldsEmpty ); void LoadIndexSettingsJson ( bson::Bson_c tNode, CSphIndexSettings & tSettings ); void operator << ( JsonEscapedBuilder & tOut, const CSphIndexSettings & tSettings ); void LoadIndexSettings ( CSphIndexSettings & tSettings, CSphReader & tReader, DWORD uVersion ); void SaveIndexSettings ( Writer_i & tWriter, const CSphIndexSettings & tSettings ); #endif // _indexsettings_
16,525
C++
.h
380
41.644737
183
0.766147
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,195
secondaryindex.h
manticoresoftware_manticoresearch/src/secondaryindex.h
// // Copyright (c) 2018-2024, Manticore Software LTD (https://manticoresearch.com) // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #ifndef _secondaryindex_ #define _secondaryindex_ #include "sphinxstd.h" #include "sphinx.h" #include "columnarmisc.h" #include "costestimate.h" #include "secondary/secondary.h" #include <math.h> #include <vector> using RowIdBlock_t = VecTraits_T<RowID_t>; class RowidIterator_i { public: virtual ~RowidIterator_i(){} virtual bool HintRowID ( RowID_t tRowID ) = 0; virtual bool GetNextRowIdBlock ( RowIdBlock_t & dRowIdBlock ) = 0; virtual int64_t GetNumProcessed() const = 0; virtual void SetCutoff ( int iCutoff ) = 0; virtual bool WasCutoffHit() const = 0; virtual void AddDesc ( CSphVector<IteratorDesc_t> & dDesc ) const = 0; }; using RowIteratorsWithEstimates_t = CSphVector<std::pair<RowidIterator_i *,int64_t>>; class SIContainer_c { friend void operator << ( JsonEscapedBuilder & tOut, const SIContainer_c & tSI ); public: bool Load ( const CSphString & sFile, CSphString & sError ); bool Drop ( const CSphString & sFile, CSphString & sError ); bool IsEmpty() const { return m_dIndexes.IsEmpty(); } void Reset() { m_dIndexes.Reset(); } void ColumnUpdated ( const CSphString & sAttr ); bool SaveMeta ( CSphString & sError ) const; bool CreateIterators ( std::vector<common::BlockIterator_i *> & dIterators, const common::Filter_t & tFilter, const common::RowidRange_t * pBounds, uint32_t uMaxValues, int64_t iRsetSize, int iCutoff, CSphString & sError ) const; int64_t GetCountDistinct ( const CSphString & sAttr ) const; bool CalcCount ( uint32_t & uCount, const common::Filter_t & tFilter, uint32_t uMaxValues, CSphString & sError ) const; uint32_t GetNumIterators ( const common::Filter_t & tFilter ) const; bool IsEnabled ( const CSphString & sAttr ) const; RowIteratorsWithEstimates_t CreateSecondaryIndexIterator ( CSphVector<SecondaryIndexInfo_t> & dSIInfo, const CSphVector<CSphFilterSettings> & dFilters, ESphCollation eCollation, const ISphSchema & tSchema, RowID_t uRowsCount, int iCutoff ) const; private: struct IndexInfo_t { std::unique_ptr<SI::Index_i> m_pIndex; CSphString m_sFile; }; CSphVector<IndexInfo_t> m_dIndexes; }; struct RowIdBoundaries_t; RowidIterator_i * CreateIteratorIntersect ( CSphVector<RowidIterator_i*> & dIterators, const RowIdBoundaries_t * pBoundaries ); RowidIterator_i * CreateIteratorWrapper ( common::BlockIterator_i * pIterator, const RowIdBoundaries_t * pBoundaries ); const CSphFilterSettings * GetRowIdFilter ( const CSphVector<CSphFilterSettings> & dFilters, RowID_t uTotalDocs, RowIdBoundaries_t & tRowidBounds ); bool ReturnIteratorResult ( RowID_t * pRowID, RowID_t * pRowIdStart, RowIdBlock_t & dRowIdBlock ); CSphVector<SecondaryIndexInfo_t> SelectIterators ( const SelectIteratorCtx_t & tCtx, float & fBestCost, StrVec_t & dWarnings ); namespace SI { class Index_i; class Builder_i; } std::unique_ptr<SI::Builder_i> CreateIndexBuilder ( int64_t iMemoryLimit, const CSphSchema & tSchema, CSphBitvec & tSIAttrs, const CSphString & sFile, int iBufferSize, CSphString & sError ); std::unique_ptr<SI::Builder_i> CreateIndexBuilder ( int64_t iMemoryLimit, const CSphSchema & tSchema, const CSphString & sFile, CSphVector<PlainOrColumnar_t> & dAttrs, int iBufferSize, CSphString & sError ); void BuildStoreSI ( RowID_t tRowID, const CSphRowitem * pRow, const BYTE * pPool, CSphVector<ScopedTypedIterator_t> & dIterators, const CSphVector<PlainOrColumnar_t> & dAttrs, SI::Builder_i * pBuilder, CSphVector<int64_t> & dTmp ); #endif // _secondaryindex_
3,857
C++
.h
70
53.342857
247
0.764878
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,196
sphinxstd.h
manticoresoftware_manticoresearch/src/sphinxstd.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #pragma once #include "config.h" #include "std/attrstub.h" #include "std/thread_annotations.h" #include "std/helpers.h" #include "std/ints.h" #include "std/checks.h" #include "std/format.h" #include "std/mem.h" #include "std/bitcount.h" #include "std/fatal.h" #include "std/log2.h" #include "std/crc32.h" #include "std/timers.h" #include "std/rand.h" #include "std/generics.h" #include "std/comp.h" #include "std/accessor.h" #include "std/sort.h" #include "std/binarysearch.h" #include "std/uniq.h" #include "std/blobs.h" #include "std/iterations.h" #include "std/vectraits.h" #include "std/storage.h" #include "std/datamove.h" #include "std/relimit.h" #include "std/vector.h" #include "std/fixedvector.h" #include "std/orderedhash.h" #include "std/string.h" #include "std/variant.h" #include "std/comma.h" #include "std/stringbuilder.h" #include "std/escaped_builder.h" #include "std/scoped_comma.h" #include "std/stringhash.h" #include "std/refptr.h" #include "std/mm.h" #include "std/buffer.h" #include "std/largebuffer.h" #include "std/threadrole.h" #include "std/scopedlock.h" #include "std/mutex.h" #include "std/autoevent.h" #include "std/rwlock.h" #include "std/at_scope_exit.h" #include "std/bitvec.h" #include "std/refcounted_mt.h" #include "std/deleter.h" #include "std/sharedptr.h" #include "std/sys.h" #include "std/queue.h" #include "std/circular_buffer.h" #include "std/tdigest.h" #include "std/zip.h" #include "std/smalloc.h" #include "std/env.h" #include "std/fastlog.h" #include "std/sphwarn.h"
1,991
C++
.h
71
27.014085
80
0.750261
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,197
columnargrouper.h
manticoresoftware_manticoresearch/src/columnargrouper.h
// // Copyright (c) 2020-2024, Manticore Software LTD (https://manticoresearch.com) // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #ifndef _columnargrouper_ #define _columnargrouper_ #include "collation.h" #include "schema/columninfo.h" class CSphGrouper; CSphGrouper * CreateGrouperColumnarInt ( const CSphString & sName, ESphAttr eType ); CSphGrouper * CreateGrouperColumnarString ( const CSphString & sName, ESphCollation eCollation ); CSphGrouper * CreateGrouperColumnarMVA ( const CSphString & sName, ESphAttr eType ); CSphGrouper * CreateGrouperColumnarMulti ( const CSphVector<CSphColumnInfo> & dAttrs, ESphCollation eCollation ); class DistinctFetcher_i; DistinctFetcher_i * CreateColumnarDistinctFetcher ( const CSphString & sName, ESphAttr eType, ESphCollation eCollation ); bool NextSet ( CSphFixedVector<int> & dSet, const CSphFixedVector<CSphVector<int64_t>> & dAllKeys ); #endif // _columnargrouper_
1,168
C++
.h
22
51.818182
121
0.794737
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,198
joinsorter.h
manticoresoftware_manticoresearch/src/joinsorter.h
// // Copyright (c) 2024, Manticore Software LTD (https://manticoresearch.com) // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #pragma once #include "sphinx.h" void SetJoinCacheSize ( int64_t iSize ); int64_t GetJoinCacheSize(); CSphVector<std::pair<int,bool>> FetchJoinRightTableFilters ( const CSphVector<CSphFilterSettings> & dFilters, const ISphSchema & tSchema, const char * szJoinedIndex ); bool NeedToMoveMixedJoinFilters ( const CSphQuery & tQuery, const ISphSchema & tSchema ); std::unique_ptr<ISphFilter> CreateJoinNullFilter ( const CSphFilterSettings & tSettings, const CSphAttrLocator & tNullMapLocator ); ISphMatchSorter * CreateJoinSorter ( const CSphIndex * pIndex, const CSphIndex * pJoinedIndex, const SphQueueSettings_t & tSettings, const CSphQuery & tQuery, ISphMatchSorter * pSorter, bool bJoinedGroupSort, CSphString & sError ); bool CreateJoinMultiSorter ( const CSphIndex * pIndex, const CSphIndex * pJoinedIndex, const SphQueueSettings_t & tSettings, const VecTraits_T<CSphQuery> & dQueries, VecTraits_T<ISphMatchSorter *> & dSorters, CSphString & sError );
1,346
C++
.h
18
73.555556
234
0.780967
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,199
exprremap.h
manticoresoftware_manticoresearch/src/exprremap.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #pragma once class ISphExpr; struct CSphAttrLocator; ISphExpr * CreateExprSortStringFixup ( const CSphAttrLocator & tLoc ); ISphExpr * CreateExprSortJson2String ( const CSphAttrLocator & tLoc, ISphExpr * pExpr );
693
C++
.h
16
42.0625
88
0.771174
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,200
sphinxint.h
manticoresoftware_manticoresearch/src/sphinxint.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #ifndef _sphinxint_ #define _sphinxint_ #include "sphinxstd.h" #include "sphinxfilter.h" #include "sphinxquery.h" #include "sphinxexcerpt.h" #include "sphinxudf.h" #include "sphinxjsonquery.h" #include "sphinxutils.h" #include "fileio.h" #include "match.h" #include "std/openhash.h" #include "dict/dict_base.h" #include <float.h> ////////////////////////////////////////////////////////////////////////// // INTERNAL CONSTANTS ////////////////////////////////////////////////////////////////////////// // used as bufer size in num-to-string conversions #define SPH_MAX_NUMERIC_STR 64 ////////////////////////////////////////////////////////////////////////// const DWORD INDEX_MAGIC_HEADER = 0x58485053; ///< my magic 'SPHX' header const DWORD INDEX_FORMAT_VERSION = 67; ///< added jieba const char MAGIC_CODE_SENTENCE = '\x02'; // emitted from tokenizer on sentence boundary const char MAGIC_CODE_PARAGRAPH = '\x03'; // emitted from stripper (and passed via tokenizer) on paragraph boundary const char MAGIC_CODE_ZONE = '\x04'; // emitted from stripper (and passed via tokenizer) on zone boundary; followed by zero-terminated zone name const char MAGIC_WORD_HEAD = '\x01'; // prepended to keyword by source, stored in (crc) dictionary const char MAGIC_WORD_TAIL = '\x01'; // appended to keyword by source, stored in (crc) dictionary const char MAGIC_WORD_HEAD_NONSTEMMED = '\x02'; // prepended to keyword by source, stored in dictionary const char MAGIC_WORD_BIGRAM = '\x03'; // used as a bigram (keyword pair) separator, stored in dictionary extern const char * MAGIC_WORD_SENTENCE; ///< value is "\3sentence" extern const char * MAGIC_WORD_PARAGRAPH; ///< value is "\3paragraph" const int64_t DEFAULT_RT_MEM_LIMIT = 128 * 1024 * 1024; ////////////////////////////////////////////////////////////////////////// // INTERNAL GLOBALS ////////////////////////////////////////////////////////////////////////// /// costs for max_predicted_time limits, defined in sphinxsearch.cpp /// measured in nanoseconds (that is, 1e-9) extern int g_iPredictorCostSkip; extern int g_iPredictorCostDoc; extern int g_iPredictorCostHit; extern int g_iPredictorCostMatch; extern bool g_bJsonStrict; extern bool g_bJsonAutoconvNumbers; extern bool g_bJsonKeynamesToLowercase; ////////////////////////////////////////////////////////////////////////// // INTERNAL HELPER FUNCTIONS, CLASSES, ETC ////////////////////////////////////////////////////////////////////////// // shorter names for more compact bson #define SZ_TYPE "a" #define SZ_VIRTUALLY_PLAIN "b" #define SZ_CHILDREN "c" #define SZ_OPTIONS "d" #define SZ_FIELDS "e" #define SZ_MAX_FIELD_POS "f" #define SZ_WORD "g" #define SZ_QUERYPOS "h" #define SZ_EXCLUDED "i" #define SZ_EXPANDED "j" #define SZ_FIELD_START "k" #define SZ_FIELD_END "l" #define SZ_MORPHED "m" #define SZ_BOOST "n" #define SZ_ZONES "o" #define SZ_ZONESPANS "p" #define SZ_REGEX "r" /// generic COM-like uids enum ExtraData_e { EXTRA_GET_DATA_ZONESPANS, EXTRA_GET_DATA_ZONESPANLIST, EXTRA_GET_DATA_RANKFACTORS, EXTRA_GET_DATA_PACKEDFACTORS, EXTRA_GET_DATA_RANKER_STATE, EXTRA_GET_QUEUE_WORST, EXTRA_GET_QUEUE_SORTVAL, EXTRA_GET_LAST_INSERT_ID, EXTRA_SET_BLOBPOOL, EXTRA_SET_POOL_CAPACITY, EXTRA_SET_MATCHPUSHED, EXTRA_SET_MATCHPOPPED, EXTRA_SET_MATCHTAG, EXTRA_SET_RANKER_PLUGIN, EXTRA_SET_RANKER_PLUGIN_OPTS, EXTRA_GET_POOL_SIZE, EXTRA_SET_BOUNDARIES, EXTRA_SET_ITERATOR, EXTRA_SET_COLUMNAR, }; /// generic COM-like interface class ISphExtra { public: virtual ~ISphExtra () {} inline bool ExtraData ( ExtraData_e eType, void** ppData ) { return ExtraDataImpl ( eType, ppData ); } private: virtual bool ExtraDataImpl ( ExtraData_e, void** ) { return false; } }; class ISphRanker; class ISphMatchSorter; enum QueryDebug_e { QUERY_DEBUG_NO_PAYLOAD = 1<<0, QUERY_DEBUG_NO_LOG = 1<<1 }; // collect valid schemas from sorters, excluding one CSphVector<const ISphSchema *> SorterSchemas ( const VecTraits_T<ISphMatchSorter *> & dSorters, int iSkipSorter ); // return index of sorter with max schema, and sum match capacity among the sorters std::pair<int, int> GetMaxSchemaIndexAndMatchCapacity ( const VecTraits_T<ISphMatchSorter *> & dSorters ); ////////////////////////////////////////////////////////////////////////// // MEMORY TRACKER ////////////////////////////////////////////////////////////////////////// #define MEM_CATEGORIES \ MEM_CATEGORY(MEM_CORE), \ MEM_CATEGORY(MEM_INDEX_DISK), \ MEM_CATEGORY(MEM_INDEX_RT), \ MEM_CATEGORY(MEM_API_HANDLE ), \ MEM_CATEGORY(MEM_API_SEARCH ), \ MEM_CATEGORY(MEM_API_QUERY ), \ MEM_CATEGORY(MEM_RT_ACCUM), \ MEM_CATEGORY(MEM_MMAPED), \ MEM_CATEGORY(MEM_BINLOG), \ MEM_CATEGORY(MEM_SQL_HANDLE), \ MEM_CATEGORY(MEM_SQL_INSERT), \ MEM_CATEGORY(MEM_SQL_SELECT), \ MEM_CATEGORY(MEM_SQL_DELETE), \ MEM_CATEGORY(MEM_SQL_SET), \ MEM_CATEGORY(MEM_SQL_BEGIN), \ MEM_CATEGORY(MEM_SQL_COMMIT), \ MEM_CATEGORY(MEM_SQL_ALTER), \ MEM_CATEGORY(MEM_DISK_QUERY), \ MEM_CATEGORY(MEM_DISK_QUERYEX), \ MEM_CATEGORY(MEM_RT_QUERY), \ MEM_CATEGORY(MEM_RT_RES_MATCHES), \ MEM_CATEGORY(MEM_RT_RES_STRINGS) #define MEM_CATEGORY(_arg) _arg enum MemCategory_e { MEM_CATEGORIES, MEM_TOTAL }; #undef MEM_CATEGORY #if SPH_ALLOCS_PROFILER void sphMemStatPush ( MemCategory_e eCategory ); void sphMemStatPop ( MemCategory_e eCategory ); // memory tracker struct MemTracker_c : ISphNoncopyable { const MemCategory_e m_eCategory; ///< category /// ctor explicit MemTracker_c ( MemCategory_e eCategory ) : m_eCategory ( eCategory ) { sphMemStatPush ( m_eCategory ); } /// dtor ~MemTracker_c () { sphMemStatPop ( m_eCategory ); } }; #define MEMORY(name) MemTracker_c tracker_##__LINE__##name(name); #else // SPH_ALLOCS_PROFILER 0 #define MEMORY(name) #endif // if SPH_ALLOCS_PROFILER ////////////////////////////////////////////////////////////////////////// // BLOCK-LEVEL ATTRIBUTE INDEX BUILDER ////////////////////////////////////////////////////////////////////////// #define DOCINFO_INDEX_FREQ 128 // FIXME? make this configurable inline int64_t MVA_UPSIZE ( const DWORD * pMva ) { #if USE_LITTLE_ENDIAN return *(int64_t*)( const_cast<DWORD*>(pMva) ); #else int64_t iMva = (int64_t)( (uint64_t)pMva[0] | ( ( (uint64_t)pMva[1] )<<32 ) ); return iMva; #endif } inline std::pair<DWORD,DWORD> MVA_BE ( const DWORD * pMva ) { #if USE_LITTLE_ENDIAN return {pMva[1], pMva[0]}; #else return {pMva[0], pMva[1]}; #endif } class CSphFreeList { private: CSphTightVector<int> m_dFree; int m_iNextFree = 0; #ifndef NDEBUG int m_iSize = 0; #endif public: void Reset ( int iSize ) { #ifndef NDEBUG m_iSize = iSize; #endif m_iNextFree = 0; m_dFree.Reserve ( iSize ); } int Get () { if ( !m_dFree.IsEmpty() ) return m_dFree.Pop (); return m_iNextFree++; } void Free ( int iIndex ) { assert ( iIndex>=0 && iIndex<m_iSize ); m_dFree.Add ( iIndex ); } void Swap ( CSphFreeList& rhs ) noexcept { m_dFree.SwapData ( rhs.m_dFree ); ::Swap ( m_iNextFree, rhs.m_iNextFree ); #ifndef NDEBUG ::Swap ( m_iSize, rhs.m_iSize ); #endif } }; ////////////////////////////////////////////////////////////////////////// // INLINES, FIND_XXX() GENERIC FUNCTIONS ////////////////////////////////////////////////////////////////////////// /// find a value-enclosing span in a sorted vector (aka an index at which vec[i] <= val < vec[i+1]) template < typename T, typename U > FORCE_INLINE int FindSpan ( const VecTraits_T<T> & dVec, U tRef, int iSmallTreshold=8 ) { // empty vector if ( !dVec.GetLength() ) return -1; // check last semi-span if ( dVec.Last()<tRef || dVec.Last()==tRef ) return dVec.GetLength()-1; // linear search for small vectors if ( dVec.GetLength()<=iSmallTreshold ) { for ( int i=0; i<dVec.GetLength()-1; i++ ) if ( ( dVec[i]<tRef || dVec[i]==tRef ) && tRef<dVec[i+1] ) return i; return -1; } // binary search for longer vectors const T * pStart = dVec.Begin(); const T * pEnd = &dVec.Last(); if ( ( pStart[0]<tRef || pStart[0]==tRef ) && tRef<pStart[1] ) return 0; if ( ( pEnd[-1]<tRef || pEnd[-1]==tRef ) && tRef<pEnd[0] ) return int ( pEnd-dVec.Begin()-1 ); while ( pEnd-pStart>1 ) { if ( tRef<*pStart || *pEnd<tRef ) break; assert ( *pStart<tRef ); assert ( tRef<*pEnd ); const T * pMid = pStart + (pEnd-pStart)/2; assert ( pMid+1 < &dVec.Last() ); if ( ( pMid[0]<tRef || pMid[0]==tRef ) && tRef<pMid[1] ) return int ( pMid - dVec.Begin() ); if ( tRef<pMid[0] ) pEnd = pMid; else pStart = pMid; } return -1; } ////////////////////////////////////////////////////////////////////////// // INLINES, UTF-8 TOOLS ////////////////////////////////////////////////////////////////////////// #define SPH_MAX_UTF8_BYTES 4 /// decode UTF-8 codepoint /// advances buffer ptr in all cases, including the end of buffer (ie. zero byte)! /// so eof MUST be handled, otherwise, you get OOB /// /// returns -1 on failure /// returns 0 on end of buffer /// returns codepoint on success inline int sphUTF8Decode ( const BYTE * & pBuf ) { BYTE v = *pBuf++; if ( !v ) return 0; // check for 7-bit case if ( v<128 ) return v; // get number of bytes int iBytes = 0; while ( v & 0x80 ) { iBytes++; v <<= 1; } // check for valid number of bytes if ( iBytes<2 || iBytes>SPH_MAX_UTF8_BYTES ) return -1; int iCode = ( v >> iBytes ); iBytes--; do { if ( !(*pBuf) ) return 0; // unexpected eof if ( ((*pBuf) & 0xC0)!=0x80 ) return -1; // invalid code iCode = ( iCode<<6 ) + ( (*pBuf) & 0x3F ); iBytes--; pBuf++; } while ( iBytes ); // all good return iCode; } /// encode UTF-8 codepoint to buffer, macro version for the Really Critical places #define SPH_UTF8_ENCODE(_ptr,_code) \ if ( (_code)<0x80 ) \ { \ *_ptr++ = (BYTE)( (_code) & 0x7F ); \ } else if ( (_code)<0x800 ) \ { \ _ptr[0] = (BYTE)( ( ((_code)>>6) & 0x1F ) | 0xC0 ); \ _ptr[1] = (BYTE)( ( (_code) & 0x3F ) | 0x80 ); \ _ptr += 2; \ } else if ( (_code)<0x10000 )\ { \ _ptr[0] = (BYTE)( ( ((_code)>>12) & 0x0F ) | 0xE0 ); \ _ptr[1] = (BYTE)( ( ((_code)>>6) & 0x3F ) | 0x80 ); \ _ptr[2] = (BYTE)( ( (_code) & 0x3F ) | 0x80 ); \ _ptr += 3; \ } else \ { \ _ptr[0] = (BYTE)( ( ((_code)>>18) & 0x0F ) | 0xF0 ); \ _ptr[1] = (BYTE)( ( ((_code)>>12) & 0x3F ) | 0x80 ); \ _ptr[2] = (BYTE)( ( ((_code)>>6) & 0x3F ) | 0x80 ); \ _ptr[3] = (BYTE)( ( (_code) & 0x3F ) | 0x80 ); \ _ptr += 4; \ } /// encode UTF-8 codepoint to buffer /// returns number of bytes used inline int sphUTF8Encode ( BYTE * pBuf, int iCode ) { if ( iCode<0x80 ) { pBuf[0] = (BYTE)( iCode & 0x7F ); return 1; } if ( iCode<0x800 ) { pBuf[0] = (BYTE)( ( (iCode>>6) & 0x1F ) | 0xC0 ); pBuf[1] = (BYTE)( ( iCode & 0x3F ) | 0x80 ); return 2; } if ( iCode<0x10000 ) { pBuf[0] = (BYTE)( ( (iCode>>12) & 0x0F ) | 0xE0 ); pBuf[1] = (BYTE)( ( (iCode>>6) & 0x3F ) | 0x80 ); pBuf[2] = (BYTE)( ( iCode & 0x3F ) | 0x80 ); return 3; } pBuf[0] = (BYTE)( ( (iCode>>18) & 0x0F ) | 0xF0 ); pBuf[1] = (BYTE)( ( (iCode>>12) & 0x3F ) | 0x80 ); pBuf[2] = (BYTE)( ( (iCode>>6) & 0x3F ) | 0x80 ); pBuf[3] = (BYTE)( ( iCode & 0x3F ) | 0x80 ); return 4; } /// compute UTF-8 string length in codepoints inline int sphUTF8Len ( const char * pStr ) { if ( !pStr || *pStr=='\0' ) return 0; const BYTE * pBuf = (const BYTE*) pStr; int iRes = 0, iCode; while ( ( iCode = sphUTF8Decode(pBuf) )!=0 ) if ( iCode>0 ) iRes++; return iRes; } /// compute UTF-8 string length in codepoints inline int sphUTF8Len ( const char * pStr, int iMax ) { if ( !pStr || *pStr=='\0' ) return 0; const BYTE * pBuf = (const BYTE*) pStr; int iRes = 0, iCode; while ( pBuf<( (const BYTE *) pStr+iMax ) && iRes<iMax && ( iCode = sphUTF8Decode ( pBuf ) )!=0 ) if ( iCode>0 ) ++iRes; return iRes; } /// quick check for UTF-8 inline bool sphIsUTF8 ( const char * pStr ) { while ( *pStr ) { if ( *pStr < 0 ) return true; pStr++; } return false; } /// convert UTF-8 to codepoints, return string length inline int sphUTF8ToWideChar ( const char * pSrc, int * pDst, int iMaxLen ) { const BYTE * p = (const BYTE*) pSrc; int iLen = 0, iCode; while ( ( iCode = sphUTF8Decode(p) )!=0 && iLen<iMaxLen ) { *pDst++ = iCode; iLen++; } *pDst = 0; return iLen; } #define sphStrMatchStatic(_str, _cstr) ( strncmp ( _str, _cstr, sizeof(_str)-1 )==0 ) ////////////////////////////////////////////////////////////////////////// // MATCHING ENGINE INTERNALS ////////////////////////////////////////////////////////////////////////// static const int FIELD_BITS = 8; typedef Hitman_c<FIELD_BITS> HITMAN; /// hit in the stream /// combines posting info (docid and hitpos) with a few more matching/ranking bits /// /// note that while in simple cases every hit would just represent a single keyword, /// this is NOT always the case; phrase, proximity, and NEAR operators (that already /// analyze keywords positions while matching the document) can emit a single folded /// hit representing the entire multi-keyword match, so that the ranker could avoid /// double work processing individual hits again. in such cases, m_uWeight, m_uSpanlen, /// and m_uMatchlen will differ from the "usual" value of 1. /// /// thus, in folded hits: /// - m_uWeight is the match LCS value in all cases (phrase, proximity, near). /// - m_uSpanlen is the match span length, ie. a distance from the first to the last /// matching keyword. for phrase operators it natually equals m_uWeight, for other /// operators it might be very different. /// - m_uMatchlen is a piece of voodoo magic that only the near operator seems to use. struct ExtHit_t { RowID_t m_tRowID; Hitpos_t m_uHitpos; WORD m_uQuerypos; WORD m_uNodepos; WORD m_uSpanlen; WORD m_uMatchlen; DWORD m_uWeight; ///< 1 for individual keywords, LCS value for folded phrase/proximity/near hits DWORD m_uQposMask; }; /// match in the stream struct ExtDoc_t { RowID_t m_tRowID; DWORD m_uDocFields; float m_fTFIDF; }; struct ZoneHits_t { CSphVector<Hitpos_t> m_dStarts; CSphVector<Hitpos_t> m_dEnds; }; enum SphZoneHit_e { SPH_ZONE_FOUND, SPH_ZONE_NO_SPAN, SPH_ZONE_NO_DOCUMENT }; class ISphZoneCheck { public: virtual ~ISphZoneCheck () {} virtual SphZoneHit_e IsInZone ( int iZone, const ExtHit_t * pHit, int * pLastSpan ) = 0; }; struct SphFactorHashEntry_t { RowTagged_t m_tRow; int m_iRefCount; BYTE * m_pData; SphFactorHashEntry_t * m_pPrev; SphFactorHashEntry_t * m_pNext; }; typedef CSphFixedVector<SphFactorHashEntry_t *> SphFactorHash_t; DWORD FactorPoolHash ( const RowTagged_t & tRow, int iLen ); struct SphExtraDataRankerState_t { const CSphSchema * m_pSchema = nullptr; const int64_t * m_pFieldLens = nullptr; CSphAttrLocator m_tFieldLensLoc; int64_t m_iTotalDocuments = 0; int m_iFields = 0; int m_iMaxQpos = 0; }; struct MatchSortAccessor_t { using T = CSphMatch; using MEDIAN_TYPE = T *; private: mutable CSphMatch m_tMedian; public: MatchSortAccessor_t () = default; MatchSortAccessor_t ( const MatchSortAccessor_t & ) {} virtual ~MatchSortAccessor_t() { m_tMedian.m_pDynamic = nullptr; // not yours } MEDIAN_TYPE Key ( CSphMatch * a ) const { return a; } void CopyKey ( MEDIAN_TYPE * pMed, CSphMatch * pVal ) const { *pMed = &m_tMedian; m_tMedian.m_tRowID = pVal->m_tRowID; m_tMedian.m_iWeight = pVal->m_iWeight; m_tMedian.m_pStatic = pVal->m_pStatic; m_tMedian.m_pDynamic = pVal->m_pDynamic; m_tMedian.m_iTag = pVal->m_iTag; } void Swap ( T * a, T * b ) const { ::Swap ( *a, *b ); } T * Add ( T * p, int i ) const { return p+i; } int Sub ( T * b, T * a ) const { return (int)(b-a); } }; ////////////////////////////////////////////////////////////////////////// // INLINES, MISC ////////////////////////////////////////////////////////////////////////// inline const char * sphTypeName ( ESphAttr eType ) { switch ( eType ) { case SPH_ATTR_NONE: return "none"; case SPH_ATTR_INTEGER: return "uint"; case SPH_ATTR_TIMESTAMP: return "timestamp"; case SPH_ATTR_BOOL: return "bool"; case SPH_ATTR_FLOAT: return "float"; case SPH_ATTR_BIGINT: return "bigint"; case SPH_ATTR_STRING: case SPH_ATTR_STRINGPTR: return "string"; // not 'stringptr' since it used to be human-readable case SPH_ATTR_TOKENCOUNT: return "tokencount"; case SPH_ATTR_JSON: return "json"; case SPH_ATTR_UINT32SET: return "mva"; case SPH_ATTR_INT64SET: return "mva64"; case SPH_ATTR_FLOAT_VECTOR: return "float_vector"; default: return "unknown"; } } inline const char * sphTypeDirective ( ESphAttr eType ) { switch ( eType ) { case SPH_ATTR_NONE: return "???"; case SPH_ATTR_INTEGER: return "sql_attr_uint"; case SPH_ATTR_TIMESTAMP: return "sql_attr_timestamp"; case SPH_ATTR_BOOL: return "sql_attr_bool"; case SPH_ATTR_FLOAT: return "sql_attr_float"; case SPH_ATTR_BIGINT: return "sql_attr_bigint"; case SPH_ATTR_STRING: return "sql_attr_string"; case SPH_ATTR_STRINGPTR: return "sql_attr_string"; case SPH_ATTR_TOKENCOUNT: return "_autogenerated_tokencount"; case SPH_ATTR_JSON: return "sql_attr_json"; case SPH_ATTR_UINT32SET: return "sql_attr_multi"; case SPH_ATTR_INT64SET: return "sql_attr_multi bigint"; default: return "???"; } } inline const char * sphRtTypeDirective ( ESphAttr eType ) { switch ( eType ) { case SPH_ATTR_INTEGER: return "rt_attr_uint"; case SPH_ATTR_TIMESTAMP: return "rt_attr_timestamp"; case SPH_ATTR_BOOL: return "rt_attr_bool"; case SPH_ATTR_FLOAT: return "rt_attr_float"; case SPH_ATTR_BIGINT: return "rt_attr_bigint"; case SPH_ATTR_STRING: case SPH_ATTR_STRINGPTR: return "rt_attr_string"; case SPH_ATTR_JSON: return "rt_attr_json"; case SPH_ATTR_UINT32SET: return "rt_attr_multi"; case SPH_ATTR_INT64SET: return "rt_attr_multi64"; case SPH_ATTR_FLOAT_VECTOR: return "rt_attr_float_vector"; default: return nullptr; } } inline std::pair<CSphString,int> SqlUnescapeN ( const char * sEscaped, int iLen ) { CSphString sRes; assert ( iLen>=2 ); assert ( ( sEscaped[0]=='\'' && sEscaped[iLen - 1]=='\'' ) || ( sEscaped[0]=='"' && sEscaped[iLen - 1]=='"' ) ); // skip heading and trailing quotes const char * s = sEscaped + 1; const char * sMax = s + iLen - 2; sRes.Reserve ( iLen-2 ); auto * d = const_cast<char *> (sRes.cstr ()); while ( s<sMax ) { if ( s[0]=='\\' ) { switch ( s[1] ) { case 'b': *d++ = '\b'; break; case 'n': *d++ = '\n'; break; case 'r': *d++ = '\r'; break; case 't': *d++ = '\t'; break; case '0': *d++ = ' '; break; default: *d++ = s[1]; } s += 2; } else *d++ = *s++; } *d = '\0'; return { sRes, d - sRes.cstr() }; } inline CSphString SqlUnescape ( const char* sEscaped, int iLen ) { return SqlUnescapeN ( sEscaped, iLen ).first; } ////////////////////////////////////////////////////////////////////////// // DISK INDEX INTERNALS ////////////////////////////////////////////////////////////////////////// void RemoveDictSpecials ( CSphString & sWord, bool bBigram ); const CSphString & RemoveDictSpecials ( const CSphString & sWord, CSphString & sBuf, bool bBigram ); DWORD sphParseMorphAot ( const char * ); uint64_t sphGetSettingsFNV ( const CSphIndexSettings & tSettings ); uint64_t SchemaFNV ( const ISphSchema & tSchema ); ////////////////////////////////////////////////////////////////////////// // USER VARIABLES ////////////////////////////////////////////////////////////////////////// using fnGetUserVar = UservarIntSet_c ( * ) ( const CSphString & sUservar ); void SetUserVarsHook ( fnGetUserVar fnHook ); bool UservarsAvailable(); UservarIntSet_c Uservars ( const CSphString & sUservar ); ////////////////////////////////////////////////////////////////////////// // MISC FUNCTION PROTOTYPES ////////////////////////////////////////////////////////////////////////// const BYTE * SkipQuoted ( const BYTE * p ); /// make string lowercase but keep case of JSON.field void sphColumnToLowercase ( char * sVal ); // stack for evaluating ft nodes void SetExtNodeStackSize ( int iDelta, int iExtra ); // returns 0: query can't be run at all (even hardlimit stack will be exceeded), sError is set. // returns -1: query might be run on current frame // other positive: necessary free size of stack int ConsiderStack ( const struct XQNode_t * pRoot, CSphString & sError ); int ConsiderStackAbsolute ( const struct XQNode_t* pRoot ); void sphTransformExtendedQuery ( XQNode_t ** ppNode, const CSphIndexSettings & tSettings, bool bHasBooleanOptimization, const ISphKeywordsStat * pKeywords ); void TransformAotFilter ( XQNode_t * pNode, const CSphWordforms * pWordforms, const CSphIndexSettings& tSettings ); int ExpandKeywords ( int iIndexOpt, QueryOption_e eQueryOpt, const CSphIndexSettings & tSettings, bool bWordDict ); bool ParseMorphFields ( const CSphString & sMorphology, const CSphString & sMorphFields, const CSphVector<CSphColumnInfo> & dFields, CSphBitvec & tMorphFields, CSphString & sError ); void sphSetUnlinkOld ( bool bUnlink ); bool sphGetUnlinkOld (); void sphUnlinkIndex ( const char * sName, bool bForce ); void WriteSchema ( CSphWriter & fdInfo, const CSphSchema & tSchema ); void ReadSchema ( CSphReader & rdInfo, CSphSchema & m_tSchema, DWORD uVersion ); void ReadSchemaJson ( bson::Bson_c tNode, CSphSchema & tSchema ); bool AddFieldLens ( CSphSchema & tSchema, bool bDynamic, CSphString & sError ); bool LoadHitlessWords ( const CSphString & sHitlessFiles, const TokenizerRefPtr_c& pTok, const DictRefPtr_c& pDict, CSphVector<SphWordID_t> & dHitlessWords, CSphString & sError ); void GetSettingsFiles ( const TokenizerRefPtr_c& pTok, const DictRefPtr_c& pDict, const CSphIndexSettings& tSettings, const FilenameBuilder_i* pFilenameBuilder, StrVec_t& dFiles ); struct BuildBufferSettings_t { int m_iSIMemLimit = 128*1024*1024; int m_iBufferAttributes = 8*1024*1024; int m_iBufferStorage = 8*1024*1024; int m_iBufferColumnar = 1*1024*1024; int m_iBufferFulltext = 8*1024*1024; int m_iBufferDict = 16*1024*1024; }; bool sphMerge ( const CSphIndex * pDst, const CSphIndex * pSrc, VecTraits_T<CSphFilterSettings> dFilters, CSphIndexProgress & tProgress, CSphString& sError ); /// json save/load void operator<< ( JsonEscapedBuilder& tOut, const CSphSchema& tSchema ); void RebalanceWeights ( const CSphFixedVector<int64_t> & dTimers, CSphFixedVector<float>& pWeights ); // FIXME!!! remove with converter const char * CheckFmtMagic ( DWORD uHeader ); bool WriteKillList ( const CSphString & sFilename, const DocID_t * pKlist, int nEntries, const KillListTargets_c & tTargets, CSphString & sError ); void WarnAboutKillList ( const CSphVector<DocID_t> & dKillList, const KillListTargets_c & tTargets ); template < typename VECTOR > int sphPutBytes ( VECTOR * pOut, const void * pData, int iLen ) { int iOff = pOut->GetLength(); pOut->Append ( pData, iLen ); return iOff; } template<typename CP> inline int sphCheckpointCmpCrc ( SphWordID_t iWordID, const CP& tCP ) { return ( iWordID < tCP.m_uWordID ) ? -1 : ( iWordID == tCP.m_uWordID ? 0 : 1 ); } template < typename CP, typename PRED > const CP * sphSearchCheckpointCrc ( SphWordID_t iWordID, VecTraits_T<CP> dCheckpoints, PRED && tPred ) { const CP * pStart = dCheckpoints.begin(); const CP * pEnd = &dCheckpoints.Last(); if ( sphCheckpointCmpCrc ( iWordID, tPred ( pStart ) )<0 ) return nullptr; if ( sphCheckpointCmpCrc ( iWordID, tPred ( pEnd ) )>=0 ) return pEnd; while ( pEnd-pStart>1 ) { const CP * pMid = pStart + (pEnd-pStart)/2; const int iCmpRes = sphCheckpointCmpCrc ( iWordID, tPred ( pMid ) ); if ( !iCmpRes ) return pMid; else if ( iCmpRes<0 ) pEnd = pMid; else pStart = pMid; } assert ( pStart >= dCheckpoints.begin() ); assert ( pStart <= &dCheckpoints.Last() ); assert ( sphCheckpointCmpCrc ( iWordID, tPred ( pStart ) )>=0 && sphCheckpointCmpCrc ( iWordID, tPred ( pEnd ) )<0 ); return pStart; } template < typename CP > const CP * sphSearchCheckpointCrc ( SphWordID_t iWordID, VecTraits_T<CP> dCheckpoints ) { return sphSearchCheckpointCrc ( iWordID, std::move(dCheckpoints), [] ( const CP* pCP ) { return *pCP; } ); } int sphDictCmp ( const char* pStr1, int iLen1, const char* pStr2, int iLen2 ); int sphDictCmpStrictly ( const char* pStr1, int iLen1, const char* pStr2, int iLen2 ); template <typename CP> int sphCheckpointCmp ( const char * sWord, int iLen, const CP & tCP ) { return sphDictCmp ( sWord, iLen, tCP.m_szWord, (int) strlen ( tCP.m_szWord ) ); } template <typename CP> int sphCheckpointCmpStrictly ( const char * sWord, int iLen, const CP & tCP ) { return sphDictCmpStrictly ( sWord, iLen, tCP.m_szWord, (int)strlen ( tCP.m_szWord ) ); } template<typename CP> int sphCheckpointCmpStrictly ( const char* sWord, int iLen, SphWordID_t iWordID, bool bWordDict, const CP& tCP ) { return bWordDict ? sphCheckpointCmpStrictly ( sWord, iLen, tCP ) : sphCheckpointCmpCrc ( iWordID, tCP ); } template < typename CP, typename PRED > const CP * sphSearchCheckpointWrd ( const char * sWord, int iWordLen, bool bStarMode, VecTraits_T<CP> dCheckpoints, PRED && tPred ) { assert ( iWordLen>0 ); const CP * pStart = dCheckpoints.begin(); const CP * pEnd = &dCheckpoints.Last(); if ( bStarMode && sphCheckpointCmp ( sWord, iWordLen, tPred ( pStart ) )<0 ) return nullptr; if ( !bStarMode && sphCheckpointCmpStrictly ( sWord, iWordLen, tPred ( pStart ) )<0 ) return nullptr; if ( sphCheckpointCmpStrictly ( sWord, iWordLen, tPred ( pEnd ) )>=0 ) return pEnd; while ( pEnd-pStart>1 ) { const CP * pMid = pStart + (pEnd-pStart)/2; const int iCmpRes = sphCheckpointCmpStrictly ( sWord, iWordLen, tPred ( pMid ) ); if ( !iCmpRes ) return pMid; else if ( iCmpRes<0 ) pEnd = pMid; else pStart = pMid; } assert ( pStart >= dCheckpoints.begin() ); assert ( pStart <= &dCheckpoints.Last() ); assert ( sphCheckpointCmp ( sWord, iWordLen, tPred ( pStart ) )>=0 && sphCheckpointCmpStrictly ( sWord, iWordLen, tPred ( pEnd ) )<0 ); return pStart; } template < typename CP > const CP * sphSearchCheckpointWrd ( const char * sWord, int iWordLen, bool bStarMode, VecTraits_T<CP> dCheckpoints ) { return sphSearchCheckpointWrd ( sWord, iWordLen, bStarMode, std::move(dCheckpoints), [] ( const CP* pCP ) { return *pCP; } ); } class ISphRtDictWraper : public CSphDict { protected: ~ISphRtDictWraper() override = default; public: virtual const BYTE * GetPackedKeywords () = 0; virtual int GetPackedLen () = 0; virtual void ResetKeywords() = 0; virtual const char * GetLastWarning() const = 0; virtual void ResetWarning() = 0; }; using ISphRtDictWraperRefPtr_c = CSphRefcountedPtr<ISphRtDictWraper>; ISphRtDictWraperRefPtr_c sphCreateRtKeywordsDictionaryWrapper ( DictRefPtr_c pBase, bool bStoreID ); struct SphExpanded_t { int m_iNameOff; int m_iDocs; int m_iHits; }; struct ISphSubstringPayload { virtual ~ISphSubstringPayload() {} int m_iTotalDocs = 0; int m_iTotalHits = 0; }; // levenstein distance for words int sphLevenshtein ( const char * sWord1, int iLen1, const char * sWord2, int iLen2, CSphVector<int> & dTmp ); // levenstein distance for unicode codepoints int sphLevenshtein ( const int * sWord1, int iLen1, const int * sWord2, int iLen2, CSphVector<int> & dTmp ); struct Slice_t { DWORD m_uOff = 0; DWORD m_uLen; }; struct SuggestWord_t { int m_iNameOff; int m_iLen; int m_iDistance; int m_iDocs; DWORD m_iNameHash; }; struct SuggestArgs_t { int m_iLimit { 5 }; // limit into result set int m_iMaxEdits { 4 }; // levenstein distance threshold int m_iDeltaLen { 3 }; // filter out words from dictionary these shorter \ longer then reference word int m_iQueueLen { 25 }; int m_iRejectThr { 4 }; bool m_bQueryMode { false }; bool m_bResultOneline { false }; bool m_bResultStats { true }; bool m_bNonCharAllowed { false }; bool m_bSentence { false }; }; struct SuggestResultSet_t { CSphVector<BYTE> m_dBuf; CSphVector<SuggestWord_t> m_dMatched; }; struct SuggestResult_t : public SuggestResultSet_t { // state CSphVector<char> m_dTrigrams; int m_iNGramLen = 3; // payload void * m_pWordReader = nullptr; cRefCountedRefPtrGeneric_t m_pSegments; bool m_bMergeWords = false; // word CSphString m_sWord; int m_iLen = 0; int m_dCodepoints[SPH_MAX_WORD_LEN]; int m_iCodepoints = 0; bool m_bUtf8 = false; bool m_bHasExactDict = false; CSphString m_sSentence; SuggestResult_t () { m_dBuf.Reserve ( 8096 ); m_dMatched.Reserve ( 512 ); } ~SuggestResult_t () { assert ( !m_pWordReader ); assert ( !m_pSegments ); } bool SetWord ( const char * sWord, const TokenizerRefPtr_c& pTok, bool bUseLastWord, bool bSetSentence ); void Flattern ( int iLimit ); }; class ISphWordlistSuggest { public: virtual ~ISphWordlistSuggest () {} virtual void SuffixGetChekpoints ( const SuggestResult_t & tRes, const char * sSuffix, int iLen, CSphVector<DWORD> & dCheckpoints ) const = 0; virtual void SetCheckpoint ( SuggestResult_t & tRes, DWORD iCP ) const = 0; struct DictWord_t { const char * m_sWord; int m_iLen; int m_iDocs; }; virtual bool ReadNextWord ( SuggestResult_t & tRes, DictWord_t & tWord ) const = 0; }; void sphGetSuggest ( const ISphWordlistSuggest * pWordlist, int iInfixCodepointBytes, const SuggestArgs_t & tArgs, SuggestResult_t & tRes ); void SuggestMergeDocs ( CSphVector<SuggestWord_t> & dMatched ); struct ExpansionTrait_t { int m_iExpansionLimit = 0; bool m_bHasExactForms = false; ESphHitless m_eHitless = SPH_HITLESS_NONE; cRefCountedRefPtrGeneric_t m_pIndexData; }; using RegexTerm_t = std::pair <CSphString, XQNode_t *>; class DictTerm2Expanded_i; struct ExpansionContext_t; class ISphWordlist { public: struct Args_t : public ExpansionTrait_t, ISphNoncopyable { CSphVector<SphExpanded_t> m_dExpanded; const bool m_bPayload; std::unique_ptr<ISphSubstringPayload> m_pPayload { nullptr }; int m_iTotalDocs; int m_iTotalHits; ExpansionStats_t & m_tExpansionStats; Args_t ( bool bPayload, ExpansionContext_t & tCtx ); void AddExpanded ( const BYTE * sWord, int iLen, int iDocs, int iHits ); const char * GetWordExpanded ( int iIndex ) const; private: CSphVector<char> m_sBuf; }; virtual ~ISphWordlist () {} virtual void GetPrefixedWords ( const char * sSubstring, int iSubLen, const char * sWildcard, Args_t & tArgs ) const = 0; virtual void GetInfixedWords ( const char * sSubstring, int iSubLen, const char * sWildcard, Args_t & tArgs ) const = 0; virtual void ScanRegexWords ( const VecTraits_T<RegexTerm_t> & dTerms, const ISphWordlist::Args_t & tArgs, const VecTraits_T< std::unique_ptr<DictTerm2Expanded_i> > & dConverters ) const = 0; }; class DictTerm2Expanded_i { public: DictTerm2Expanded_i() = default; virtual ~DictTerm2Expanded_i() = default; virtual void Convert ( ISphWordlist::Args_t & tArgs ) = 0; }; using VecExpandConv_t = VecTraits_T< std::unique_ptr<DictTerm2Expanded_i> >; class CSphScopedPayload { public: CSphScopedPayload () {} ~CSphScopedPayload () { for ( auto & dPayload : m_dPayloads ) SafeDelete ( dPayload ); } void Add ( ISphSubstringPayload * pPayload ) { m_dPayloads.Add ( pPayload ); } private: CSphVector<ISphSubstringPayload *> m_dPayloads; }; struct ExpansionContext_t : public ExpansionTrait_t { const ISphWordlist * m_pWordlist = nullptr; BYTE * m_pBuf = nullptr; CSphQueryResultMeta * m_pResult = nullptr; int m_iMinPrefixLen = 0; int m_iMinInfixLen = 0; bool m_bMergeSingles = false; CSphScopedPayload * m_pPayloads = nullptr; int m_iCutoff = -1; bool m_bAllowExpansion = true; ExpansionStats_t m_tExpansionStats; bool m_bOnlyTreeFix = false; CSphVector<RegexTerm_t> m_dRegexTerms; bool m_bHasWildcards = false; void AggregateStats (); }; struct GetKeywordsSettings_t { bool m_bStats = true; bool m_bFoldLemmas = false; bool m_bFoldBlended = false; bool m_bFoldWildcards = false; int m_iExpansionLimit = 0; bool m_bSortByDocs = false; bool m_bSortByHits = false; int m_iCutoff = -1; bool m_bAllowExpansion = true; JiebaMode_e m_eJiebaMode = JiebaMode_e::DEFAULT; }; XQNode_t * sphExpandXQNode ( XQNode_t * pNode, ExpansionContext_t & tCtx ); void sphQueryExpandKeywords ( XQNode_t ** ppNode, const CSphIndexSettings & tSettings, int iExpandKeywords, bool bWordDict ); inline int sphGetExpansionMagic ( int iDocs, int iHits ) { return ( iHits<=256 ? 1 : iDocs + 1 ); // magic threshold; mb make this configurable? } bool sphIsExpandedPayload ( int iDocs, int iHits ); bool sphHasExpandableWildcards ( const char * sWord ); bool sphExpandGetWords ( const char * sWord, const ExpansionContext_t & tCtx, ISphWordlist::Args_t & tWordlist ); bool ExpandRegex ( ExpansionContext_t & tCtx, CSphString & sError ); void ExpandedMergeThdDocs ( int iDocs ); void ExpandedMergeThdHits ( int iHits ); template<typename T> struct ExpandedOrderDesc_T { bool IsLess ( const T & a, const T & b ) const { return ( sphGetExpansionMagic ( a.m_iDocs, a.m_iHits )>sphGetExpansionMagic ( b.m_iDocs, b.m_iHits ) ); } }; class CSphKeywordDeltaWriter { private: BYTE m_sLastKeyword [SPH_MAX_WORD_LEN*3+4]; int m_iLastLen; public: CSphKeywordDeltaWriter () { Reset(); } void Reset () { m_iLastLen = 0; } template <typename F> void PutDelta ( F & WRITER, const BYTE * pWord, int iLen ) { assert ( pWord && iLen ); // how many bytes of a previous keyword can we reuse? BYTE iMatch = 0; int iMinLen = Min ( m_iLastLen, iLen ); assert ( iMinLen<(int)sizeof(m_sLastKeyword) ); while ( iMatch<iMinLen && m_sLastKeyword[iMatch]==pWord[iMatch] ) ++iMatch; BYTE iDelta = (BYTE)( iLen - iMatch ); assert ( iDelta>0 ); assert ( iLen < (int)sizeof(m_sLastKeyword) ); memcpy ( m_sLastKeyword, pWord, iLen ); m_iLastLen = iLen; // match and delta are usually tiny, pack them together in 1 byte // tricky bit, this byte leads the entry so it must never be 0 (aka eof mark)! if ( iDelta<=8 && iMatch<=15 ) { BYTE uPacked = BYTE ( 0x80 + ( (iDelta-1)<<4 ) + iMatch ); WRITER.PutBytes ( &uPacked, 1 ); } else { WRITER.PutBytes ( &iDelta, 1 ); // always greater than 0 WRITER.PutBytes ( &iMatch, 1 ); } WRITER.PutBytes ( pWord + iMatch, iDelta ); } }; BYTE sphDoclistHintPack ( SphOffset_t iDocs, SphOffset_t iLen ); // wordlist checkpoints frequency #define SPH_WORDLIST_CHECKPOINT 64 #if _WIN32 void localtime_r ( const time_t * clock, struct tm * res ); void gmtime_r ( const time_t * clock, struct tm * res ); #endif /// compute utf-8 character length in bytes from its first byte inline int sphUtf8CharBytes ( BYTE uFirst ) { // 110x xxxx, 2 bytes // 1110 xxxx, 3 bytes // 1111 0xxx, 4 bytes // others - either 1 byte, or invalid/unsupported code static const std::array<BYTE, 16> dValues { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 4 }; return dValues[uFirst >> 4]; } // calculate length, upto iInfixCodepointBytes chars from infix start inline int sphGetInfixLength ( const char* sInfix, int iBytes, int iInfixCodepointBytes ) { if ( iInfixCodepointBytes == 1 ) return Min ( 6, iBytes ); int iCharsLeft = 6; const char* s = sInfix; const char* sMax = sInfix + iBytes; while ( iCharsLeft-- && s < sMax ) s += sphUtf8CharBytes ( *s ); return (int)( s - sInfix ); } ////////////////////////////////////////////////////////////////////////// /// parser to build lowercaser from textual config struct RemapXSV_t { int m_iAttr {-1}; int m_iField {-1}; int m_iTag {-1}; }; // internals attributes are last no need to send them void sphGetAttrsToSend ( const ISphSchema & tSchema, bool bAgentMode, bool bNeedId, CSphBitvec & tAttrs ); inline void FlipEndianness ( DWORD* pData ) { BYTE* pB = (BYTE*)pData; BYTE a = pB[0]; pB[0] = pB[3]; pB[3] = a; a = pB[1]; pB[1] = pB[2]; pB[2] = a; }; struct SchemaItemVariant_t { int m_iField = -1; int m_iStr = -1; int m_iMva = -1; ESphAttr m_eType = SPH_ATTR_NONE; CSphAttrLocator m_tLoc; }; using SchemaItemHash_c = OpenHashTable_T<uint64_t, SchemaItemVariant_t>; template <typename T> BYTE PrereadMapping ( const char * sIndexName, const char * sFor, bool bMlock, bool bOnDisk, CSphBufferTrait<T> & tBuf ) { static volatile BYTE g_uHash; if ( bOnDisk || tBuf.IsEmpty() ) return g_uHash; auto pCur = (const BYTE*)tBuf.GetReadPtr(); const BYTE * pEnd = pCur + tBuf.GetLengthBytes(); const int iHalfPage = GetMemPageSize()/2; g_uHash = 0xff; for ( ; pCur<pEnd; pCur+=iHalfPage ) g_uHash ^= *pCur; g_uHash ^= *(pEnd-1); // we want to prevent PrereadMapping() from being aggressively optimized away // volatile return values *should* normally achieve that CSphString sWarning; if ( bMlock && !tBuf.MemLock ( sWarning ) ) sphWarning ( "table '%s': %s for %s", sIndexName, sWarning.cstr(), sFor ); return g_uHash; } // generally it should not work significantly slower than just PrereadMapping, since once page raised to mem // we iterate it much faster then raising itself, so the bottleneck should be in disk IO, not in mem iterations inline DWORD PrereadMappingCountingBits ( const char * sIndexName, const char * sFor, bool bMlock, bool bOnDisk, CSphBufferTrait<DWORD> & tBuf ) { DWORD uBits = 0; tBuf.Apply ( [&uBits] ( DWORD uData ) { uBits += sphBitCount ( uData ); } ); CSphString sWarning; if ( bMlock && !tBuf.MemLock ( sWarning ) ) sphWarning ( "table '%s': %s for %s", sIndexName, sWarning.cstr(), sFor ); return uBits; } // crash related code struct CrashQuery_t { ByteBlob_t m_dQuery { nullptr, 0 }; Str_t m_dIndex { nullptr, 0 }; WORD m_uCMD = 0; // last command (header) WORD m_uVer = 0; // last command's version (header) QueryType_e m_eType = QUERY_API; }; // get ref to crash info saved thread-locally (beware: it will became invalid after switching context!) // use manual get/set, or CrashQueryKeeper_c around context switching (like: throttle, coro event) to survive. CrashQuery_t & GlobalCrashQueryGetRef (); // RAII keeps copy of TLS crash query (just define this guard to pass context switch) class CrashQueryKeeper_c : public ISphNoncopyable, public ISphNonmovable { const CrashQuery_t m_tReference; public: // will store currently active crash query from current TLS CrashQueryKeeper_c (); // will restore saved crash query to current TLS ~CrashQueryKeeper_c (); // will restore saved crash query to current TLS void RestoreCrashQuery () const; }; int sphFormatCurrentTime ( char* sTimeBuf, int iBufLen ); void sphFormatCurrentTime ( StringBuilder_c& sOut ); CSphString sphCurrentUtcTime ( ); #endif // _sphinxint_
39,427
C++
.h
1,162
31.89759
192
0.667675
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,201
accumulator.h
manticoresoftware_manticoresearch/src/accumulator.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // /// @file _accumulator.h_ /// Declarations for the stuff related to accumulator #ifndef _accumulator_ #define _accumulator_ #include "sphinxint.h" #include "docstore.h" struct StoredQueryDesc_t { CSphFixedVector<CSphFilterSettings> m_dFilters { 0 }; CSphFixedVector<FilterTreeItem_t> m_dFilterTree { 0 }; CSphString m_sQuery; CSphString m_sTags; int64_t m_iQUID = 0; bool m_bQL = true; }; class StoredQuery_i : public ISphNoncopyable, public StoredQueryDesc_t { public: virtual ~StoredQuery_i() {} }; // commands that got replicated, transactions enum class ReplCmd_e { PQUERY_ADD = 0, PQUERY_DELETE, TRUNCATE, CLUSTER_ALTER_ADD, CLUSTER_ALTER_DROP, RT_TRX, UPDATE_API, UPDATE_QL, UPDATE_JSON, TOTAL }; struct CSphReconfigureSettings; class InsertDocData_c; struct RtSegment_t; class MemoryWriter_c; // command trait struct ReplicationCommand_t { // common ReplCmd_e m_eCommand { ReplCmd_e::TOTAL }; WORD m_uVersion = 0; CSphString m_sIndex; // move to accumulator CSphString m_sCluster; // add std::unique_ptr<StoredQuery_i> m_pStored; // delete CSphVector<int64_t> m_dDeleteQueries; CSphString m_sDeleteTags; // truncate std::unique_ptr<CSphReconfigureSettings> m_tReconfigure; // commit related bool m_bCheckIndex = true; bool m_bIsolated = false; // update AttrUpdateSharedPtr_t m_pUpdateAPI; bool m_bBlobUpdate = false; const CSphQuery * m_pUpdateCond = nullptr; }; std::unique_ptr<ReplicationCommand_t> MakeReplicationCommand ( ReplCmd_e eCommand, CSphString sIndex, CSphString sCluster = CSphString() ); class RtIndex_i; class ColumnarBuilderRT_i; /// indexing accumulator class RtAccum_t { public: DWORD m_uAccumDocs = 0; int64_t m_iAccumBytes = 0; CSphTightVector<CSphWordHit> m_dAccum; CSphTightVector<CSphRowitem> m_dAccumRows; CSphVector<DocID_t> m_dAccumKlist; CSphTightVector<BYTE> m_dBlobs; CSphVector<DWORD> m_dPerDocHitsCount; CSphVector<std::unique_ptr<ReplicationCommand_t>> m_dCmd; bool m_bKeywordDict = false; DictRefPtr_c m_pDict; const void * m_pRefDict = nullptr; // not owned, used only for comparing via == public: void SetupDict ( const RtIndex_i * pIndex, const DictRefPtr_c& pDict, bool bKeywordDict ); void Sort(); void CleanupPart(); void Cleanup(); void AddDocument ( ISphHits * pHits, const InsertDocData_c & tDoc, bool bReplace, int iRowSize, const DocstoreBuilder_i::Doc_t * pStoredDoc ); void CleanupDuplicates ( int iRowSize ); void GrabLastWarning ( CSphString & sWarning ); void SetIndex ( RtIndex_i * pIndex ); RowID_t GenerateRowID(); void ResetRowID(); uint64_t GetSchemaHash() const { return m_uSchemaHash; } RtIndex_i * GetIndex() const { return m_pIndex; } int GetIndexGeneration() const { return m_iIndexGeneration; } const CSphString & GetIndexName() const { return m_sIndexName; } int64_t GetIndexId() const { return m_iIndexId; } ReplicationCommand_t * AddCommand ( ReplCmd_e eCmd, CSphString sIndex, CSphString sCluster = CSphString() ); void LoadRtTrx ( ByteBlob_t tTrx, DWORD uVer ); void SaveRtTrx ( MemoryWriter_c & tWriter ) const; const BYTE * GetPackedKeywords() const; int GetPackedLen() const; bool SetupDocstore ( const RtIndex_i & tIndex, CSphString & sError ); bool IsReplace () const { return m_bReplace; } [[nodiscard]] bool IsClusterCommand () const noexcept; [[nodiscard]] bool IsUpdateCommand ( ) const noexcept; private: bool m_bReplace = false; ///< insert or replace mode (affects CleanupDuplicates() behavior) ISphRtDictWraperRefPtr_c m_pDictRt; std::unique_ptr<BlobRowBuilder_i> m_pBlobWriter; std::unique_ptr<DocstoreRT_i> m_pDocstore; std::unique_ptr<ColumnarBuilderRT_i> m_pColumnarBuilder; RowID_t m_tNextRowID = 0; CSphFixedVector<BYTE> m_dPackedKeywords { 0 }; uint64_t m_uSchemaHash = 0; // FIXME!!! index is unlocked between add data and commit or at begin and end RtIndex_i * m_pIndex = nullptr; ///< my current owner in this thread int m_iIndexGeneration = 0; CSphString m_sIndexName; int64_t m_iIndexId = 0; void ResetDict(); void SetupDocstore(); // defined in sphinxrt.cpp friend RtSegment_t* CreateSegment ( RtAccum_t*, int, ESphHitless, const VecTraits_T<SphWordID_t>&, CSphString& ); }; #endif // _accumulator_
4,775
C++
.h
132
34.234848
145
0.735837
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,202
config_reloader.h
manticoresoftware_manticoresearch/src/config_reloader.h
// Copyright (c) 2022-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org // #pragma once #include "searchdaemon.h" class ConfigReloader_c final : public ISphNonCopyMovable { class Impl_c; std::unique_ptr<Impl_c> m_pImpl; public: explicit ConfigReloader_c ( HashOfServed_c& hDeferred ); ~ConfigReloader_c(); void LoadIndexFromConfig ( const CSphString& sIndex, IndexType_e eType, const CSphConfigSection& hIndex ) noexcept; void IssuePlainOldRotation() noexcept; };
871
C++
.h
22
38.136364
116
0.773964
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,203
binlog.h
manticoresoftware_manticoresearch/src/binlog.h
// // Copyright (c) 2021-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #pragma once #include "binlog_defs.h" #include "sphinxint.h" namespace Binlog { using ProgressCallbackSimple_t = void(); enum Txn_e : BYTE { UPDATE_ATTRS, COMMIT, PQ_ADD_DELETE, }; enum ReplayFlags_e { REPLAY_ACCEPT_DESC_TIMESTAMP = 1, REPLAY_IGNORE_OPEN_ERROR = 2, REPLAY_IGNORE_TRX_ERROR = 4, REPLAY_IGNORE_ALL_ERRORS = 0xFF }; using FnWriteCommit = std::function<void (Writer_i&)>; template < typename T > static void SaveVector ( Writer_i & tWriter, const VecTraits_T<T> &tVector ) { STATIC_ASSERT ( IS_TRIVIALLY_COPYABLE (T), NON_TRIVIAL_VECTORS_ARE_UNSERIALIZABLE ); tWriter.ZipOffset ( tVector.GetLength() ); if ( tVector.GetLength() ) tWriter.PutBytes ( tVector.Begin(), tVector.GetLengthBytes() ); } template < typename T, typename P > static bool LoadVector ( CSphReader & tReader, CSphVector <T,P> & tVector ) { STATIC_ASSERT ( IS_TRIVIALLY_COPYABLE(T), NON_TRIVIAL_VECTORS_ARE_UNSERIALIZABLE ); tVector.Resize ( (int) tReader.UnzipOffset() ); // FIXME? sanitize? if ( tVector.GetLength() ) tReader.GetBytes ( tVector.Begin(), (int) tVector.GetLengthBytes() ); return !tReader.GetErrorFlag(); } void Init ( CSphString sBinlogPath ); void Configure ( const CSphConfigSection & hSearchd, DWORD uReplayFlags ); void SetCommon ( bool bCommonBinlog ); void Deinit (); bool IsActive(); bool MockDisabled ( bool bNewVal ); bool IsFlushEnabled(); void Flush(); int64_t NextFlushTimestamp(); bool Commit ( int64_t * pTID, const char* szIndexName, CSphString & sError, FnWriteCommit && fnSaver ); /// replay stored binlog void Replay ( const SmallStringHash_T<CSphIndex*> & hIndexes, ProgressCallbackSimple_t * pfnProgressCallback = nullptr ); enum Shutdown_e : bool { NoShutdown=false, Shutdown }; enum ForceSave_e : BYTE { NoSave=0, ForceSave, DropTable }; void NotifyIndexFlush ( int64_t iTID, const char* szIndexName, Shutdown_e eShutdown, ForceSave_e eForceSave ); CSphString GetPath(); int64_t LastTidFor ( const CSphString & sIndex ); }
2,505
C++
.h
65
36.246154
122
0.739579
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,204
indexcheck.h
manticoresoftware_manticoresearch/src/indexcheck.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #ifndef _indexcheck_ #define _indexcheck_ #include "sphinx.h" class DebugCheckReader_i { public: virtual ~DebugCheckReader_i () = default; virtual int64_t GetLengthBytes () = 0; virtual bool GetBytes ( void * pData, int iSize ) = 0; virtual bool SeekTo ( int64_t iOff, int iHint ) = 0; }; // simple error reporter for debug checks class DebugCheckError_i { public: virtual ~DebugCheckError_i() = default; virtual bool Fail ( const char* szFmt, ... ) = 0; virtual void Msg ( const char* szFmt, ... ) = 0; virtual void Progress ( const char* szFmt, ... ) = 0; virtual void Done() = 0; virtual int64_t GetNumFails() const = 0; virtual const DocID_t* GetExtractDocs () const {return nullptr;}; }; DebugCheckError_i* MakeDebugCheckError ( FILE* fp, DocID_t* pExtract ); // common code for debug checks in RT and disk indexes class DebugCheckHelper_c { protected: void DebugCheck_Attributes ( DebugCheckReader_i & tAttrs, DebugCheckReader_i & tBlobs, int64_t nRows, int64_t iMinMaxBytes, const CSphSchema & tSchema, DebugCheckError_i & tReporter ) const; void DebugCheck_DeadRowMap ( int64_t iSizeBytes, int64_t nRows, DebugCheckError_i & tReporter ) const; }; // disk index checker class DiskIndexChecker_c { class Impl_c; std::unique_ptr<Impl_c> m_pImpl; public: DiskIndexChecker_c ( CSphIndex& tIndex, DebugCheckError_i& tReporter ); ~DiskIndexChecker_c(); bool OpenFiles (); void Setup ( int64_t iNumRows, int64_t iDocinfoIndex, int64_t iMinMaxIndex, bool bCheckIdDups ); CSphVector<SphWordID_t> & GetHitlessWords(); void Check(); }; void DebugCheckSchema ( const ISphSchema & tSchema, DebugCheckError_i & tReporter ); bool DebugCheckSchema ( const ISphSchema & tSchema, CSphString & sError ); bool SchemaConfigureCheckAttribute ( const CSphSchema & tSchema, const CSphColumnInfo & tCol, CSphString & sError ); #endif // _indexcheck_
2,351
C++
.h
59
38.169492
191
0.751427
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,205
searchdreplication.h
manticoresoftware_manticoresearch/src/searchdreplication.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // /// @file _searchdreplication_.h /// Declarations for the stuff specifically needed for replication #ifndef _searchdreplication_ #define _searchdreplication_ #include "searchdsql.h" #include <optional> // return path to given cluster, or empty and error std::optional<CSphString> GetClusterPath ( const CSphString& sCluster ); // collect all available into an array CSphVector<ClusterDesc_t> ReplicationCollectClusters (); // set Galera option for cluster bool ReplicateSetOption ( const CSphString & sCluster, const CSphString & sName, const CSphString & sVal ); // single point there all commands passed these might be replicated, even if no cluster bool HandleCmdReplicate ( RtAccum_t & tAcc ); bool HandleCmdReplicateDelete ( RtAccum_t & tAcc, int & iDeletedCount ); bool HandleCmdReplicateUpdate ( RtAccum_t & tAcc, CSphString & sWarning, int & iUpdated ); // Commit replicated commands came from cluster bool HandleCmdReplicated ( RtAccum_t& m_tAcc ); // delete all clusters on daemon shutdown void ReplicationServiceShutdown(); // prepare saved clusters (but not yet touch wsrep or even update nodes from remotes; only offline actions) // bForce will cause 'safe_to_bootstrap: 1' added to grastate.data void PrepareClustersOnStartup ( const VecTraits_T<ListenerDesc_t> & dListeners, bool bForce ); // start clusters on daemon start void ReplicationServiceStart ( bool bBootStrap ); // cluster joins to existed nodes bool ClusterJoin ( const CSphString & sCluster, const StrVec_t & dNames, const CSphVector<SqlInsert_t> & dValues, bool bUpdateNodes ); // cluster creates master node bool ClusterCreate ( const CSphString & sCluster, const StrVec_t & dNames, const CSphVector<SqlInsert_t> & dValues ); // cluster deletes bool GloballyDeleteCluster ( const CSphString & sCluster, CSphString & sError ); // Return actual nodes list at cluster StrVec_t ClusterGetAllNodes ( const CSphString& sCluster ); // cluster ALTER statement bool ClusterAlter ( const CSphString & sCluster, const CSphString & sIndex, bool bAdd, CSphString & sError ); // cluster ALTER statement that updates nodes option from view nodes at all nodes at cluster bool ClusterAlterUpdate ( const CSphString & sCluster, const CSphString & sUpdate, CSphString & sError ); // dump all clusters statuses void ReplicateClustersStatus ( VectorLike & dStatus ); // validate that SphinxQL statement could be run for this cluster:index bool ValidateClusterStatement ( const CSphString & sIndexName, const ServedDesc_t & tDesc, const CSphString & sStmtCluster, bool bHTTP ); std::optional<CSphString> IsPartOfCluster ( const ServedDesc_t* pDesc ); // set cluster name into index(es) desc for fast rejects bool AssignClusterToIndex ( const CSphString & sIndex, const CSphString & sCluster ); bool AssignClusterToIndexes ( const VecTraits_T<CSphString> & dIndexes, const CSphString & sCluster ); bool SetIndexesClusterTOI ( const ReplicationCommand_t * pCmd ); CSphString WaitClusterReady ( const CSphString& sCluster, int64_t iTimeoutS ); std::pair<int,CSphString> WaitClusterCommit ( const CSphString& sCluster, int iTxn, int64_t iTimeoutS ); #endif // _searchdreplication_
3,540
C++
.h
58
59.603448
137
0.79057
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,206
sortcomp.h
manticoresoftware_manticoresearch/src/sortcomp.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #ifndef _sortcomp_ #define _sortcomp_ #include "sphinxstd.h" class ISphMatchComparator : public ISphRefcountedMT { using fnFuncLessType = bool ( const CSphMatch & a, const CSphMatch & b, const CSphMatchComparatorState & t ); public: FORCE_INLINE bool VirtualIsLess ( const CSphMatch & a, const CSphMatch & b, const CSphMatchComparatorState & tState ) const { assert ( m_fnLessFunc ); return m_fnLessFunc ( a, b, tState ); } protected: ISphMatchComparator ( fnFuncLessType * fnLessFunc ) : m_fnLessFunc { fnLessFunc } {} ~ISphMatchComparator () override = default; private: fnFuncLessType * m_fnLessFunc = nullptr; }; class MatchRelevanceLt_fn : public ISphMatchComparator { public: static bool IsLess ( const CSphMatch & a, const CSphMatch & b, const CSphMatchComparatorState & tState ) { if ( a.m_iWeight!=b.m_iWeight ) return a.m_iWeight < b.m_iWeight; return a.m_tRowID > b.m_tRowID; } MatchRelevanceLt_fn() : ISphMatchComparator (IsLess) {} }; class MatchTimeSegments_fn : public ISphMatchComparator { public: static FORCE_INLINE bool IsLess ( const CSphMatch & a, const CSphMatch & b, const CSphMatchComparatorState & t ) { SphAttr_t aa = a.GetAttr ( t.m_tLocator[0] ); SphAttr_t bb = b.GetAttr ( t.m_tLocator[0] ); int iA = GetSegment ( aa, t.m_iNow ); int iB = GetSegment ( bb, t.m_iNow ); if ( iA!=iB ) return iA > iB; if ( a.m_iWeight!=b.m_iWeight ) return a.m_iWeight < b.m_iWeight; if ( aa!=bb ) return aa<bb; return a.m_tRowID > b.m_tRowID; } MatchTimeSegments_fn() : ISphMatchComparator (IsLess) {} protected: static FORCE_INLINE int GetSegment ( SphAttr_t iStamp, SphAttr_t iNow ) { if ( iStamp>=iNow-3600 ) return 0; // last hour if ( iStamp>=iNow-24*3600 ) return 1; // last day if ( iStamp>=iNow-7*24*3600 ) return 2; // last week if ( iStamp>=iNow-30*24*3600 ) return 3; // last month if ( iStamp>=iNow-90*24*3600 ) return 4; // last 3 months return 5; // everything else } }; class MatchExpr_fn : public ISphMatchComparator { public: static FORCE_INLINE bool IsLess ( const CSphMatch & a, const CSphMatch & b, const CSphMatchComparatorState & t ) { float aa = a.GetAttrFloat ( t.m_tLocator[0] ); // FIXME! OPTIMIZE!!! simplified (dword-granular) getter could be used here float bb = b.GetAttrFloat ( t.m_tLocator[0] ); if ( aa!=bb ) return aa<bb; return a.m_tRowID > b.m_tRowID; } MatchExpr_fn() : ISphMatchComparator (IsLess) {} }; #define SPH_TEST_PAIR(_aa,_bb,_idx ) \ if ( (_aa)!=(_bb) ) \ return ( (t.m_uAttrDesc >> (_idx)) & 1 ) ^ ( (_aa) > (_bb) ); #define SPH_TEST_KEYPART(_idx) \ switch ( t.m_eKeypart[_idx] ) \ { \ case SPH_KEYPART_ROWID: SPH_TEST_PAIR ( a.m_tRowID, b.m_tRowID, _idx ); break; \ case SPH_KEYPART_WEIGHT: SPH_TEST_PAIR ( a.m_iWeight, b.m_iWeight, _idx ); break; \ case SPH_KEYPART_INT: \ { \ SphAttr_t aa = a.GetAttr ( t.m_tLocator[_idx] ); \ SphAttr_t bb = b.GetAttr ( t.m_tLocator[_idx] ); \ SPH_TEST_PAIR ( aa, bb, _idx ); \ break; \ } \ case SPH_KEYPART_FLOAT: \ { \ float aa = a.GetAttrFloat ( t.m_tLocator[_idx] ); \ float bb = b.GetAttrFloat ( t.m_tLocator[_idx] ); \ SPH_TEST_PAIR ( aa, bb, _idx ) \ break; \ } \ case SPH_KEYPART_DOUBLE: \ { \ double aa = a.GetAttrDouble ( t.m_tLocator[_idx] ); \ double bb = b.GetAttrDouble ( t.m_tLocator[_idx] ); \ SPH_TEST_PAIR ( aa, bb, _idx ) \ break; \ } \ case SPH_KEYPART_STRINGPTR: \ case SPH_KEYPART_STRING: \ { \ int iCmp = t.CmpStrings ( a, b, _idx ); \ if ( iCmp!=0 ) \ return ( ( t.m_uAttrDesc >> (_idx) ) & 1 ) ^ ( iCmp>0 ); \ break; \ } \ } class MatchGeneric1_fn : public ISphMatchComparator { public: static FORCE_INLINE bool IsLess ( const CSphMatch & a, const CSphMatch & b, const CSphMatchComparatorState & t ) { SPH_TEST_KEYPART(0); return a.m_tRowID>b.m_tRowID; } MatchGeneric1_fn() : ISphMatchComparator (IsLess) {} }; class MatchGeneric2_fn : public ISphMatchComparator { public: static FORCE_INLINE bool IsLess ( const CSphMatch & a, const CSphMatch & b, const CSphMatchComparatorState & t ) { SPH_TEST_KEYPART(0); SPH_TEST_KEYPART(1); return a.m_tRowID>b.m_tRowID; } MatchGeneric2_fn() : ISphMatchComparator (IsLess) {} }; class MatchGeneric3_fn : public ISphMatchComparator { public: static FORCE_INLINE bool IsLess ( const CSphMatch & a, const CSphMatch & b, const CSphMatchComparatorState & t ) { SPH_TEST_KEYPART(0); SPH_TEST_KEYPART(1); SPH_TEST_KEYPART(2); return a.m_tRowID>b.m_tRowID; } MatchGeneric3_fn() : ISphMatchComparator (IsLess) {} }; class MatchGeneric4_fn : public ISphMatchComparator { public: static FORCE_INLINE bool IsLess ( const CSphMatch & a, const CSphMatch & b, const CSphMatchComparatorState & t ) { SPH_TEST_KEYPART(0); SPH_TEST_KEYPART(1); SPH_TEST_KEYPART(2); SPH_TEST_KEYPART(3); return a.m_tRowID>b.m_tRowID; } MatchGeneric4_fn() : ISphMatchComparator (IsLess) {} }; class MatchGeneric5_fn : public ISphMatchComparator { public: static FORCE_INLINE bool IsLess ( const CSphMatch & a, const CSphMatch & b, const CSphMatchComparatorState & t ) { SPH_TEST_KEYPART(0); SPH_TEST_KEYPART(1); SPH_TEST_KEYPART(2); SPH_TEST_KEYPART(3); SPH_TEST_KEYPART(4); return a.m_tRowID>b.m_tRowID; } MatchGeneric5_fn() : ISphMatchComparator (IsLess) {} }; #endif // _sortcomp_
5,849
C++
.h
181
29.845304
124
0.693497
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,207
cjkpreprocessor.h
manticoresoftware_manticoresearch/src/cjkpreprocessor.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #pragma once #include "sphinx.h" #include "tokenizer/remap_range.h" class CJKPreprocessor_c { public: virtual ~CJKPreprocessor_c() = default; virtual bool Init ( CSphString & sError ) = 0; virtual CJKPreprocessor_c * Clone ( const FieldFilterOptions_t * pOptions ) = 0; bool Process ( const BYTE * pBuffer, int iLength, CSphVector<BYTE> & dOut, bool bQuery ); bool SetBlendChars ( const char * szBlendChars, CSphString & sError ); protected: virtual void ProcessBuffer ( const BYTE * pBuffer, int iLength ) = 0; virtual const BYTE * GetNextToken ( int & iTokenLen ) = 0; private: CSphVector<CSphRemapRange> m_dBlendChars; void AddTextChunk ( const BYTE * pStart, int iLen, CSphVector<BYTE> & dOut, bool bChinese, bool bQuery ); FORCE_INLINE bool NeedAddSpace ( const BYTE * pToken, const CSphVector<BYTE> & dOut, bool bQuery ) const { int iResLen = dOut.GetLength(); if ( !iResLen ) return false; if ( bQuery && ( IsSpecialQueryCode ( dOut[iResLen - 1] ) || IsSpecialQueryCode ( *pToken ) ) ) return false; if ( IsBlendChar( dOut[iResLen - 1] ) || IsBlendChar ( *pToken ) ) return false; return !sphIsSpace ( dOut[iResLen-1] ) && !sphIsSpace ( *pToken ); } FORCE_INLINE bool IsSpecialQueryCode ( int iCode ) const { return iCode=='!' || iCode=='^' || iCode=='$' || iCode=='*' || iCode=='='; } FORCE_INLINE bool IsBlendChar ( int iCode ) const { ARRAY_FOREACH ( i, m_dBlendChars ) if ( iCode>=m_dBlendChars[i].m_iStart && iCode<=m_dBlendChars[i].m_iEnd ) return true; return false; } }; class FieldFilterCJK_c : public ISphFieldFilter { public: FieldFilterCJK_c ( std::unique_ptr<CJKPreprocessor_c> pPreprocessor ); bool Init ( CSphString & sError ); int Apply ( const BYTE * sField, int iLength, CSphVector<BYTE> & dStorage, bool bQuery ) final; void GetSettings ( CSphFieldFilterSettings & tSettings ) const final; std::unique_ptr<ISphFieldFilter> Clone ( const FieldFilterOptions_t * pOptions ) const final; bool SetBlendChars ( const char * szBlendChars, CSphString & sError ); void Setup ( std::unique_ptr<ISphFieldFilter> pParent ); private: std::unique_ptr<CJKPreprocessor_c> m_pPreprocessor; std::unique_ptr<ISphFieldFilter> m_pParent; CSphString m_sBlendChars; }; std::unique_ptr<ISphFieldFilter> CreateFilterCJK ( std::unique_ptr<ISphFieldFilter> pParent, std::unique_ptr<CJKPreprocessor_c> pPreprocessor, const char * szBlendChars, CSphString & sError ); bool CheckTokenizerCJK ( CSphIndexSettings & tSettings, const CSphTokenizerSettings & tTokSettings, CSphString & sError );
3,075
C++
.h
68
42.985294
192
0.730409
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,208
sphinx_alter.h
manticoresoftware_manticoresearch/src/sphinx_alter.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #ifndef _sphinx_alter_ #define _sphinx_alter_ #include "sphinxexpr.h" #include "columnarlib.h" #include "indexsettings.h" class WriteWrapper_c { public: virtual ~WriteWrapper_c() = default; virtual void PutBytes ( const BYTE * pData, int iSize ) = 0; virtual SphOffset_t GetPos() const = 0; virtual bool IsError() const = 0; }; class CSphWriter; std::unique_ptr<WriteWrapper_c> CreateWriteWrapperDisk ( CSphWriter & tWriter ); std::unique_ptr<WriteWrapper_c> CreateWriteWrapperMem ( CSphTightVector<CSphRowitem> & dSPA ); std::unique_ptr<WriteWrapper_c> CreateWriteWrapperMem ( CSphTightVector<BYTE> & dSPB ); class CSphSchema; class Docstore_i; class DocstoreBuilder_i; struct AttrAddRemoveCtx_t { CSphString m_sName; ESphAttr m_eType; int m_iBits; DWORD m_uFlags; AttrEngine_e m_eEngine; knn::IndexSettings_t m_tKNN; }; // common add/remove attribute/field code for both RT and plain indexes class IndexAlterHelper_c { public: virtual ~IndexAlterHelper_c() = default; virtual bool Alter_IsMinMax ( const CSphRowitem * pDocinfo, int iStride ) const { return false; } protected: bool Alter_AddRemoveRowwiseAttr ( const CSphSchema & tOldSchema, const CSphSchema & tNewSchema, const CSphRowitem * pDocinfo, DWORD uNumRows, const BYTE * pBlobPool, WriteWrapper_c & tSPAWriter, WriteWrapper_c & tSPBWriter, bool bAddAttr, const CSphString & sAttrName ); bool Alter_AddRemoveFromSchema ( CSphSchema & tSchema, const AttrAddRemoveCtx_t & tCtx, bool bAdd, CSphString & sError ) const; bool Alter_AddRemoveColumnar ( bool bAdd, const ISphSchema & tOldSchema, const ISphSchema & tNewSchema, columnar::Columnar_i * pColumnar, columnar::Builder_i * pBuilder, DWORD uRows, const CSphString & sIndex, CSphString & sError ); bool Alter_AddRemoveFieldFromSchema ( bool bAdd, CSphSchema & tSchema, const CSphString & sFieldName, DWORD uFieldFlags, CSphString & sError ); void Alter_AddRemoveFromDocstore ( DocstoreBuilder_i & tBuilder, const Docstore_i * pDocstore, DWORD uNumDocs, const CSphSchema & tNewSchema ); }; #endif // _sphinx_alter_
2,556
C++
.h
54
45.777778
273
0.770189
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,209
sortertraits.h
manticoresoftware_manticoresearch/src/sortertraits.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #pragma once #include "sphinxsort.h" #include "aggregate.h" #include "sphinxfilter.h" class MatchSorter_c : public ISphMatchSorter { public: void SetState ( const CSphMatchComparatorState & tState ) override; const CSphMatchComparatorState & GetState() const override { return m_tState; } void SetSchema ( ISphSchema * pSchema, bool bRemapCmp ) override; const ISphSchema * GetSchema() const override { return ( ISphSchema *) m_pSchema; } void SetColumnar ( columnar::Columnar_i * pColumnar ) override { m_pColumnar = pColumnar; } int64_t GetTotalCount() const override { return m_iTotal; } void CloneTo ( ISphMatchSorter * pTrg ) const override; bool CanBeCloned() const override; void SetFilteredAttrs ( const sph::StringSet & hAttrs, bool bAddDocid ) override; void TransformPooled2StandalonePtrs ( GetBlobPoolFromMatch_fn fnBlobPoolFromMatch, GetColumnarFromMatch_fn fnGetColumnarFromMatch, bool bFinalizeSorters ) override; void SetRandom ( bool bRandom ) override { m_bRandomize = bRandom; } bool IsRandom() const override { return m_bRandomize; } int GetMatchCapacity() const override { return m_iMatchCapacity; } RowTagged_t GetJustPushed() const override { return m_tJustPushed; } VecTraits_T<RowTagged_t> GetJustPopped() const override { return m_dJustPopped; } protected: SharedPtr_t<ISphSchema> m_pSchema; ///< sorter schema (adds dynamic attributes on top of index schema) CSphMatchComparatorState m_tState; ///< protected to set m_iNow automatically on SetState() calls StrVec_t m_dTransformed; columnar::Columnar_i * m_pColumnar = nullptr; bool m_bRandomize = false; int64_t m_iTotal = 0; int m_iMatchCapacity = 0; RowTagged_t m_tJustPushed; CSphTightVector<RowTagged_t> m_dJustPopped; }; /// match-sorting priority queue traits class CSphMatchQueueTraits : public MatchSorter_c, ISphNoncopyable { public: explicit CSphMatchQueueTraits ( int iSize ); ~CSphMatchQueueTraits () override; int GetLength() override { return Used(); } void SwapMatchQueueTraits ( CSphMatchQueueTraits& rhs ); const VecTraits_T<CSphMatch> & GetMatches() const { return m_dData; } protected: int m_iSize; // size of internal struct we can operate CSphFixedVector<CSphMatch> m_dData; CSphTightVector<int> m_dIData; // indexes into m_pData, to avoid extra moving of matches themselves CSphMatch * Last() const { return &m_dData[m_dIData.Last ()]; } CSphMatch & Get ( int iElem ) const { return m_dData[m_dIData[iElem]]; } CSphMatch & Add(); int Used() const { return m_dIData.GetLength(); } bool IsEmpty() const { return m_dIData.IsEmpty(); } void ResetAfterFlatten() { m_dIData.Resize(0); } int ResetDynamic ( int iMaxUsed ); int ResetDynamicFreeData ( int iMaxUsed ); }; class MatchCloner_c { public: void SetSchema ( const ISphSchema * pSchema ); // clone plain part (incl. pointers) from src to dst // keep group part (aggregates, group_concat) of dst intact // it assumes that tDst m_pDynamic contains correct data, or wiped away. void CloneKeepingAggrs ( CSphMatch & tDst, const CSphMatch & tSrc ); // clone plain part (incl. pointers) from src to dst // group part (aggregates, group_concat) is not copied void CloneWithoutAggrs ( CSphMatch & tDst, const CSphMatch & tSrc ); // just write group part (aggregates, group_concat) without cloning // assumes tDst has allocated m_pDynamic. Fixme! look to #881 again... void CopyAggrs ( CSphMatch & tDst, const CSphMatch & tSrc ); // copy group part (aggregates) // move group_concat part without reallocating void MoveAggrs ( CSphMatch & tDst, CSphMatch & tSrc ); void AddRaw ( const CSphAttrLocator& tLoc ) { m_dAttrsGrp.Add(tLoc); } void AddPtr ( const CSphAttrLocator &tLoc ) { m_dAttrsPtr.Add(tLoc); } void ResetAttrs(); // (re)fill m_dMyPtrRows and m_dOtherPtrRows from m_dAttrsPtr void CommitPtrs(); private: CSphFixedVector<CSphRowitem> m_dRowBuf { 0 }; CSphVector<CSphAttrLocator> m_dAttrsGrp; // locators for grouping attrs (@groupby, @count, @distinct, etc.) CSphVector<CSphAttrLocator> m_dAttrsPtr; // locators for group_concat attrs CSphVector<int> m_dMyPtrRows; // rowids matching m_dAttrsPtr. i.e. grpconcat ptr result I own CSphVector<int> m_dOtherPtrRows; // rest rowids NOT matching m_dAttrsPtr. i.e. other ptr results const CSphSchemaHelper * m_pSchema = nullptr; bool m_bPtrRowsCommited = false; // readiness of m_dMyPtrRows and m_dOtherPtrRows }; class BaseGroupSorter_c : public BlobPool_c, protected CSphGroupSorterSettings { public: BaseGroupSorter_c ( const CSphGroupSorterSettings & tSettings ) { (CSphGroupSorterSettings&)(*this) = tSettings; } ~BaseGroupSorter_c() override { ResetAggregates(); } protected: MatchCloner_c m_tPregroup; CSphVector<AggrFunc_i *> m_dAggregates; void SetColumnar ( columnar::Columnar_i * pColumnar ); void SetupBaseGrouper ( ISphSchema * pSchema, int iDistinct, CSphVector<AggrFunc_i *> * pAvgs = nullptr ); // HAVING filtering bool EvalHAVING ( const CSphMatch& tMatch ); void AggrUpdate ( CSphMatch & tDst, const CSphMatch & tSrc, bool bGrouped, bool bMerge = false ); void AggrSetup ( CSphMatch & tDst, const CSphMatch & tSrc, bool bMerge = false ); void AggrUngroup ( CSphMatch & tMatch ); private: void ResetAggregates(); };
5,852
C++
.h
115
48.869565
168
0.745136
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,210
costestimate.h
manticoresoftware_manticoresearch/src/costestimate.h
// // Copyright (c) 2018-2024, Manticore Software LTD (https://manticoresearch.com) // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #ifndef _costestimate_ #define _costestimate_ #include "sphinx.h" class CostEstimate_i { public: virtual ~CostEstimate_i() = default; virtual float CalcQueryCost() = 0; }; float EstimateMTCost ( float fCost, int iThreads ); float EstimateMTCostCS ( float fCost, int iThreads ); float EstimateMTCostSI ( float fCost, int iThreads ); float EstimateMTCostSIFT ( float fCost, int iThreads ); struct SecondaryIndexInfo_t { CSphVector<SecondaryIndexType_e> m_dCapabilities; SecondaryIndexType_e m_eType = SecondaryIndexType_e::FILTER; SecondaryIndexType_e m_eForce = SecondaryIndexType_e::NONE; int64_t m_iRsetEstimate = 0; int64_t m_iTotalValues = 0; // total values (used mainly for MVAs; different from total docs) int64_t m_iPartialColumnarMinMax = -1; uint32_t m_uNumSIIterators = 0; bool m_bHasHistograms = false; bool m_bUsable = false; bool m_bCreated = false; }; class SIContainer_c; struct SelectIteratorCtx_t { const CSphQuery & m_tQuery; const CSphVector<CSphFilterSettings> & m_dFilters; const ISphSchema & m_tIndexSchema; const ISphSchema & m_tSorterSchema; const HistogramContainer_c * m_pHistograms = nullptr; columnar::Columnar_i * m_pColumnar = nullptr; const SIContainer_c & m_tSI; int m_iCutoff = -1; int64_t m_iTotalDocs = 0; int m_iThreads = 1; bool m_bCalcPushCost = true; bool m_bFromIterator = false; float m_fDocsLeft = 1.0f; SelectIteratorCtx_t ( const CSphQuery & tQuery, const CSphVector<CSphFilterSettings> & dFilters, const ISphSchema & tIndexSchema, const ISphSchema & tSorterSchema, const HistogramContainer_c * pHistograms, columnar::Columnar_i * pColumnar, const SIContainer_c & tSI, int iCutoff, int64_t iTotalDocs, int iThreads ); bool IsEnabled_SI ( const CSphFilterSettings & tFilter ) const; bool IsEnabled_Analyzer ( const CSphFilterSettings & tFilter ) const; void IgnorePushCost() { m_bCalcPushCost = false; } }; struct NodeEstimate_t; CostEstimate_i * CreateCostEstimate ( const CSphVector<SecondaryIndexInfo_t> & dSIInfo, const SelectIteratorCtx_t & tCtx, int iCutoff ); float CalcFTIntersectCost ( const NodeEstimate_t & tEst1, const NodeEstimate_t & tEst2, int64_t iTotalDocs, int iDocsPerBlock1, int iDocsPerBlock2 ); #endif // _costestimate_
2,713
C++
.h
60
43.516667
318
0.744512
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,211
coroutine.h
manticoresoftware_manticoresearch/src/coroutine.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #pragma once #include "threadutils.h" #include "mini_timer.h" #include <atomic> #include <chrono> #include <optional> // note: we not yet link to boost::fiber, so just inclusion of some of it's header is enough. // Once we do link - add searching of that component into Cmake, than m.b. remove this comment as redundant #include "coro_waker.h" #define LOG_LEVEL_RESEARCH true #define LOG_COMPONENT_OBJ this << " " #define LOG_COMPONENT_COROEV LOG_COMPONENT_OBJ << m_szName << ": " #define LEVENT if ( LOG_LEVEL_RESEARCH ) LOG_MSG << LOG_COMPONENT_COROEV namespace Threads { /// get the pointer to my job's stack (m.b. different from thread stack in coro) const void* MyStack(); /// get size of the stack (either thread, either coro - depends from context) int MyStackSize(); /// get size of used stack (threads or coro - depends from context) int64_t GetStackUsed(); // helper to align stack suze size_t AlignStackSize ( size_t iSize ); // used as signaller - invokes custom deleter in d-tr. using Waiter_t = SharedPtrCustom_t<void>; // perform handler in plain coro (as continuation), or in dedicated (if called from plain thread) void CallPlainCoroutine ( Handler fnHandler, Scheduler_i* pScheduler = nullptr ); void CallCoroutine ( Handler fnHandler ); bool CallCoroutineRes ( Predicate fnHandler ); // start handler in coroutine, self (if any) or main scheduler, second-priority void StartJob ( Handler handler, Scheduler_i * pScheduler = GlobalWorkPool() ); // perform handler in custom stack // note: handler is called as linear routine, without scheduler. // It should NOT switch context (i.e. no yield/resume) void MockCallCoroutine ( VecTraits_T<BYTE> dStack, Handler fnHandler ); // if returns true - we could perform runtime calculation of stack sizes. bool StackMockingAllowed(); // N of running threads in scheduler, or in global scheduler int NThreads (); Handler CurrentRestarter ( bool bVip = true ) noexcept; Coro::Waker_c CreateWaker( Coro::Worker_c* pWorker = nullptr ) noexcept; // Returns smart pointer, which will issue rescheduling of current coro on destroy. // restarter - pushes to usual working queue, continuator - try to resume immediately, then pushes to vip queue. Waiter_t DefferedRestarter() noexcept; Waiter_t DefferedContinuator() noexcept; // yield, then release passed waiter. void WaitForDeffered ( Waiter_t&& ) noexcept; // start dTasks, then yield until iN of them completed. Returns idx of the task which fired the trigger int WaitForN ( DWORD uN, std::initializer_list<Handler> dTasks ); // set to 1 for manual testing/debugging in single thread and predefined sequence of chunks #define MODELING 0 /** Federate context - manages non-thread-safe shared things in mult-threaded working. Basic idea: in one thread we may just use our thing in serial way. But if they may be copied/cloned - we may run several threads, each with own independed copy/clone. If the things collect something, on finish we may iterate over the clones and collect the data from them. Example: we have FOO dFoo and FEE *pFee, both not thread-safe, both clonable. We want to run 100 similar tasks which shares these objects and might be run in parallel. First, wrap their types into structs: struct RefContext // lightweight: contains only references or pointers to original objects { FOO &m_dFoo; FEE *m_pFee; RefContext (FOO & dFoo, FEE * pFee) : m_dFoo(dFoo), m_pFee(pFee) {} // that is to collect results from the clones void MergeChild ( RefContext dChild ); // if clonable, we may parallelize, if not - only single thread serial work possible bool IsClonable() { return true; } }; struct Context // full clones or copies: will be used instead of originals in other coroutines. { FOO m_dFoo; FEE m_pFee; // must initialize fields by cloning parent's one Context ( const RefContext& dParent ); operator RefContext() { return { m_dFoo, &m_pFee }; } } 1. Before work, create context. C-tr params is directly forwarded to ctr of RefContext. i.e., for RefContext (FOO & dFoo, FEE * pFee) ctr will be ClonableCtx_T<RefContext,... > (FOO & dFoo, FEE * pFee) FOO dParentFoo; FEE dParentFee; ... ClonableCtx_T<RefContext, Context> dCtx (dParentFoo, &dParentFee); 2. Pass ref to created context to coroutines (via capturing by ref, pointer, whatever). 3. Run tasks, using result of Concurrency ( NJobs ) as number of workers. 3. Inside worker, call member CloneNewContext() and use it exclusively. For first call it just returns ref to the context by c-tr, no overhead for extra cloning. Every next call will clone that original context and provide you ref to it, use it exclusively. That is good to check first, if you really need the context (say, if whole queue of tasks to proceed is already abandoned - you have nothing to do and most probably don't need this clone). When parent is non-clonable, concurrency will return '1', and so, the only task will be in work. If it *is* clonable - you may have up to concurrency parallel workers (but it is no necessary that all of them actually will be in game; quite often ones started earlier completes whole queue before later run). After finish, if you collect some state, use either Finalize() - will provide results to bottom context from children (if any). Or ForAll() - to just iterate all contexts bOrdered indicates whether order of processing is important. In this case very first job will surely come to parent context. That is may be case for querying disk chunks, or pseudo-shares of a plain index. But for parallel pq/snippets that is not the case. **/ enum class ECONTEXT { UNORDERED, ORDERED }; template <typename REFCONTEXT, typename CONTEXT, ECONTEXT IS_ORDERED> class ClonableCtx_T { REFCONTEXT m_dParentContext; CSphFixedVector<std::optional<CONTEXT>> m_dChildrenContexts {0}; CSphFixedVector<int> m_dJobsOrder {0}; std::atomic<int> m_iTasks {0}; // each call to CloneNewContext() increases value bool m_bSingle; // ctr with disabled (single-thread) working public: template <typename... PARAMS > explicit ClonableCtx_T ( PARAMS && ... tParams ); bool IsSingle() const; // Num of parallel workers to complete iTasks jobs void LimitConcurrency ( int iDistThreads ); int Concurrency ( int iTasks ) const; void Finalize(); // called once per coroutine, when it really has to process something. 2-nd result is JobID, m.b. used in SetJobOrder. template <ECONTEXT ORD = IS_ORDERED> std::enable_if_t<ORD == ECONTEXT::UNORDERED, std::pair<REFCONTEXT, int>> CloneNewContext(); template<ECONTEXT ORD = IS_ORDERED> std::enable_if_t<ORD == ECONTEXT::ORDERED, std::pair<REFCONTEXT, int>> CloneNewContext ( bool bFirst ); // set (optionally) 'weight' of a job; ForAll will iterate jobs according to ascending weights template<ECONTEXT ORD = IS_ORDERED> std::enable_if_t<ORD == ECONTEXT::ORDERED> SetJobOrder ( int iCtxID, int iOrder ); // informational int NumWorked() const; template<typename FNPROCESSOR, ECONTEXT ORD = IS_ORDERED> std::enable_if_t<ORD == ECONTEXT::UNORDERED> ForAll ( FNPROCESSOR fnProcess, bool bIncludeRoot ); private: template<typename FNPROCESSOR, ECONTEXT ORD = IS_ORDERED> std::enable_if_t<ORD == ECONTEXT::ORDERED> ForAll ( FNPROCESSOR fnProcess, bool bIncludeRoot ); }; // create context and return resuming functor. // calling resumer will run handler until it finishes or yields. // returns flag of how coroutine interrupted: finished(true) or yielded(false) using Resumer_fn = std::function<bool()>; Resumer_fn MakeCoroExecutor ( Handler fnHandler ); bool IsInsideCoroutine(); namespace Coro { Worker_c* CurrentWorker() noexcept; // call CurrentWorker and assert it is not null Worker_c* Worker() noexcept; // start handler in coroutine, first-priority void Go ( Handler&& handler, Scheduler_i* pScheduler ); // start task continuation in coroutine, second-priority void Co ( Handler&& handler, Waiter_t tSignaller ); // perform handler in dedicated coro with custom stack (scheduler is same, or global if none) // try to run immediately (if thread wasn't switched yet), or push to first-priority queue void Continue ( Handler&& fnHandler, int iStack=0 ); // if iStack<0, just immediately invoke the handler (that is bypass) template<typename HANDLER> void Continue ( int iStack, HANDLER&& handler ); // if iStack<0, just immediately invoke the handler (that is bypass). Returns boolean result from handler template<typename HANDLER> bool ContinueBool ( int iStack, HANDLER handler ); // Run handler in single or many user threads. // NOTE! even with concurrency==1 it is not sticked to the same OS thread, so avoid using thread-local storage. void ExecuteN ( int iConcurrency, Handler&& handler ); Scheduler_i * CurrentScheduler (); // yield (pause), and then run handler outside void YieldWith ( Handler handler ) noexcept; // move coroutine to another scheduler void MoveTo ( Scheduler_i * pScheduler ) noexcept; // yield to external context. Underscore (_) added to name due to MS Windows build issue void Yield_ () noexcept; void Reschedule() noexcept; int ID() noexcept; int NumOfRestarts() noexcept; static const int tmDefaultThrotleTimeQuantumMs = 100; // default value, if nothing specified // that changes default daemon-wide void SetDefaultThrottlingPeriodMS ( int tmPeriodMs ); // -1 means 'use value of tmThrotleTimeQuantumMs' // 0 means 'don't throttle' // any other positive expresses throttling interval in milliseconds void SetThrottlingPeriodMS ( int tmPeriodMs = -1 ); void SetThrottlingPeriodUS ( int64_t tmPeriodUs ); int64_t GetThrottlingPeriodUS(); // check if we run > ThrottleQuantum since last resume, or since timer restart bool RuntimeExceeded() noexcept; const int64_t& GetNextTimePointUS() noexcept; // common throttle action - keep crash query and reschedule. Timer will be re-engaged on resume void RescheduleAndKeepCrashQuery ( bool bVip = false ) noexcept; // just re-engage timer, without rescheduling void RestartRuntime() noexcept; inline void ThrottleAndKeepCrashQuery ( bool bVip = false ) noexcept { if ( RuntimeExceeded() ) RescheduleAndKeepCrashQuery ( bVip ); } // yield and reschedule after given period of time (in milliseconds) void SleepMsec ( int iMsec ); // periodical check with minimum footprint. // check may be called with high rate - billions time a sec. // to avoid 'heavy' check, we first measure time of several iterations (1, 2, 3, 5, 8 ... fibonacci), // until measured time reach 1/CHECK_PER_PERIOD of throttling period. Then we run such 'heavy' checks only when reach // measured N of iterations. So, for ~10M iterations we make just 36 measurements, and then make mostly CHECK_PER_PERIOD 'heavy' checks per throttling period. class HighFreqChecker_c : public ISphNoncopyable { static constexpr int CHECK_PER_PERIOD = 8; int m_iHits = -1; /// main hits counter int m_iPivotHits = 0; /// up bound of the counter - do heavy check when reached int m_iFibPrev = 0; /// previous and current fibonacci seq numbers int m_iFibCurrent = 1; /// const int64_t m_iPivotPeriod { GetThrottlingPeriodUS() / CHECK_PER_PERIOD }; /// time in Us until we continue probinb std::chrono::time_point<std::chrono::steady_clock> m_tmFirstHit; /// timestamp of first iteration public: bool operator()(); }; // event is specially designed for netloop - here SetEvent doesn't require to be run from Coro, however WaitEvent does. // by that fact other kind of condvar is not suitable here. class Event_c { enum ESTATE : BYTE { Signaled_e = 1, Waited_e = 2, }; volatile Worker_c* m_pCtx = nullptr; // only one waiter allowed std::atomic<BYTE> m_uState { 0 }; public: ~Event_c(); void SetEvent(); void WaitEvent(); }; // instead of real blocking it yield current coro, so, MUST be used only with coro context class CAPABILITY ( "mutex" ) RWLock_c: public ISphNoncopyable { mutable sph::Spinlock_c m_tInternalMutex {}; WaitQueue_c m_tWaitRQueue {}; WaitQueue_c m_tWaitWQueue {}; DWORD m_uState { 0 }; // lower bit - w-locked, rest - N of r-locks with bias 2 public: RWLock_c() = default; void WriteLock() ACQUIRE(); void ReadLock() ACQUIRE_SHARED(); void Unlock() UNLOCK_FUNCTION(); bool TestNextWlock() const noexcept; }; class CAPABILITY ( "mutex" ) Mutex_c: public ISphNoncopyable { sph::Spinlock_c m_tWaitQueueSpinlock {}; WaitQueue_c m_tWaitQueue {}; Worker_c* m_pOwner { nullptr }; public: using mtx = Mutex_c; Mutex_c() = default; void Lock() ACQUIRE(); void Unlock() RELEASE(); }; using ScopedMutex_t = CSphScopedLock<Mutex_c>; // condition variable - simplified port from Boost::fibers (we don't use timered functions right now) class ConditionVariableAny_c: public ISphNoncopyable { sph::Spinlock_c m_tWaitQueueSpinlock {}; WaitQueue_c m_tWaitQueue {}; public: ConditionVariableAny_c() = default; ~ConditionVariableAny_c() { assert ( m_tWaitQueue.Empty() ); } void NotifyOne() noexcept; void NotifyAll() noexcept; template<typename LockType> void Wait ( LockType& tMutex ) REQUIRES ( tMutex ); template<typename LockType> bool WaitUntil ( LockType& tMutex, int64_t iTimestamp ) REQUIRES ( tMutex ); template<typename LockType> bool WaitForMs ( LockType& tMutex, int64_t iTimePeriodMS ) REQUIRES ( tMutex ); template<typename LockType, typename PRED> void Wait ( LockType& tMutex, PRED fnPred ) REQUIRES ( tMutex ); template<typename LockType, typename PRED> bool WaitUntil ( LockType& tMutex, PRED fnPred, int64_t iTimestamp ) REQUIRES ( tMutex ); template<typename LockType, typename PRED> bool WaitForMs ( LockType& tMutex, PRED fnPred, int64_t iTimePeriodMS ) REQUIRES ( tMutex ); }; class ConditionVariable_c: public ISphNoncopyable { ConditionVariableAny_c m_tCnd; public: ConditionVariable_c() = default; void NotifyOne() noexcept { m_tCnd.NotifyOne(); } void NotifyAll() noexcept { m_tCnd.NotifyAll(); } void Wait ( ScopedMutex_t& lt ) REQUIRES (lt) { m_tCnd.Wait ( lt ); } bool WaitUntil ( ScopedMutex_t& lt, int64_t iTime ) REQUIRES (lt) { return m_tCnd.WaitUntil ( lt, iTime ); } bool WaitForMs ( ScopedMutex_t& lt, int64_t iPeriodMS ) REQUIRES (lt) { return m_tCnd.WaitForMs ( lt, iPeriodMS ); } template<typename PRED> void Wait ( ScopedMutex_t& lt, PRED&& fnPred ) REQUIRES (lt); template<typename PRED> bool WaitUntil ( ScopedMutex_t& lt, PRED&& fnPred, int64_t iTime ) REQUIRES (lt); template<typename PRED> bool WaitForMs ( ScopedMutex_t& lt, PRED&& fnPred, int64_t iPeriodMS ) REQUIRES (lt); }; template<typename T> class Waitable_T: public ISphNoncopyable { mutable ConditionVariable_c m_tCondVar; mutable Mutex_c m_tMutex; T m_tValue { 0 }; public: template<typename... PARAMS> explicit Waitable_T ( PARAMS&&... tParams ); void SetValue ( T tValue ); T ExchangeValue ( T tNewValue ); void SetValueAndNotifyOne ( T tValue ); void SetValueAndNotifyAll ( T tValue ); void UpdateValueAndNotifyOne ( T tValue ); void UpdateValueAndNotifyAll ( T tValue ); template<typename MOD> void ModifyValue ( MOD&& fnMod ); template<typename MOD> void ModifyValueAndNotifyOne ( MOD&& fnMod ); template<typename MOD> void ModifyValueAndNotifyAll ( MOD&& fnMod ); T GetValue() const; const T& GetValueRef() const; inline void NotifyOne(); inline void NotifyAll(); void Wait () const; bool WaitUntil(int64_t iTime) const; bool WaitForMs(int64_t iPeriodMS) const; template<typename PRED> T Wait ( PRED&& fnPred ) const; template<typename PRED> T WaitUntil ( PRED&& fnPred, int64_t iTime ) const; template<typename PRED> T WaitForMs ( PRED&& fnPred, int64_t iPeriodMs ) const; template<typename PRED> void WaitVoid ( PRED&& fnPred ) const; template<typename PRED> bool WaitVoidUntil ( PRED&& fnPred, int64_t iTime ) const; template<typename PRED> bool WaitVoidForMs ( PRED&& fnPred, int64_t iPeriodMs ) const; }; } // namespace Coro /// capability for tracing scheduler using SchedRole CAPABILITY ( "role" ) = Scheduler_i*; using RoledSchedulerSharedPtr_t CAPABILITY ( "role" ) = SchedulerSharedPtr_t; inline void AcquireSched ( SchedRole R ) ACQUIRE( R ) NO_THREAD_SAFETY_ANALYSIS { Coro::MoveTo ( R ); } inline void AcquireSched ( RoledSchedulerSharedPtr_t & R ) ACQUIRE( R ) NO_THREAD_SAFETY_ANALYSIS { Coro::MoveTo ( R ); } class SCOPED_CAPABILITY ScopedScheduler_c : ISphNoncopyable { SchedRole m_pRoleRef = nullptr; public: ScopedScheduler_c() = default; explicit ScopedScheduler_c ( SchedRole pRole ) ACQUIRE ( pRole ); explicit ScopedScheduler_c ( RoledSchedulerSharedPtr_t& pRole ) ACQUIRE ( pRole ); ~ScopedScheduler_c () RELEASE(); }; inline void CheckAcquiredSched ( SchedRole R ) ACQUIRE( R ) NO_THREAD_SAFETY_ANALYSIS { // assert ( !Coro::CurrentScheduler () || R==Coro::CurrentScheduler() ); assert ( R== Coro::CurrentScheduler () ); } inline void CheckAcquiredSched ( RoledSchedulerSharedPtr_t& R ) ACQUIRE( R ) NO_THREAD_SAFETY_ANALYSIS { // assert ( !Coro::CurrentScheduler () || R==Coro::CurrentScheduler () ); assert ( R== Coro::CurrentScheduler () ); } inline void CheckReleasedSched ( SchedRole R ) RELEASE( R ) NO_THREAD_SAFETY_ANALYSIS { } inline void CheckReleasedSched ( RoledSchedulerSharedPtr_t & R ) RELEASE( R ) NO_THREAD_SAFETY_ANALYSIS { } class SCOPED_CAPABILITY CheckRole_c { public: /// acquire on creation inline explicit CheckRole_c ( SchedRole tRole ) ACQUIRE( tRole ) { CheckAcquiredSched ( tRole ); } /// release on going out of scope ~CheckRole_c () RELEASE() = default; }; using SccRL_t = CSphScopedRLock_T<Coro::RWLock_c>; using SccWL_t = CSphScopedWLock_T<Coro::RWLock_c>; using ScopedCoroMutex_t = Coro::ScopedMutex_t; // fake locks using FakeRL_t = FakeScopedRLock_T<Coro::RWLock_c>; using FakeWL_t = FakeScopedWLock_T<Coro::RWLock_c>; } // namespace Threads #include "detail/coroutine_impl.h"
18,194
C++
.h
394
44.329949
158
0.759113
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,212
memio.h
manticoresoftware_manticoresearch/src/memio.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #ifndef _memio_ #define _memio_ #include "sphinxstd.h" #include "fileio.h" class MemoryReader_c { public: MemoryReader_c ( const BYTE * pData, int iLen ) noexcept; explicit MemoryReader_c ( ByteBlob_t dData ) noexcept; int GetPos() const; void SetPos ( int iOff ); uint64_t UnzipOffset(); DWORD UnzipInt(); CSphString GetString(); SphOffset_t GetOffset(); DWORD GetDword(); void GetBytes ( void * pData, int iLen ); const BYTE * Begin() const; int GetLength() const; bool HasData() const; template<typename T> T GetVal (); template<typename T> void GetVal ( T& tVal ); protected: const BYTE * m_pData = nullptr; const int m_iLen = 0; const BYTE * m_pCur = nullptr; }; template<typename T> T GetVal( MemoryReader_c& tReader ); // first DWORD is len, then follows data template<typename VECTOR> void GetArray ( VECTOR& dBuf, MemoryReader_c& tIn ); void GetArray ( CSphVector<CSphString>& dBuf, MemoryReader_c& tIn ); class MemoryWriter_c : public Writer_i { public: MemoryWriter_c ( CSphVector<BYTE> & dBuf ); int GetPos(); void ZipOffset ( uint64_t uVal ) override; void ZipInt ( DWORD uVal ) override; void PutString ( const CSphString & sVal ) override; void PutString ( const char * szVal ) override; void PutZString ( const CSphString & sVal ) final; void PutZString ( const char * szVal ) final; void PutDword ( DWORD uVal ) override; void PutOffset ( SphOffset_t uValue ) override; void PutWord ( WORD uVal ) override; void PutBytes ( const void * pData, int64_t iLen ) override; void PutByte ( BYTE uVal ) override; void PutUint64 ( uint64_t uVal ); template<typename T> void PutVal ( T tVal ); protected: CSphVector<BYTE> & m_dBuf; }; template<typename T> void PutVal ( MemoryWriter_c& tWriter, T tVal ); // put DWORD size, then elems template<typename T> void SaveArray ( const VecTraits_T<T>& dBuf, MemoryWriter_c& tOut ); void SaveArray ( const VecTraits_T<CSphString>& dBuf, MemoryWriter_c& tOut ); // fixme: get rid of this class MemoryReader2_c : public MemoryReader_c { public: MemoryReader2_c ( const BYTE * pData, int iLen ); uint64_t UnzipInt(); uint64_t UnzipOffset(); }; // fixme: get rid of this class MemoryWriter2_c : public MemoryWriter_c { public: MemoryWriter2_c ( CSphVector<BYTE> & dBuf ); void ZipOffset ( uint64_t uVal ) override; void ZipInt ( DWORD uVal ) override; }; #include "memio_impl.h" #endif // _memio_
2,922
C++
.h
92
29.869565
80
0.729865
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,213
jsonqueryfilter.h
manticoresoftware_manticoresearch/src/jsonqueryfilter.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #ifndef _jsonqueryfilter_ #define _jsonqueryfilter_ #include "sphinxjson.h" struct CSphQuery; struct LocationField_t { float m_fLat = 0.0f; float m_fLon = 0.0f; }; struct LocationSource_t { CSphString m_sLat; CSphString m_sLon; }; class GeoDistInfo_c { public: bool Parse ( const JsonObj_c & tRoot, bool bNeedDistance, CSphString & sError, CSphString & sWarning ); CSphString BuildExprString() const; bool IsGeoDist() const { return m_bGeodist; } float GetDistance() const { return m_fDistance; } private: bool m_bGeodist {false}; bool m_bGeodistAdaptive {true}; float m_fDistance {0.0f}; LocationField_t m_tLocAnchor; LocationSource_t m_tLocSource; bool ParseDistance ( const JsonObj_c & tDistance, CSphString & sError ); }; const char * GetFilterAttrPrefix(); bool IsFilter ( const JsonObj_c & tJson ); bool ParseJsonQueryFilters ( const JsonObj_c & tJson, CSphQuery & tQuery, CSphString & sError, CSphString & sWarning ); #endif
1,367
C++
.h
42
30.880952
121
0.745995
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,214
compressed_mysql_layer.h
manticoresoftware_manticoresearch/src/compressed_mysql_layer.h
// // Copyright (c) 2021-2024, Manticore Software LTD (https://manticoresearch.com) // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #pragma once #include "networking_daemon.h" #include "sphinxstd.h" // payloads below this threshold will be send as 'uncompressed' packets static const int MIN_COMPRESS_LENGTH = 50; class MysqlCompressedSocket_c : public AsyncNetBuffer_c { protected: std::unique_ptr<AsyncNetBuffer_c> m_pFrontend; AsyncNetInputBuffer_c& m_tIn; GenericOutputBuffer_c& m_tOut; BYTE m_uPackedID = 0; DWORD ReadLSBSmallDword ( InputBuffer_c& tIn ); void SendLSBSmallDword ( DWORD uValue ); public: explicit MysqlCompressedSocket_c ( std::unique_ptr<AsyncNetBuffer_c> pFrontend ); void SetWTimeoutUS ( int64_t iTimeoutUS ) final; int64_t GetWTimeoutUS() const final; void SetTimeoutUS ( int64_t iTimeoutUS ) final; int64_t GetTimeoutUS() const final; int64_t GetTotalReceived() const final; int64_t GetTotalSent() const final; }; template<typename COMPR> class MysqlCompressedSocket_T : public MysqlCompressedSocket_c, public COMPR { bool SendPacket ( ByteBlob_t dBlob ) { // send as uncompressed if ( dBlob.second < MIN_COMPRESS_LENGTH ) { SendLSBSmallDword ( dBlob.second ); m_tOut.SendByte ( ++m_uPackedID ); SendLSBSmallDword ( 0 ); m_tOut.SendBytes ( dBlob ); return m_tOut.Flush(); } // compress and send compressed blob auto iPos = m_tOut.GetSentCount(); auto uSpace = COMPR::Common_compressBound ( dBlob.second ); auto pOut = m_tOut.ReservePlace ( uSpace + 7 ); m_tOut.SendBytes ( &uSpace, 3 ); m_tOut.SendByte ( ++m_uPackedID ); SendLSBSmallDword ( dBlob.second ); COMPR::Common_compress ( pOut + 7, &uSpace, dBlob.first, dBlob.second ); m_tOut.Rewind ( iPos ); SendLSBSmallDword ( uSpace ); m_tOut.CommitZeroCopy ( uSpace + 4 ); return m_tOut.Flush(); } protected: int ReadFromBackend ( int iNeed, int, bool bIntr ) final { int iRead = 0; while ( iNeed > iRead ) { // compressed packet header: 3 bytes of raw size, 1 byte packet id, 3 bytes of uncompressed size if ( !m_tIn.ReadFrom ( 7, bIntr ) ) return -1; auto uRawSize = ReadLSBSmallDword ( m_tIn ); m_uPackedID = m_tIn.GetByte(); auto uUncompressedSize = (typename COMPR::csize_t) ReadLSBSmallDword ( m_tIn ); // read raw packet (compressed or uncompressed) if ( !m_tIn.ReadFrom ( uRawSize, bIntr ) ) return -1; if ( !uUncompressedSize ) // raw uncompressed, return as is { m_tIn.GetBytes ( AllocateBuffer ( uRawSize ).begin(), uRawSize ); iRead += uRawSize; continue; } // compressed input const BYTE* pFoo = nullptr; m_tIn.GetBytesZerocopy ( &pFoo, uRawSize ); if (!COMPR::Common_uncompress ( AllocateBuffer ( uUncompressedSize ).begin(), &uUncompressedSize, pFoo, uRawSize )) return -1; iRead += uUncompressedSize; } return iRead; } public: explicit MysqlCompressedSocket_T ( std::unique_ptr<AsyncNetBuffer_c> pFrontend ) : MysqlCompressedSocket_c ( std::move ( pFrontend ) ) {} bool SendBuffer ( const VecTraits_T<BYTE>& dData ) final { ByteBlob_t dBlob = dData; static const int iMaxOneCompressedPacketLen = 0x01000000U - 6; while ( !::IsEmpty ( dBlob ) ) { auto iSize = Min ( dBlob.second, iMaxOneCompressedPacketLen ); if ( !SendPacket ( { dBlob.first, iSize } ) ) return false; dBlob.first += iSize; dBlob.second -= iSize; } return true; } };
3,670
C++
.h
108
31.166667
118
0.718556
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,215
tokenizerbase_impl.h
manticoresoftware_manticoresearch/src/tokenizer/tokenizerbase_impl.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #pragma once #include "tokenizer.h" #include "sphinxdefs.h" class ExceptionsTrie_c; class CSphTokenizerBase: public ISphTokenizer { public: CSphTokenizerBase(); bool SetCaseFolding ( const char* sConfig, CSphString& sError ) final; bool LoadSynonyms ( const char* sFilename, const CSphEmbeddedFiles* pFiles, StrVec_t& dWarnings, CSphString& sError ) final; void WriteSynonyms ( Writer_i & tWriter ) const final; void WriteSynonyms ( JsonEscapedBuilder & tOut ) const final; void CloneBase ( const CSphTokenizerBase* pFrom, ESphTokenizerClone eMode ); const char* GetTokenStart() const noexcept final { return (const char*)m_pTokenStart; } const char* GetTokenEnd() const noexcept final { return (const char*)m_pTokenEnd; } const char* GetBufferPtr() const noexcept final { return (const char*)m_pCur; } const char* GetBufferEnd() const noexcept final { return (const char*)m_pBufferMax; } void SetBufferPtr ( const char* sNewPtr ) final; uint64_t GetSettingsFNV() const noexcept final; bool SetBlendChars ( const char* sConfig, CSphString& sError ) final; bool WasTokenMultiformDestination ( bool&, int& ) const noexcept final { return false; } bool IsQueryTok() const noexcept final { return m_eMode != SPH_CLONE_INDEX; } protected: ~CSphTokenizerBase() override; bool BlendAdjust ( const BYTE* pPosition ); int CodepointArbitrationI ( int iCodepoint ); int CodepointArbitrationQ ( int iCodepoint, bool bWasEscaped, BYTE uNextByte ); protected: const BYTE* m_pBuffer = nullptr; ///< my buffer const BYTE* m_pBufferMax = nullptr; ///< max buffer ptr, exclusive (ie. this ptr is invalid, but every ptr below is ok) const BYTE* m_pCur = nullptr; ///< current position const BYTE* m_pTokenStart = nullptr; ///< last token start point const BYTE* m_pTokenEnd = nullptr; ///< last token end point BYTE m_sAccum[3 * SPH_MAX_WORD_LEN + 3]; ///< folded token accumulator BYTE* m_pAccum = nullptr; ///< current accumulator position int m_iAccum = 0; ///< boundary token size BYTE m_sAccumBlend[3 * SPH_MAX_WORD_LEN + 3]; ///< blend-acc, an accumulator copy for additional blended variants int m_iBlendNormalStart = 0; ///< points to first normal char in the accumulators (might be NULL) int m_iBlendNormalEnd = 0; ///< points just past (!) last normal char in the accumulators (might be NULL) ExceptionsTrie_c* m_pExc = nullptr; ///< exceptions trie, if any bool m_bHasBlend = false; const BYTE* m_pBlendStart = nullptr; const BYTE* m_pBlendEnd = nullptr; ESphTokenizerClone m_eMode { SPH_CLONE_INDEX }; };
3,074
C++
.h
74
39.540541
125
0.745059
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,216
tok_internals.h
manticoresoftware_manticoresearch/src/tokenizer/tok_internals.h
// // Copyright (c) 2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org // #pragma once #include "charset_definition_parser.h" struct RemapRangeTagged_t: public CSphRemapRange { int m_iTag = -1; RemapRangeTagged_t() = default; explicit RemapRangeTagged_t ( const CSphRemapRange& tRange ) : CSphRemapRange { tRange } {} }; // need a stable sort with the major tag first inline bool operator< ( const RemapRangeTagged_t& a, const RemapRangeTagged_t& b ) { if ( a.m_iStart == b.m_iStart ) return ( a.m_iTag > b.m_iTag ); return ( a.m_iStart < b.m_iStart ); } class CSphCharsetDefinitionParser { StringBuilder_c m_sError; const char* m_pCurrent = nullptr; static CSphVector<CharsetAlias_t> m_dCharsetAliases; bool Error ( const char* szMessage ); void SkipSpaces(); bool IsEof(); bool CheckEof(); int ParseCharsetCode(); bool AddRange ( CSphRemapRange tRange, CSphVector<RemapRangeTagged_t>& dRanges ); public: bool Parse ( const char* sConfig, CSphVector<CSphRemapRange>& dRanges ); CSphString GetLastError(); static const CSphVector<CharsetAlias_t>& GetCharsetAliases(); static bool InitCharsetAliasTable ( CSphString& sError ); }; // used in tests void MergeIntersectedRanges ( CSphVector<RemapRangeTagged_t>& dRanges ); bool AddRange ( CSphRemapRange tRange, CSphVector<RemapRangeTagged_t>& dRanges, CSphString* pError = nullptr ); struct GtQuotation_t { static constexpr BYTE EscapingSpace ( BYTE c ) { return ( c=='=' || c == '>' ) ? 1 : 0; } static void EscapeChar ( BYTE *& pOut, BYTE c ) { if ( EscapingSpace ( c ) ) *pOut++ = '\\'; *pOut++ = c; } static void EscapeCharWithSpaces ( BYTE *& pOut, BYTE c ) { if ( EscapingSpace ( c ) ) { pOut[0] = '\\'; pOut[1] = c; pOut += 2; } else *pOut++ = c; } }; using GtEscapedBuilder = EscapedStringBuilder_T<GtQuotation_t>;
2,240
C++
.h
72
29.083333
111
0.725035
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,217
lowercaser.h
manticoresoftware_manticoresearch/src/tokenizer/lowercaser.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #pragma once #include "remap_range.h" #include "sphinxstd.h" class CSphLowercaser; using LowercaserRefcountedPtr = CSphRefcountedPtr<CSphLowercaser>; using LowercaserRefcountedConstPtr = CSphRefcountedPtr<const CSphLowercaser>; /// lowercaser class CSphLowercaser final: public ISphRefcountedMT { static constexpr int CHARS_COUNT = 0x30000; static constexpr int CHUNK_BITS = 8; static constexpr int CHUNK_SIZE = 1 << CHUNK_BITS; // 0x100 for 8 bits, 0x200 for 9 bits static constexpr int CHUNK_COUNT = CHARS_COUNT >> CHUNK_BITS; // 0x300 for 8 bits, 0x180 for 9 bits static constexpr int CHUNK_BYTES = CHUNK_SIZE * sizeof ( DWORD ); static constexpr int CHUNK_MASK = CHUNK_SIZE - 1; int m_iChunks = 0; ///< how much chunks are actually allocated CSphFixedVector<DWORD> m_dData {0}; ///< chunks themselves. 1Kb per chunk (256 DWORDs) DWORD* m_pChunk[CHUNK_COUNT] { nullptr }; ///< pointers to non-empty chunks. That is 6kB per table volatile int m_iGeneration = 0; ///< my generation. Each change increases generation mutable CSphMutex m_tLock; ///< protects moment of cache creation from concurrency // with 32-bits pointers: // 8 bits per chunk: 3Kb chunks, 1Kb page. 1 page = 4Kb, 2 pages = 5Kb, 3 pages = 6Kb, 4 pages = 7Kb, 5 pages = 8Kb // 9 bits per chunk: 1.5Kb chunks, 2Kb page. 1 page = 3.5Kb, 2 pages = 5.5Kb, 3 pages = 7.5Kb, 4 pages = 9.5Kb, 5 pages = 11.5Kb // 10 bits per chunk: 0.75Kb chunks, 4Kb page. 1 page = 4.75Kb, 2 pages = 8.75Kb, 3 pages = 12.75Kb, 4 pages = 16.75Kb, 5 pages = 20.75Kb // with 64-bits pointers: // 8 bits per chunk: 6Kb chunks, 1Kb page. 1 page = 7Kb, 2 pages = 8Kb, 3 pages = 9Kb, 4 pages = 10Kb, 5 pages = 11Kb // 9 bits per chunk: 3Kb chunks, 2Kb page. 1 page = 5Kb, 2 pages = 7Kb, 3 pages = 9Kb, 4 pages = 11Kb, 5 pages = 13Kb // 10 bits per chunk: 1.5Kb chunks, 4Kb page. 1 page = 5.5Kb, 2 pages = 9.5Kb, 3 pages = 13.5Kb, 4 pages = 17.5Kb, 5 pages = 21.5Kb // seems that for 64-bits using 9 bits per chunk is better with typical configurations; need to test! void InvalidateStoredClones() noexcept; protected: ~CSphLowercaser() final = default; public: static constexpr int MAX_CODE = CHARS_COUNT; CSphLowercaser() = default; // modifiers void Reset(); void SetRemap ( const CSphLowercaser* pLC ); void AddRemaps ( const VecTraits_T<CSphRemapRange>& dRemaps, DWORD uAddFlags=0, DWORD uResetFlags=0 ); void AddChars ( const char* szChars, DWORD uAddFlags=0, DWORD uResetFlags=0 ); // check that nothing from dRemaps is referenced somewhere bool CheckRemap ( CSphString& sError, const VecTraits_T<CSphRemapRange>& dRemaps, const char* sSource, bool bCanRemap ) const noexcept; // runtime use (const, noexcept, thread-safe) int ToLower ( int iCode ) const noexcept; int GetMaxCodepointLength() const noexcept; uint64_t GetFNV() const noexcept; // buffering stuff. Returns such cached clone instead of full cloning #define LOWERCASE_CLONE( name ) \ private: \ mutable volatile int m_i##name##Gen = -1; \ mutable LowercaserRefcountedConstPtr m_p##name##LC; \ void Up##name##Clone() const noexcept; \ \ public: \ inline LowercaserRefcountedConstPtr Get##name##LC() const noexcept \ { \ Up##name##Clone(); \ assert ( m_p##name##LC ); \ return m_p##name##LC; \ } LOWERCASE_CLONE ( Query ) // GetQueryLC - special "\\" (all the rest also imply that special) LOWERCASE_CLONE ( QueryWildExactJson ) // GetQueryWildExactJsonLC - "*?%" and specials "=" LOWERCASE_CLONE ( QueryWildExact ) // GetQueryWildExactLC - "*?%" and specials "\\=()|-!@~"/^$<" LOWERCASE_CLONE ( QueryWildJson ) // GetQueryWildJsonLC - "*?%" LOWERCASE_CLONE ( QueryWild ) // GetQueryWildLC - "*?%" and specials "()|-!@~"/^$<" LOWERCASE_CLONE ( QueryExactJson ) // GetQueryExactJsonLC - specials "=" LOWERCASE_CLONE ( QueryExact ) // GetQueryExactLC - specials "=()|-!@~"/^$<" // LOWERCASE_CLONE ( QueryJson ) // the same as just 'Query' - special "\\" - that is usual old cloned query LOWERCASE_CLONE ( Query_ ) // GetQuery_LC - specials "()|-!@~"/^$<" #undef LOWERCASE_CLONE }; inline int CSphLowercaser::ToLower ( int iCode ) const noexcept { if ( iCode < 0 || iCode >= MAX_CODE ) return iCode; DWORD* pChunk = m_pChunk[iCode >> CHUNK_BITS]; if ( pChunk ) return (int)pChunk[iCode & CHUNK_MASK]; return 0; }
4,859
C++
.h
91
51.142857
138
0.704211
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,218
tokenizerbase2_impl.h
manticoresoftware_manticoresearch/src/tokenizer/tokenizerbase2_impl.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #pragma once #include "tokenizerbase_impl.h" #include "sphinxdefs.h" #include "sphinxint.h" #include "lowercaser_impl.h" #include "exceptions_trie.h" inline bool IsWhitespace ( int c ) { return ( c == '\0' || c == ' ' || c == '\t' || c == '\r' || c == '\n' ); } inline bool IsPunctuation ( int c ) { return ( c >= 33 && c <= 47 ) || ( c >= 58 && c <= 64 ) || ( c >= 91 && c <= 96 ) || ( c >= 123 && c <= 126 ); } inline bool ShortTokenFilter ( const BYTE* pToken, int iLen ) { return pToken[0] == '*' || ( iLen > 0 && pToken[iLen - 1] == '*' ); } // handles escaped specials that are not in the character set // returns true if the codepoint should be processed as a simple codepoint, // returns false if it should be processed as a whitespace // for example: aaa\!bbb => aaa bbb inline bool Special2Simple ( int& iCodepoint ) { if ( ( iCodepoint & FLAG_CODEPOINT_DUAL ) || !( iCodepoint & FLAG_CODEPOINT_SPECIAL ) ) { iCodepoint &= ~( FLAG_CODEPOINT_SPECIAL | FLAG_CODEPOINT_DUAL ); return true; } return false; } /// methods that get specialized with regards to charset type /// aka GetCodepoint() decoder and everything that depends on it class CSphTokenizerBase2: public CSphTokenizerBase { protected: /// get codepoint inline int GetCodepoint() { while ( m_pCur < m_pBufferMax ) { int iCode = sphUTF8Decode ( m_pCur ); if ( iCode >= 0 ) return iCode; // successful decode } return -1; // eof } /// accum codepoint inline void AccumCodepoint ( int iCode ) { assert ( iCode > 0 ); assert ( m_iAccum >= 0 ); // throw away everything which is over the token size bool bFit = ( m_iAccum < SPH_MAX_WORD_LEN ); bFit &= ( m_pAccum - m_sAccum + SPH_MAX_UTF8_BYTES <= (int)sizeof ( m_sAccum ) ); if ( bFit ) { m_pAccum += sphUTF8Encode ( m_pAccum, iCode ); assert ( m_pAccum >= m_sAccum && m_pAccum < m_sAccum + sizeof ( m_sAccum ) ); m_iAccum++; } } protected: BYTE* GetBlendedVariant(); bool CheckException ( const BYTE* pStart, const BYTE* pCur, bool bQueryMode ); template<bool IS_QUERY, bool IS_BLEND, bool IS_ESCAPE> BYTE* DoGetToken() { // return pending blending variants if_const ( IS_BLEND ) { BYTE* pVar = GetBlendedVariant(); if ( pVar ) return pVar; m_bBlendedPart = ( m_pBlendEnd != nullptr ); } // in query mode, lets capture (soft-whitespace hard-whitespace) sequences and adjust overshort counter // sample queries would be (one NEAR $$$) or (one | $$$ two) where $ is not a valid character bool bGotNonToken = ( !IS_QUERY || m_bPhrase ); // only do this in query mode, never in indexing mode, never within phrases bool bGotSoft = false; // hey Beavis he said soft huh huhhuh m_pTokenStart = nullptr; for ( ;; ) { // get next codepoint const BYTE* const pCur = m_pCur; // to redo special char, if there's a token already int iCodePoint = ( pCur < m_pBufferMax && *pCur < 128 ) ? *m_pCur++ : GetCodepoint(); int iCode = GetLowercaser().ToLower ( iCodePoint ); // handle escaping const bool bWasEscaped = ( ( IS_QUERY || IS_ESCAPE ) && iCodePoint == '\\' ); // whether current codepoint was escaped if ( bWasEscaped ) { iCodePoint = GetCodepoint(); iCode = GetLowercaser().ToLower ( iCodePoint ); if ( !Special2Simple ( iCode ) ) iCode = 0; } // handle eof if ( iCode < 0 ) { FlushAccum(); // suddenly, exceptions if ( m_pExc && m_pTokenStart && CheckException ( m_pTokenStart, pCur, IS_QUERY ) ) return m_sAccum; // skip trailing short word if ( m_iLastTokenLen < m_tSettings.m_iMinWordLen ) { if ( !m_bShortTokenFilter || !ShortTokenFilter ( m_sAccum, m_iLastTokenLen ) ) { if ( m_iLastTokenLen ) ++m_iOvershortCount; m_iLastTokenLen = 0; if_const ( IS_BLEND ) BlendAdjust ( pCur ); return nullptr; } } // keep token end here as BlendAdjust might change m_pCur m_pTokenEnd = m_pCur; // return trailing word if_const ( IS_BLEND && !BlendAdjust ( pCur ) ) return nullptr; if_const ( IS_BLEND && m_bBlended ) return GetBlendedVariant(); return m_sAccum; } // handle all the flags.. if_const ( IS_QUERY ) iCode = CodepointArbitrationQ ( iCode, bWasEscaped, *m_pCur ); else if ( m_bDetectSentences ) iCode = CodepointArbitrationI ( iCode ); // handle ignored chars if ( iCode & FLAG_CODEPOINT_IGNORE ) continue; // handle blended characters if_const ( IS_BLEND && ( iCode & FLAG_CODEPOINT_BLEND ) ) { if ( m_pBlendEnd ) iCode = 0; else { m_bBlended = true; m_pBlendStart = m_iAccum ? m_pTokenStart : pCur; } } // handle soft-whitespace-only tokens if ( !bGotNonToken && !m_iAccum ) { if ( !bGotSoft ) { // detect opening soft whitespace if ( ( iCode == 0 && !IsWhitespace ( iCodePoint ) && !IsPunctuation ( iCodePoint ) ) || ( ( iCode & FLAG_CODEPOINT_BLEND ) && !m_iAccum ) ) { bGotSoft = true; } } else { // detect closing hard whitespace or special // (if there was anything meaningful in the meantime, we must never get past the outer if!) if ( IsWhitespace ( iCodePoint ) || ( iCode & FLAG_CODEPOINT_SPECIAL ) ) { ++m_iOvershortCount; bGotNonToken = true; } } } // handle whitespace and boundary if ( m_bBoundary && ( iCode == 0 ) ) { m_bTokenBoundary = true; m_iBoundaryOffset = int ( pCur - m_pBuffer - 1 ); } m_bBoundary = ( iCode & FLAG_CODEPOINT_BOUNDARY ) != 0; // handle separator (aka, most likely a token!) if ( iCode == 0 || m_bBoundary ) { FlushAccum(); // suddenly, exceptions if ( m_pExc && CheckException ( m_pTokenStart ? m_pTokenStart : pCur, pCur, IS_QUERY ) ) return m_sAccum; if_const ( IS_BLEND && !BlendAdjust ( pCur ) ) continue; if ( m_iLastTokenLen < m_tSettings.m_iMinWordLen && !( m_bShortTokenFilter && ShortTokenFilter ( m_sAccum, m_iLastTokenLen ) ) ) { if ( m_iLastTokenLen ) ++m_iOvershortCount; continue; } else { m_pTokenEnd = pCur; if_const ( IS_BLEND && m_bBlended ) return GetBlendedVariant(); return m_sAccum; } } // handle specials if ( iCode & FLAG_CODEPOINT_SPECIAL ) { // skip short words preceding specials if ( m_iAccum < m_tSettings.m_iMinWordLen ) { m_sAccum[m_iAccum] = '\0'; if ( !m_bShortTokenFilter || !ShortTokenFilter ( m_sAccum, m_iAccum ) ) { if ( m_iAccum ) m_iOvershortCount++; FlushAccum(); } } if ( m_iAccum == 0 ) { m_bNonBlended = m_bNonBlended || ( !( iCode & FLAG_CODEPOINT_BLEND ) && !( iCode & FLAG_CODEPOINT_SPECIAL ) ); m_bWasSpecial = !( iCode & FLAG_CODEPOINT_NGRAM ); m_pTokenStart = pCur; m_pTokenEnd = m_pCur; AccumCodepoint ( iCode & MASK_CODEPOINT ); // handle special as a standalone token } else { m_pCur = pCur; // we need to flush current accum and then redo special char again m_pTokenEnd = pCur; } FlushAccum(); // suddenly, exceptions if ( m_pExc && m_pTokenStart && CheckException ( m_pTokenStart, pCur, IS_QUERY ) ) return m_sAccum; if_const ( IS_BLEND ) { if ( !BlendAdjust ( pCur ) ) continue; if ( m_bBlended ) return GetBlendedVariant(); } return m_sAccum; } if ( m_iAccum == 0 ) m_pTokenStart = pCur; // tricky bit // heading modifiers must not (!) affected blended status // eg. we want stuff like '=-' (w/o apostrophes) thrown away when pure_blend is on if_const ( IS_BLEND ) if_const ( !( IS_QUERY && !m_iAccum && sphIsModifier ( iCode & MASK_CODEPOINT ) ) ) m_bNonBlended = m_bNonBlended || !( iCode & FLAG_CODEPOINT_BLEND ); // just accumulate // manual inlining of utf8 encoder gives us a few extra percent // which is important here, this is a hotspot if ( m_iAccum < SPH_MAX_WORD_LEN && ( m_pAccum - m_sAccum + SPH_MAX_UTF8_BYTES <= (int)sizeof ( m_sAccum ) ) ) { iCode &= MASK_CODEPOINT; m_iAccum++; SPH_UTF8_ENCODE ( m_pAccum, iCode ); } } } void FlushAccum(); public: int SkipBlended() final; };
8,727
C++
.h
265
28.762264
125
0.636288
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,219
tokenizer.h
manticoresoftware_manticoresearch/src/tokenizer/tokenizer.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #pragma once #include "sphinxstd.h" #include "lowercaser.h" #include "indexsettings.h" #include "fileutils.h" class CSphWriter; class CSphSchema; class FilenameBuilder_i; struct CSphMultiformContainer; struct CSphEmbeddedFiles; enum ESphBigram : BYTE; ///////////////////////////////////////////////////////////////////////////// /// TOKENIZERS ///////////////////////////////////////////////////////////////////////////// enum ESphTokenizerClone { SPH_CLONE_INDEX, ///< clone tokenizer and set indexing mode SPH_CLONE_QUERY, ///< clone tokenizer and set querying mode SPH_CLONE_QUERY_WILD_EXACT_JSON, SPH_CLONE_QUERY_WILD_EXACT, SPH_CLONE_QUERY_WILD_JSON, SPH_CLONE_QUERY_WILD, SPH_CLONE_QUERY_EXACT_JSON, SPH_CLONE_QUERY_EXACT, SPH_CLONE_QUERY_, SPH_CLONE, ///< just clone 'as is' }; enum ESphTokenMorph { SPH_TOKEN_MORPH_RAW, ///< no morphology applied, tokenizer does not handle morphology SPH_TOKEN_MORPH_ORIGINAL, ///< no morphology applied, but tokenizer handles morphology SPH_TOKEN_MORPH_GUESS ///< morphology applied }; /// generic tokenizer class ISphTokenizer : public ISphRefcountedMT { /// trivial dtor - inherited from Refcounted protected: ~ISphTokenizer() override = default; public: /// set new translation table /// returns true on success, false on failure virtual bool SetCaseFolding ( const char * sConfig, CSphString & sError ); /// add additional character as valid (with folding to itself) virtual void AddPlainChars ( const char* szChars ); /// add special chars to translation table /// updates lowercaser so that these remap to -1 virtual void AddSpecials ( const char * sSpecials ); /// set ignored characters virtual bool SetIgnoreChars ( const char * sIgnored, CSphString & sError ); /// set n-gram characters (for CJK n-gram indexing) virtual bool SetNgramChars ( const char *, CSphString & ) { return true; } /// set n-gram length (for CJK n-gram indexing) virtual void SetNgramLen ( int ) {} /// load synonyms list virtual bool LoadSynonyms ( const char * sFilename, const CSphEmbeddedFiles * pFiles, StrVec_t & dWarnings, CSphString & sError ) = 0; /// write synonyms to file virtual void WriteSynonyms ( Writer_i & tWriter ) const = 0; virtual void WriteSynonyms ( JsonEscapedBuilder & tOut ) const = 0; /// set phrase boundary chars virtual bool SetBoundary ( const char * sConfig, CSphString & sError ); /// set blended characters virtual bool SetBlendChars ( const char * sConfig, CSphString & sError ); /// set blended tokens processing mode virtual bool SetBlendMode ( const char * sMode, CSphString & sError ); /// setup tokenizer using given settings virtual void Setup ( const CSphTokenizerSettings & tSettings ); /// save tokenizer settings to a stream virtual const CSphTokenizerSettings & GetSettings () const { return m_tSettings; } /// get synonym file info virtual const CSphSavedFile & GetSynFileInfo () const { return m_tSynFileInfo; } public: /// pass next buffer virtual void SetBuffer ( const BYTE * sBuffer, int iLength ) = 0; /// set current index schema (only intended for the token filter plugins) virtual bool SetFilterSchema ( const CSphSchema &, CSphString & ) { return true; } /// set per-document options from INSERT virtual bool SetFilterOptions ( const char *, CSphString & ) { return true; } /// notify tokenizer that we now begin indexing a field with a given number (only intended for the token filter plugins) virtual void BeginField ( int ) {} /// get next token virtual BYTE * GetToken () = 0; /// get next token comply escaping rules virtual BYTE * GetTokenEscaped () { return GetToken(); } /// calc codepoint length virtual int GetCodepointLength ( int iCode ) const noexcept = 0; /// get max codepoint length virtual int GetMaxCodepointLength () const noexcept = 0; /// enable indexing-time sentence boundary detection, and paragraph indexing virtual bool EnableSentenceIndexing ( CSphString & sError ); /// enable zone indexing virtual bool EnableZoneIndexing ( CSphString & sError ); /// enable tokenized multiform tracking virtual void EnableTokenizedMultiformTracking () {} /// get last token length, in codepoints virtual int GetLastTokenLen () const noexcept { return m_iLastTokenLen; } /// get last token boundary flag (true if there was a boundary before the token) virtual bool GetBoundary () const noexcept { return m_bTokenBoundary; } /// get byte offset of the last boundary character virtual int GetBoundaryOffset () const noexcept { return m_iBoundaryOffset; } /// was last token a special one? virtual bool WasTokenSpecial () const noexcept { return m_bWasSpecial; } virtual bool WasTokenSynonym () const noexcept { return m_bWasSynonym; } /// get amount of overshort keywords skipped before this token virtual int GetOvershortCount () const noexcept { return ( !m_bBlended && m_bBlendedPart ? 0 : m_iOvershortCount ); } /// get original tokenized multiform (if any); NULL means there was none virtual BYTE * GetTokenizedMultiform () noexcept { return nullptr; } /// was last token a part of multi-wordforms destination /// head parameter might be useful to distinguish between sequence of different multi-wordforms virtual bool WasTokenMultiformDestination ( bool & bHead, int & iDestCount ) const noexcept = 0; /// check whether this token is a generated morphological guess ESphTokenMorph GetTokenMorph() const noexcept { return m_eTokenMorph; } virtual bool TokenIsBlended () const noexcept { return m_bBlended; } virtual bool TokenIsBlendedPart () const noexcept { return m_bBlendedPart; } virtual int SkipBlended () { return 0; } public: /// spawn a clone of my own virtual TokenizerRefPtr_c Clone ( ESphTokenizerClone eMode ) const noexcept = 0; /// start buffer point of last token virtual const char * GetTokenStart () const noexcept = 0; /// end buffer point of last token (exclusive, ie. *GetTokenEnd() is already NOT part of a token!) virtual const char * GetTokenEnd () const noexcept = 0; /// current buffer ptr virtual const char * GetBufferPtr () const noexcept = 0; /// buffer end virtual const char * GetBufferEnd () const noexcept = 0; /// set new buffer ptr (must be within current bounds) virtual void SetBufferPtr ( const char * sNewPtr ) = 0; /// get settings hash virtual uint64_t GetSettingsFNV () const noexcept ; /// if I'm cloned in index, or any kind of query mode virtual bool IsQueryTok() const noexcept = 0; /// get (readonly) lowercaser const CSphLowercaser & GetLowercaser() const noexcept { assert ( m_pLC ); return *m_pLC; } /// set the phrase mode for precessing tokens virtual void SetPhraseMode ( bool bPhrase ) { m_bPhrase = bPhrase; } virtual bool IsPhraseMode () const noexcept { return m_bPhrase; } protected: virtual bool RemapCharacters ( const char * sConfig, DWORD uFlags, const char * sSource, bool bCanRemap, CSphString & sError ); virtual bool AddSpecialsSPZ ( const char * sSpecials, const char * sDirective, CSphString & sError ); protected: static const BYTE BLEND_TRIM_NONE = 1; static const BYTE BLEND_TRIM_HEAD = 2; static const BYTE BLEND_TRIM_TAIL = 4; static const BYTE BLEND_TRIM_BOTH = 8; static const BYTE BLEND_TRIM_ALL = 16; private: LowercaserRefcountedConstPtr m_pLC; ///< my lowercaser mutable std::atomic<CSphLowercaser*> m_pStagingLC {nullptr}; ///< preparing my lowercaser. protected: CSphLowercaser & StagingLowercaser(); LowercaserRefcountedConstPtr GetLC() const noexcept; void SetLC ( LowercaserRefcountedConstPtr rhs) ; protected: int m_iLastTokenLen = 0; ///< last token length, in codepoints bool m_bTokenBoundary = false; ///< last token boundary flag (true after boundary codepoint followed by separator) bool m_bBoundary = false; ///< boundary flag (true immediately after boundary codepoint) int m_iBoundaryOffset = 0; ///< boundary character offset (in bytes) bool m_bWasSpecial = false; ///< special token flag bool m_bWasSynonym = false; ///< last token is a synonym token int m_iOvershortCount = 0; ///< skipped overshort tokens count ESphTokenMorph m_eTokenMorph {SPH_TOKEN_MORPH_RAW}; ///< whether last token was a generated morphological guess bool m_bBlended = false; ///< whether last token (as in just returned from GetToken()) was blended bool m_bNonBlended = true; ///< internal, whether there were any normal chars in that blended token bool m_bBlendedPart = false; ///< whether last token is a normal subtoken of a blended token bool m_bBlendAdd = false; ///< whether we have more pending blended variants (of current accumulator) to return BYTE m_uBlendVariants {BLEND_TRIM_NONE}; ///< mask of blended variants as requested by blend_mode (see BLEND_TRIM_xxx flags) BYTE m_uBlendVariantsPending = 0;///< mask of pending blended variants (we clear bits as we return variants) bool m_bBlendSkipPure = false; ///< skip purely blended tokens bool m_bShortTokenFilter = false;///< short token filter flag bool m_bDetectSentences = false; ///< should we detect sentence boundaries? CSphTokenizerSettings m_tSettings; ///< tokenizer settings CSphSavedFile m_tSynFileInfo; ///< synonyms file info bool m_bPhrase = false; }; using TokenizerRefPtr_c = CSphRefcountedPtr<ISphTokenizer>; namespace Tokenizer { /// create a tokenizer using the given settings TokenizerRefPtr_c Create ( const CSphTokenizerSettings & tSettings, const CSphEmbeddedFiles * pFiles, FilenameBuilder_i * pFilenameBuilder, StrVec_t & dWarnings, CSphString & sError ); /// add multiform filter upon given tokenizer void AddToMultiformFilterTo ( TokenizerRefPtr_c& pTokenizer, const CSphMultiformContainer* pContainer ); /// add bigram filter upon given tokenizer void AddBigramFilterTo ( TokenizerRefPtr_c& pTokenizer, ESphBigram eBigramIndex, const CSphString& sBigramWords, CSphString& sError ); /// create a plugin filter /// sSspec is a library, name, and options specification string, eg "myplugins.dll:myfilter1:arg1=123" void AddPluginFilterTo ( TokenizerRefPtr_c& pTokenizer, const CSphString & sSpec, CSphString & sError ); namespace Detail { /// create UTF-8 tokenizer TokenizerRefPtr_c CreateUTF8Tokenizer ( bool bDefaultCharset = true ); /// create UTF-8 tokenizer with n-grams support (for CJK n-gram indexing) TokenizerRefPtr_c CreateUTF8NgramTokenizer ( bool bDefaultCharset = true ); } // namespace Detail } // namespace Tokenizer
11,261
C++
.h
204
53.127451
185
0.728059
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,220
multiform_container.h
manticoresoftware_manticoresearch/src/tokenizer/multiform_container.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // // that is internal header shared between tokenizer and dict implementations #pragma once #include "sphinxstd.h" struct CSphNormalForm { CSphString m_sForm; int m_iLengthCP; }; struct CSphMultiform { int m_iFileId; CSphTightVector<CSphNormalForm> m_dNormalForm; CSphTightVector<CSphString> m_dTokens; }; struct CSphMultiforms { int m_iMinTokens; int m_iMaxTokens; CSphVector<CSphMultiform*> m_pForms; // OPTIMIZE? blobify? }; struct CSphMultiformContainer { int m_iMaxTokens = 0; using CSphMultiformHash = CSphOrderedHash<CSphMultiforms*, CSphString, CSphStrHashFunc, 131072> ; CSphMultiformHash m_Hash; };
1,103
C++
.h
37
28.27027
98
0.787133
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,221
remap_range.h
manticoresoftware_manticoresearch/src/tokenizer/remap_range.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #pragma once /// lowercaser remap range struct CSphRemapRange { int m_iStart = -1; int m_iEnd = -1; int m_iRemapStart = -1; CSphRemapRange() = default; CSphRemapRange ( int iStart, int iEnd, int iRemapStart ) : m_iStart ( iStart ) , m_iEnd ( iEnd ) , m_iRemapStart ( iRemapStart ) {} explicit CSphRemapRange ( int iSingle ) : m_iStart ( iSingle ) , m_iEnd ( iSingle ) , m_iRemapStart ( iSingle ) {} };
901
C++
.h
30
28.266667
80
0.715438
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false